effect-durable-agent 0.1.0-alpha.26 → 0.1.0-alpha.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{delivery-o6sDIiwO.d.ts → delivery-C0aN3Oza.d.ts} +2 -2
- package/dist/domain/command-queues.d.ts +1 -1
- package/dist/domain/message-transcript.d.ts +36 -2
- package/dist/domain/reduced-state.d.ts +1 -1
- package/dist/domain/run-scheduling.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/{reduced-state-B5WxKSM5.d.ts → reduced-state-D50SR0qM.d.ts} +4 -391
- package/dist/services/compaction.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.d.ts +1 -1
- package/dist/services/runtime.js +0 -1
- package/dist/services/runtime.js.map +1 -1
- package/dist/services/session-query.d.ts +2 -2
- package/dist/services/session-query.js +5 -19
- package/dist/services/session-query.js.map +1 -1
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-store.js +2 -2
- package/dist/services/session-store.js.map +1 -1
- package/dist/services/sink-registry.d.ts +1 -1
- package/dist/services/span-names.d.ts +1 -1
- package/dist/services/span-names.js +0 -1
- package/dist/services/span-names.js.map +1 -1
- package/dist/{subscription-Dzr5LqPX.js → subscription-hkD4M3xp.js} +9 -4
- package/dist/subscription-hkD4M3xp.js.map +1 -0
- package/dist/testkit/layers.d.ts +1 -1
- package/dist/testkit/transcript.d.ts +1 -1
- package/dist/transcript.d.ts +2 -2
- package/dist/transcript.js +3 -3
- package/dist/websocket/events.d.ts +1 -1
- package/dist/websocket.d.ts +1 -1
- package/dist/websocket.js +1 -1
- package/dist/{window-read-DBf1Iktt.d.ts → window-read-BG8lxMVB.d.ts} +11 -2
- package/dist/{window-read-Bk7-4ALN.js → window-read-C8anZVdl.js} +21 -2
- package/dist/window-read-C8anZVdl.js.map +1 -0
- package/package.json +1 -1
- package/dist/subscription-Dzr5LqPX.js.map +0 -1
- package/dist/window-read-Bk7-4ALN.js.map +0 -1
|
@@ -2,7 +2,7 @@ import { g as SessionId } from "../core-BcimKMIv.js";
|
|
|
2
2
|
import { i as EDAAppEvents, o as EDASessionStore, s as EDASessionStoreError } from "../session-store-CWYZ29CV.js";
|
|
3
3
|
import { t as ModelResolver } from "../model-resolver-DUms5p6X.js";
|
|
4
4
|
import { r as EDAReducerRegistry } from "../reducer-registry-CPObI3cs.js";
|
|
5
|
-
import {
|
|
5
|
+
import { An as EDAPromptProjector, Ct as RunScheduler, Jt as EDASink, K as EDARuntime, dn as CompactionPolicy, on as CompactionExecutor, q as EDARuntimeConfig, rt as SessionCommandAdmissionError } from "../reduced-state-D50SR0qM.js";
|
|
6
6
|
import { i as EDAToolRegistryShape, t as EDAModelToolkit } from "../tool-registry-B_WE2ZwK.js";
|
|
7
7
|
import { t as IdGenerator } from "../id-generator-BKGoKjt-.js";
|
|
8
8
|
import { t as EDAKeepAlive } from "../keep-alive-_zFCUvt3.js";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { G as EDACommandTerminalEvent, J as EDARuntimeError, K as EDARuntime, W as CommittedCommandTerminalEvent, X as EDARuntimeSubmit, Y as EDARuntimeShape, q as EDARuntimeConfig } from "../reduced-state-
|
|
1
|
+
import { G as EDACommandTerminalEvent, J as EDARuntimeError, K as EDARuntime, W as CommittedCommandTerminalEvent, X as EDARuntimeSubmit, Y as EDARuntimeShape, q as EDARuntimeConfig } from "../reduced-state-D50SR0qM.js";
|
|
2
2
|
export { CommittedCommandTerminalEvent, EDACommandTerminalEvent, EDARuntime, EDARuntimeConfig, EDARuntimeError, EDARuntimeShape, EDARuntimeSubmit };
|
package/dist/services/runtime.js
CHANGED
|
@@ -75,7 +75,6 @@ const makeLiveRuntime = (config) => Effect.gen(function* () {
|
|
|
75
75
|
return yield* blockOnCommand(commandIdFromCommandAdmitted(admitted), admitted.position.seq);
|
|
76
76
|
}),
|
|
77
77
|
snapshot: () => query.snapshot(),
|
|
78
|
-
messages: () => query.messages(),
|
|
79
78
|
eventsAfter: (afterSeq) => query.eventsAfter(afterSeq),
|
|
80
79
|
readEventPage: (afterSeq, limit) => query.readEventPage(afterSeq, limit)
|
|
81
80
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/services/runtime.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport { EDACommand, GrantRunCommand } from \"../types/commands\";\nimport { CommandId, DurablePosition, SequenceNumber, durablePosition } from \"../types/core\";\nimport {\n CommandCompletedEvent,\n CommandFailedEvent,\n CommandCancelledEvent,\n ModelSelectionPayload,\n NonNegativeInt,\n SystemPromptText,\n} from \"../types/events\";\nimport type { PositionedEvent } from \"../types/events\";\nimport { SessionState } from \"./session-state\";\nimport type {\n EDASubmittable,\n SessionCommandAdmissionError,\n SessionStateShape,\n} from \"./session-state\";\nimport { CommittedDurableEvent } from \"./session-store\";\nimport { EDASessionQuery } from \"./session-query\";\nimport { annotateEdaSpan, committedBatchAttributes } from \"./tracing\";\nimport type { EDASessionQueryShape } from \"./session-query\";\n\n/** Configuration for one scoped session runtime instance. */\nexport const EDARuntimeConfig = Schema.Struct({\n modelSelection: ModelSelectionPayload,\n /** Maximum framework-owned tool calls one model run may execute before failing safely. */\n maxToolCallsPerRun: Schema.optionalKey(NonNegativeInt),\n systemPrompt: Schema.optionalKey(SystemPromptText),\n});\nexport type EDARuntimeConfig = typeof EDARuntimeConfig.Type;\n\n/** Public runtime error surface for command admission helpers. */\nexport type EDARuntimeError = SessionCommandAdmissionError;\n\n/** Command terminal events observed by blocking runtime helpers. */\nexport type EDACommandTerminalEvent =\n | CommandCompletedEvent\n | CommandFailedEvent\n | CommandCancelledEvent;\n\n/** Committed durable event narrowed to a command terminal boundary. */\nexport const CommittedCommandTerminalEvent = Schema.Struct({\n position: DurablePosition,\n event: Schema.Union([CommandCompletedEvent, CommandFailedEvent, CommandCancelledEvent]),\n});\nexport type CommittedCommandTerminalEvent = typeof CommittedCommandTerminalEvent.Type;\n\n/** Overloaded public submit API for single commands or ordered durable batches. */\nexport interface EDARuntimeSubmit {\n /** Submit one command and return its committed CommandAdmitted event. */\n (command: EDACommand): Effect.Effect<CommittedDurableEvent, EDARuntimeError>;\n /** Submit one ordered durable batch of commands and/or app events. */\n (\n input: ReadonlyArray<EDASubmittable>,\n ): Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDARuntimeError>;\n}\n\n/** Public facade exposed to hosts and route handlers for one live session runtime. */\nexport interface EDARuntimeShape {\n /** Trusted scheduler callback, deliberately separate from ordinary command admission. */\n /** Durable request reconciliation for trusted external schedulers. */\n readonly runRequestOutcome: EDASessionQueryShape[\"runRequestOutcome\"];\n readonly grantRun: (command: GrantRunCommand) => ReturnType<SessionStateShape[\"grantRun\"]>;\n /** Durable host wakeup callback; retry delivery without waiting for authorization. */\n readonly retryRunSchedulingDelivery: SessionStateShape[\"retryRunSchedulingDelivery\"];\n /** Submit commands and/or app durable events durably and wake the dispatch process if needed. */\n readonly submit: EDARuntimeSubmit;\n /** Block until the command reaches CommandCompleted, CommandFailed, or CommandCancelled. */\n readonly blockOnCommand: (\n commandId: CommandId,\n afterSeq?: SequenceNumber,\n ) => Effect.Effect<CommittedCommandTerminalEvent, EDARuntimeError>;\n /** Admit one command and block until that command reaches a terminal command boundary. */\n readonly submitAndBlock: (\n command: EDACommand,\n ) => Effect.Effect<CommittedCommandTerminalEvent, EDARuntimeError>;\n /** Read the authoritative live session snapshot. */\n readonly snapshot: EDASessionQueryShape[\"snapshot\"];\n /** Read durable user/assistant messages in committed order. */\n readonly messages: EDASessionQueryShape[\"messages\"];\n /** Backfill durable events after a committed sequence, then follow live events. */\n readonly eventsAfter: EDASessionQueryShape[\"eventsAfter\"];\n /** Read one bounded page of committed durable events plus the committed head. */\n readonly readEventPage: EDASessionQueryShape[\"readEventPage\"];\n}\n\n/** Top-level public facade for one effect-durable-agent session runtime. */\nexport class EDARuntime extends Context.Service<EDARuntime, EDARuntimeShape>()(\n \"@effect-durable-agent/EDARuntime\",\n) {\n static readonly Live = (config: EDARuntimeConfig) =>\n Layer.effect(EDARuntime, makeLiveRuntime(config));\n}\n\nconst makeLiveRuntime = (config: EDARuntimeConfig) =>\n Effect.gen(function* () {\n const sessionState = yield* SessionState;\n const query = yield* EDASessionQuery;\n\n const runInput = {\n modelSelection: config.modelSelection,\n ...(config.maxToolCallsPerRun === undefined\n ? {}\n : { maxToolCallsPerRun: config.maxToolCallsPerRun }),\n ...(config.systemPrompt === undefined ? {} : { systemPrompt: config.systemPrompt }),\n };\n yield* sessionState.start(runInput);\n\n const blockOnCommand = Effect.fn(function* (\n commandId: CommandId,\n afterSeq: SequenceNumber = SequenceNumber.make(0),\n ) {\n yield* annotateEdaSpan({ \"eda.command.id\": commandId, \"eda.seq.after\": afterSeq });\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const events = yield* query.eventsAfter(afterSeq);\n const terminal = yield* events.pipe(\n Stream.filter(isCommandTerminalFor(commandId)),\n Stream.take(1),\n Stream.map(toCommittedCommandTerminal),\n Stream.runCollect,\n Effect.map((events) => events[0]),\n );\n return terminal === undefined\n ? yield* Effect.die(new Error(\"Expected command terminal event\"))\n : terminal;\n }),\n );\n });\n\n const submit = Effect.fn(function* (input: EDACommand | ReadonlyArray<EDASubmittable>) {\n const items = Array.isArray(input) ? input : [input as EDACommand];\n yield* annotateEdaSpan({\n \"eda.command.submittable_count\": items.length,\n \"eda.command.count\": items.filter((item) => \"_tag\" in item).length,\n });\n const committed = Array.isArray(input)\n ? yield* sessionState.submitBatch(input)\n : [yield* sessionState.admitCommand(input as EDACommand)];\n yield* annotateEdaSpan(committedBatchAttributes(committed));\n return Array.isArray(input) ? committed : committed[0]!;\n }) as EDARuntimeSubmit;\n\n return {\n runRequestOutcome: query.runRequestOutcome,\n grantRun: (command: GrantRunCommand) => sessionState.grantRun(command, runInput),\n retryRunSchedulingDelivery: () => sessionState.retryRunSchedulingDelivery(),\n submit,\n blockOnCommand,\n submitAndBlock: Effect.fn(function* (command: EDACommand) {\n yield* annotateEdaSpan({\n \"eda.command.kind\": command._tag,\n \"eda.command.id\": command.commandId,\n \"eda.command.disposition\": \"disposition\" in command ? command.disposition : undefined,\n });\n const admitted = yield* sessionState.admitCommand(command);\n return yield* blockOnCommand(commandIdFromCommandAdmitted(admitted), admitted.position.seq);\n }),\n snapshot: () => query.snapshot(),\n messages: () => query.messages(),\n eventsAfter: (afterSeq: SequenceNumber) => query.eventsAfter(afterSeq),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n query.readEventPage(afterSeq, limit),\n };\n });\n\nconst isCommandTerminalFor =\n (commandId: CommandId) =>\n (\n event: PositionedEvent,\n ): event is PositionedEvent & { readonly event: EDACommandTerminalEvent } => {\n if (\n !Schema.is(CommandCompletedEvent)(event.event) &&\n !Schema.is(CommandFailedEvent)(event.event) &&\n !Schema.is(CommandCancelledEvent)(event.event)\n ) {\n return false;\n }\n return event.event.payload.commandId === commandId;\n };\n\nconst toCommittedCommandTerminal = (\n event: PositionedEvent & { readonly event: EDACommandTerminalEvent },\n): CommittedCommandTerminalEvent => ({\n position: durablePosition(event.position.seq),\n event: event.event,\n});\n\nconst commandIdFromCommandAdmitted = (committed: CommittedDurableEvent): CommandId => {\n const commandId =\n committed.event.type === \"CommandAdmitted\"\n ? committed.event.payload.command.commandId\n : undefined;\n if (commandId === undefined) {\n throw new Error(\"CommandAdmitted event is missing a framework commandId\");\n }\n return commandId;\n};\n"],"mappings":";;;;;;;;;;;;;AA6BA,MAAa,mBAAmB,OAAO,OAAO;CAC5C,gBAAgB;;CAEhB,oBAAoB,OAAO,YAAY,cAAc;CACrD,cAAc,OAAO,YAAY,gBAAgB;AACnD,CAAC;;AAaD,MAAa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,UAAU,MAAM,SAAS,oBACrB,UAAU,MAAM,QAAQ,QAAQ,YAChC,KAAA;CACN,IAAI,cAAc,KAAA,GAChB,MAAM,IAAI,MAAM,wDAAwD;CAE1E,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/services/runtime.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport { EDACommand, GrantRunCommand } from \"../types/commands\";\nimport { CommandId, DurablePosition, SequenceNumber, durablePosition } from \"../types/core\";\nimport {\n CommandCompletedEvent,\n CommandFailedEvent,\n CommandCancelledEvent,\n ModelSelectionPayload,\n NonNegativeInt,\n SystemPromptText,\n} from \"../types/events\";\nimport type { PositionedEvent } from \"../types/events\";\nimport { SessionState } from \"./session-state\";\nimport type {\n EDASubmittable,\n SessionCommandAdmissionError,\n SessionStateShape,\n} from \"./session-state\";\nimport { CommittedDurableEvent } from \"./session-store\";\nimport { EDASessionQuery } from \"./session-query\";\nimport { annotateEdaSpan, committedBatchAttributes } from \"./tracing\";\nimport type { EDASessionQueryShape } from \"./session-query\";\n\n/** Configuration for one scoped session runtime instance. */\nexport const EDARuntimeConfig = Schema.Struct({\n modelSelection: ModelSelectionPayload,\n /** Maximum framework-owned tool calls one model run may execute before failing safely. */\n maxToolCallsPerRun: Schema.optionalKey(NonNegativeInt),\n systemPrompt: Schema.optionalKey(SystemPromptText),\n});\nexport type EDARuntimeConfig = typeof EDARuntimeConfig.Type;\n\n/** Public runtime error surface for command admission helpers. */\nexport type EDARuntimeError = SessionCommandAdmissionError;\n\n/** Command terminal events observed by blocking runtime helpers. */\nexport type EDACommandTerminalEvent =\n | CommandCompletedEvent\n | CommandFailedEvent\n | CommandCancelledEvent;\n\n/** Committed durable event narrowed to a command terminal boundary. */\nexport const CommittedCommandTerminalEvent = Schema.Struct({\n position: DurablePosition,\n event: Schema.Union([CommandCompletedEvent, CommandFailedEvent, CommandCancelledEvent]),\n});\nexport type CommittedCommandTerminalEvent = typeof CommittedCommandTerminalEvent.Type;\n\n/** Overloaded public submit API for single commands or ordered durable batches. */\nexport interface EDARuntimeSubmit {\n /** Submit one command and return its committed CommandAdmitted event. */\n (command: EDACommand): Effect.Effect<CommittedDurableEvent, EDARuntimeError>;\n /** Submit one ordered durable batch of commands and/or app events. */\n (\n input: ReadonlyArray<EDASubmittable>,\n ): Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDARuntimeError>;\n}\n\n/** Public facade exposed to hosts and route handlers for one live session runtime. */\nexport interface EDARuntimeShape {\n /** Trusted scheduler callback, deliberately separate from ordinary command admission. */\n /** Durable request reconciliation for trusted external schedulers. */\n readonly runRequestOutcome: EDASessionQueryShape[\"runRequestOutcome\"];\n readonly grantRun: (command: GrantRunCommand) => ReturnType<SessionStateShape[\"grantRun\"]>;\n /** Durable host wakeup callback; retry delivery without waiting for authorization. */\n readonly retryRunSchedulingDelivery: SessionStateShape[\"retryRunSchedulingDelivery\"];\n /** Submit commands and/or app durable events durably and wake the dispatch process if needed. */\n readonly submit: EDARuntimeSubmit;\n /** Block until the command reaches CommandCompleted, CommandFailed, or CommandCancelled. */\n readonly blockOnCommand: (\n commandId: CommandId,\n afterSeq?: SequenceNumber,\n ) => Effect.Effect<CommittedCommandTerminalEvent, EDARuntimeError>;\n /** Admit one command and block until that command reaches a terminal command boundary. */\n readonly submitAndBlock: (\n command: EDACommand,\n ) => Effect.Effect<CommittedCommandTerminalEvent, EDARuntimeError>;\n /** Read the authoritative live session snapshot. */\n readonly snapshot: EDASessionQueryShape[\"snapshot\"];\n /** Backfill durable events after a committed sequence, then follow live events. */\n readonly eventsAfter: EDASessionQueryShape[\"eventsAfter\"];\n /** Read one bounded page of committed durable events plus the committed head. */\n readonly readEventPage: EDASessionQueryShape[\"readEventPage\"];\n}\n\n/** Top-level public facade for one effect-durable-agent session runtime. */\nexport class EDARuntime extends Context.Service<EDARuntime, EDARuntimeShape>()(\n \"@effect-durable-agent/EDARuntime\",\n) {\n static readonly Live = (config: EDARuntimeConfig) =>\n Layer.effect(EDARuntime, makeLiveRuntime(config));\n}\n\nconst makeLiveRuntime = (config: EDARuntimeConfig) =>\n Effect.gen(function* () {\n const sessionState = yield* SessionState;\n const query = yield* EDASessionQuery;\n\n const runInput = {\n modelSelection: config.modelSelection,\n ...(config.maxToolCallsPerRun === undefined\n ? {}\n : { maxToolCallsPerRun: config.maxToolCallsPerRun }),\n ...(config.systemPrompt === undefined ? {} : { systemPrompt: config.systemPrompt }),\n };\n yield* sessionState.start(runInput);\n\n const blockOnCommand = Effect.fn(function* (\n commandId: CommandId,\n afterSeq: SequenceNumber = SequenceNumber.make(0),\n ) {\n yield* annotateEdaSpan({ \"eda.command.id\": commandId, \"eda.seq.after\": afterSeq });\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const events = yield* query.eventsAfter(afterSeq);\n const terminal = yield* events.pipe(\n Stream.filter(isCommandTerminalFor(commandId)),\n Stream.take(1),\n Stream.map(toCommittedCommandTerminal),\n Stream.runCollect,\n Effect.map((events) => events[0]),\n );\n return terminal === undefined\n ? yield* Effect.die(new Error(\"Expected command terminal event\"))\n : terminal;\n }),\n );\n });\n\n const submit = Effect.fn(function* (input: EDACommand | ReadonlyArray<EDASubmittable>) {\n const items = Array.isArray(input) ? input : [input as EDACommand];\n yield* annotateEdaSpan({\n \"eda.command.submittable_count\": items.length,\n \"eda.command.count\": items.filter((item) => \"_tag\" in item).length,\n });\n const committed = Array.isArray(input)\n ? yield* sessionState.submitBatch(input)\n : [yield* sessionState.admitCommand(input as EDACommand)];\n yield* annotateEdaSpan(committedBatchAttributes(committed));\n return Array.isArray(input) ? committed : committed[0]!;\n }) as EDARuntimeSubmit;\n\n return {\n runRequestOutcome: query.runRequestOutcome,\n grantRun: (command: GrantRunCommand) => sessionState.grantRun(command, runInput),\n retryRunSchedulingDelivery: () => sessionState.retryRunSchedulingDelivery(),\n submit,\n blockOnCommand,\n submitAndBlock: Effect.fn(function* (command: EDACommand) {\n yield* annotateEdaSpan({\n \"eda.command.kind\": command._tag,\n \"eda.command.id\": command.commandId,\n \"eda.command.disposition\": \"disposition\" in command ? command.disposition : undefined,\n });\n const admitted = yield* sessionState.admitCommand(command);\n return yield* blockOnCommand(commandIdFromCommandAdmitted(admitted), admitted.position.seq);\n }),\n snapshot: () => query.snapshot(),\n eventsAfter: (afterSeq: SequenceNumber) => query.eventsAfter(afterSeq),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n query.readEventPage(afterSeq, limit),\n };\n });\n\nconst isCommandTerminalFor =\n (commandId: CommandId) =>\n (\n event: PositionedEvent,\n ): event is PositionedEvent & { readonly event: EDACommandTerminalEvent } => {\n if (\n !Schema.is(CommandCompletedEvent)(event.event) &&\n !Schema.is(CommandFailedEvent)(event.event) &&\n !Schema.is(CommandCancelledEvent)(event.event)\n ) {\n return false;\n }\n return event.event.payload.commandId === commandId;\n };\n\nconst toCommittedCommandTerminal = (\n event: PositionedEvent & { readonly event: EDACommandTerminalEvent },\n): CommittedCommandTerminalEvent => ({\n position: durablePosition(event.position.seq),\n event: event.event,\n});\n\nconst commandIdFromCommandAdmitted = (committed: CommittedDurableEvent): CommandId => {\n const commandId =\n committed.event.type === \"CommandAdmitted\"\n ? committed.event.payload.command.commandId\n : undefined;\n if (commandId === undefined) {\n throw new Error(\"CommandAdmitted event is missing a framework commandId\");\n }\n return commandId;\n};\n"],"mappings":";;;;;;;;;;;;;AA6BA,MAAa,mBAAmB,OAAO,OAAO;CAC5C,gBAAgB;;CAEhB,oBAAoB,OAAO,YAAY,cAAc;CACrD,cAAc,OAAO,YAAY,gBAAgB;AACnD,CAAC;;AAaD,MAAa,gCAAgC,OAAO,OAAO;CACzD,UAAU;CACV,OAAO,OAAO,MAAM;EAAC;EAAuB;EAAoB;CAAqB,CAAC;AACxF,CAAC;;AAyCD,IAAa,aAAb,MAAa,mBAAmB,QA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
|
|
1
|
-
import { $ as
|
|
2
|
-
export {
|
|
1
|
+
import { $ as EDASessionQueryShape, Q as EDASessionQuery, Z as EDASessionEventPage, et as EDASessionSnapshot } from "../reduced-state-D50SR0qM.js";
|
|
2
|
+
export { EDASessionEventPage, EDASessionQuery, EDASessionQueryShape, EDASessionSnapshot };
|
|
@@ -2,9 +2,8 @@ import { SequenceNumber } from "../types/core.js";
|
|
|
2
2
|
import { d as PositionedEvent } from "../envelope-BCzKUq_z.js";
|
|
3
3
|
import { qn as durableEventEnvelope } from "../durable-CD__3ztN.js";
|
|
4
4
|
import { m as LiveEventBus, u as SessionState } from "../session-state-BW0l2aNk.js";
|
|
5
|
-
import {
|
|
5
|
+
import { ReducedStateSchema } from "../domain/reduced-state-schema.js";
|
|
6
6
|
import { EDASessionStore } from "./session-store.js";
|
|
7
|
-
import { durableMessageTranscript } from "../domain/message-transcript.js";
|
|
8
7
|
import { annotateEdaSpan } from "./tracing.js";
|
|
9
8
|
import * as Context from "effect/Context";
|
|
10
9
|
import * as Effect from "effect/Effect";
|
|
@@ -13,21 +12,10 @@ import * as Schema from "effect/Schema";
|
|
|
13
12
|
import * as Stream from "effect/Stream";
|
|
14
13
|
import * as PubSub from "effect/PubSub";
|
|
15
14
|
//#region src/services/session-query.ts
|
|
16
|
-
/**
|
|
17
|
-
const DurableTranscriptMessages = Schema.Array(Schema.Union([
|
|
18
|
-
QueryMessageRecordSchema.members[1],
|
|
19
|
-
QueryMessageRecordSchema.members[3],
|
|
20
|
-
QueryMessageRecordSchema.members[4],
|
|
21
|
-
Schema.Struct({
|
|
22
|
-
...QueryMessageRecordSchema.members[2].fields,
|
|
23
|
-
consumedSeq: SequenceNumber
|
|
24
|
-
})
|
|
25
|
-
]));
|
|
26
|
-
/** Authoritative live snapshot for one EDA session plus its derived durable transcript. */
|
|
15
|
+
/** Authoritative live snapshot for one EDA session: reduced state plus app reducer states. */
|
|
27
16
|
const EDASessionSnapshot = Schema.Struct({
|
|
28
17
|
state: ReducedStateSchema,
|
|
29
|
-
reducerStates: Schema.ReadonlyMap(Schema.String, Schema.Unknown)
|
|
30
|
-
messages: DurableTranscriptMessages
|
|
18
|
+
reducerStates: Schema.ReadonlyMap(Schema.String, Schema.Unknown)
|
|
31
19
|
});
|
|
32
20
|
/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */
|
|
33
21
|
var EDASessionQuery = class EDASessionQuery extends Context.Service()("@effect-durable-agent/EDASessionQuery") {
|
|
@@ -39,8 +27,7 @@ var EDASessionQuery = class EDASessionQuery extends Context.Service()("@effect-d
|
|
|
39
27
|
const data = yield* sessionState.snapshotData();
|
|
40
28
|
return {
|
|
41
29
|
state: data.reduced,
|
|
42
|
-
reducerStates: data.reducerStates
|
|
43
|
-
messages: durableMessageTranscript(data.reduced)
|
|
30
|
+
reducerStates: data.reducerStates
|
|
44
31
|
};
|
|
45
32
|
});
|
|
46
33
|
return {
|
|
@@ -87,7 +74,6 @@ var EDASessionQuery = class EDASessionQuery extends Context.Service()("@effect-d
|
|
|
87
74
|
return outcome;
|
|
88
75
|
}),
|
|
89
76
|
snapshot: () => snapshot,
|
|
90
|
-
messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),
|
|
91
77
|
eventsAfter: (afterSeq) => Effect.gen(function* () {
|
|
92
78
|
const live = yield* liveBus.subscribeQueue();
|
|
93
79
|
const replayHead = (yield* sessionState.snapshot()).lastSeq;
|
|
@@ -150,6 +136,6 @@ const uniquePositionedEvents = (events) => {
|
|
|
150
136
|
return output;
|
|
151
137
|
};
|
|
152
138
|
//#endregion
|
|
153
|
-
export {
|
|
139
|
+
export { EDASessionQuery, EDASessionSnapshot };
|
|
154
140
|
|
|
155
141
|
//# sourceMappingURL=session-query.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-query.js","names":[],"sources":["../../src/services/session-query.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\nimport { ReducedStateSchema, QueryMessageRecordSchema } from \"../domain/reduced-state-schema\";\nimport { durableEventEnvelope } from \"../types/events/durable\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { durableMessageTranscript } from \"../domain/message-transcript\";\nimport type { DurableTranscriptMessage } from \"../domain/message-transcript\";\nimport { RunRequestOutcome } from \"../domain/run-scheduling\";\nimport { effectDurableAgentNamespace } from \"../types/events\";\nimport { type RunRequestId, SequenceNumber } from \"../types/core\";\nimport { PositionedEvent } from \"../types/events\";\nimport { EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { SessionState } from \"./session-state\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Reconnect-safe transcript query preserving the existing structured-clone Prompt parts. */\nexport const DurableTranscriptMessages = Schema.Array(\n Schema.Union([\n QueryMessageRecordSchema.members[1],\n QueryMessageRecordSchema.members[3],\n QueryMessageRecordSchema.members[4],\n Schema.Struct({ ...QueryMessageRecordSchema.members[2].fields, consumedSeq: SequenceNumber }),\n ]),\n);\n/** Authoritative live snapshot for one EDA session plus its derived durable transcript. */\nexport const EDASessionSnapshot = Schema.Struct({\n state: ReducedStateSchema,\n reducerStates: Schema.ReadonlyMap(Schema.String, Schema.Unknown),\n messages: DurableTranscriptMessages,\n});\nexport type EDASessionSnapshot = typeof EDASessionSnapshot.Type;\n\n/** Read-only query facade over authoritative live state and reconnect-safe event streams. */\nexport interface EDASessionQueryShape {\n /** Reconcile one request against committed facts, including after reducer history pruning. */\n readonly runRequestOutcome: (\n requestId: RunRequestId,\n ) => Effect.Effect<RunRequestOutcome, EDASessionStoreError>;\n /** Read the authoritative live state and derive its durable transcript. */\n readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;\n /** Read durable user/assistant messages in committed sequence order from the live snapshot. */\n readonly messages: () => Effect.Effect<\n ReadonlyArray<DurableTranscriptMessage>,\n EDASessionStoreError\n >;\n /** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Effect.Effect<\n Stream.Stream<PositionedEvent, EDASessionStoreError>,\n EDASessionStoreError,\n Scope.Scope\n >;\n /** Read one bounded committed durable slice after `afterSeq` plus the committed head. */\n readonly readEventPage: (\n afterSeq: SequenceNumber,\n limit: number,\n ) => Effect.Effect<EDASessionEventPage, EDASessionStoreError>;\n}\n\n/** Bounded committed durable event page for pull-based host delivery. */\nexport interface EDASessionEventPage {\n readonly events: ReadonlyArray<PositionedEvent>;\n readonly head: SequenceNumber;\n}\n\n/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */\nexport class EDASessionQuery extends Context.Service<EDASessionQuery, EDASessionQueryShape>()(\n \"@effect-durable-agent/EDASessionQuery\",\n) {\n static readonly Live = Layer.effect(\n EDASessionQuery,\n Effect.gen(function* () {\n const store = yield* EDASessionStore;\n const liveBus = yield* LiveEventBus;\n const sessionState = yield* SessionState;\n\n const snapshot = Effect.gen(function* () {\n const data = yield* sessionState.snapshotData();\n return {\n state: data.reduced,\n reducerStates: data.reducerStates,\n messages: durableMessageTranscript(data.reduced),\n } satisfies EDASessionSnapshot;\n });\n\n return {\n runRequestOutcome: Effect.fn(\"agent.run.request.outcome\")(function* (\n requestId: RunRequestId,\n ) {\n const head = (yield* sessionState.snapshot()).lastSeq;\n let outcome: RunRequestOutcome = { _tag: \"Unknown\" };\n yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((entry) => entry.position.seq <= head),\n Stream.runForEach((entry) =>\n Effect.sync(() => {\n const event = entry.event;\n if (event.namespace !== effectDurableAgentNamespace) return;\n switch (event.type) {\n case \"RunSchedulingRequested\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Waiting\" };\n break;\n case \"RunSchedulingInvalidated\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Invalidated\" };\n break;\n case \"RunSchedulingGranted\": {\n const grant = event.payload;\n if (grant.requestId === requestId)\n outcome = { _tag: \"Granted\", runId: grant.runId, status: \"Running\" };\n break;\n }\n case \"RunCompleted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Completed\" };\n break;\n case \"RunFailed\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Failed\" };\n break;\n case \"RunInterrupted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Interrupted\" };\n break;\n }\n }),\n ),\n );\n return outcome;\n }),\n snapshot: () => snapshot,\n messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),\n eventsAfter: (afterSeq: SequenceNumber) =>\n Effect.gen(function* () {\n const live = yield* liveBus.subscribeQueue();\n const replayHead = (yield* sessionState.snapshot()).lastSeq;\n // TODO(backpressure): this runCollect drains the store stream eagerly and buffers the\n // whole durable reconnect prefix, defeating host-level paged replay/backpressure for\n // slow clients. Stream this prefix into the live follow stream instead.\n const replay = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= replayHead),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n const activeTurnReplay = yield* liveBus.activeTurnReplay();\n const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter(\n (event) => shouldEmitLiveEvent(event, replayHead),\n );\n const reconnectPrefix: ReadonlyArray<PositionedEvent> = Array.from(\n uniquePositionedEvents([...replay, ...activeTurnReplay.events, ...pendingLive]),\n ).sort(comparePositionedEvents);\n yield* annotateEdaSpan({\n \"eda.seq.after\": afterSeq,\n \"eda.seq.head\": replayHead,\n \"eda.replay.events\": replay.length,\n \"eda.live.active_turn_events\": activeTurnReplay.events.length,\n \"eda.live.active_turn_overflowed\": activeTurnReplay.overflowed,\n \"eda.live.buffered_events\": pendingLive.length,\n });\n const follow: Stream.Stream<PositionedEvent> = Stream.fromEffectRepeat(\n PubSub.take(live),\n ).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));\n return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));\n }).pipe(\n Effect.withSpan(\"agent.events.follow\", {\n attributes: { \"eda.seq.after\": afterSeq },\n }),\n ),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n Effect.gen(function* () {\n const head = (yield* sessionState.snapshot()).lastSeq;\n if (limit <= 0 || afterSeq >= head) {\n return { events: [], head } satisfies EDASessionEventPage;\n }\n const events = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= head),\n Stream.take(limit),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n return { events, head } satisfies EDASessionEventPage;\n }).pipe(\n Effect.withSpan(\"agent.events.page\", {\n attributes: { \"eda.seq.after\": afterSeq, \"eda.page.limit\": limit },\n }),\n ),\n };\n }),\n );\n}\n\nconst shouldEmitLiveEvent = (event: PositionedEvent, replayHead: SequenceNumber): boolean =>\n event.event.durability === \"ephemeral\" || event.position.seq > replayHead;\n\nconst comparePositionedEvents = (left: PositionedEvent, right: PositionedEvent): number => {\n const seq = left.position.seq - right.position.seq;\n return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;\n};\n\nconst uniquePositionedEvents = (\n events: ReadonlyArray<PositionedEvent>,\n): ReadonlyArray<PositionedEvent> => {\n const seen = new Set<string>();\n const output: PositionedEvent[] = [];\n for (const event of events) {\n const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n output.push(event);\n }\n return output;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,MAAa,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E,MAAM,2BAA2B,MAAuB,UAAmC;CACzF,MAAM,MAAM,KAAK,SAAS,MAAM,MAAM,SAAS;CAC/C,OAAO,QAAQ,IAAI,KAAK,SAAS,SAAS,MAAM,SAAS,SAAS;AACpE;AAEA,MAAM,0BACJ,WACmC;CACnC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAA4B,CAAC;CACnC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,MAAM,GAAG,MAAM,SAAS,IAAI,GAAG,MAAM,SAAS,OAAO,GAAG,MAAM,MAAM;EAC1E,IAAI,KAAK,IAAI,GAAG,GACd;EAEF,KAAK,IAAI,GAAG;EACZ,OAAO,KAAK,KAAK;CACnB;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"session-query.js","names":[],"sources":["../../src/services/session-query.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\nimport { ReducedStateSchema } from \"../domain/reduced-state-schema\";\nimport { durableEventEnvelope } from \"../types/events/durable\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { RunRequestOutcome } from \"../domain/run-scheduling\";\nimport { effectDurableAgentNamespace } from \"../types/events\";\nimport { type RunRequestId, SequenceNumber } from \"../types/core\";\nimport { PositionedEvent } from \"../types/events\";\nimport { EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { SessionState } from \"./session-state\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Authoritative live snapshot for one EDA session: reduced state plus app reducer states. */\nexport const EDASessionSnapshot = Schema.Struct({\n state: ReducedStateSchema,\n reducerStates: Schema.ReadonlyMap(Schema.String, Schema.Unknown),\n});\nexport type EDASessionSnapshot = typeof EDASessionSnapshot.Type;\n\n/** Read-only query facade over authoritative live state and reconnect-safe event streams. */\nexport interface EDASessionQueryShape {\n /** Reconcile one request against committed facts, including after reducer history pruning. */\n readonly runRequestOutcome: (\n requestId: RunRequestId,\n ) => Effect.Effect<RunRequestOutcome, EDASessionStoreError>;\n /** Read the authoritative live state and app reducer states. */\n readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;\n /** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Effect.Effect<\n Stream.Stream<PositionedEvent, EDASessionStoreError>,\n EDASessionStoreError,\n Scope.Scope\n >;\n /** Read one bounded committed durable slice after `afterSeq` plus the committed head. */\n readonly readEventPage: (\n afterSeq: SequenceNumber,\n limit: number,\n ) => Effect.Effect<EDASessionEventPage, EDASessionStoreError>;\n}\n\n/** Bounded committed durable event page for pull-based host delivery. */\nexport interface EDASessionEventPage {\n readonly events: ReadonlyArray<PositionedEvent>;\n readonly head: SequenceNumber;\n}\n\n/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */\nexport class EDASessionQuery extends Context.Service<EDASessionQuery, EDASessionQueryShape>()(\n \"@effect-durable-agent/EDASessionQuery\",\n) {\n static readonly Live = Layer.effect(\n EDASessionQuery,\n Effect.gen(function* () {\n const store = yield* EDASessionStore;\n const liveBus = yield* LiveEventBus;\n const sessionState = yield* SessionState;\n\n const snapshot = Effect.gen(function* () {\n const data = yield* sessionState.snapshotData();\n return {\n state: data.reduced,\n reducerStates: data.reducerStates,\n } satisfies EDASessionSnapshot;\n });\n\n return {\n runRequestOutcome: Effect.fn(\"agent.run.request.outcome\")(function* (\n requestId: RunRequestId,\n ) {\n const head = (yield* sessionState.snapshot()).lastSeq;\n let outcome: RunRequestOutcome = { _tag: \"Unknown\" };\n yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((entry) => entry.position.seq <= head),\n Stream.runForEach((entry) =>\n Effect.sync(() => {\n const event = entry.event;\n if (event.namespace !== effectDurableAgentNamespace) return;\n switch (event.type) {\n case \"RunSchedulingRequested\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Waiting\" };\n break;\n case \"RunSchedulingInvalidated\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Invalidated\" };\n break;\n case \"RunSchedulingGranted\": {\n const grant = event.payload;\n if (grant.requestId === requestId)\n outcome = { _tag: \"Granted\", runId: grant.runId, status: \"Running\" };\n break;\n }\n case \"RunCompleted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Completed\" };\n break;\n case \"RunFailed\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Failed\" };\n break;\n case \"RunInterrupted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Interrupted\" };\n break;\n }\n }),\n ),\n );\n return outcome;\n }),\n snapshot: () => snapshot,\n eventsAfter: (afterSeq: SequenceNumber) =>\n Effect.gen(function* () {\n const live = yield* liveBus.subscribeQueue();\n const replayHead = (yield* sessionState.snapshot()).lastSeq;\n // TODO(backpressure): this runCollect drains the store stream eagerly and buffers the\n // whole durable reconnect prefix, defeating host-level paged replay/backpressure for\n // slow clients. Stream this prefix into the live follow stream instead.\n const replay = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= replayHead),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n const activeTurnReplay = yield* liveBus.activeTurnReplay();\n const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter(\n (event) => shouldEmitLiveEvent(event, replayHead),\n );\n const reconnectPrefix: ReadonlyArray<PositionedEvent> = Array.from(\n uniquePositionedEvents([...replay, ...activeTurnReplay.events, ...pendingLive]),\n ).sort(comparePositionedEvents);\n yield* annotateEdaSpan({\n \"eda.seq.after\": afterSeq,\n \"eda.seq.head\": replayHead,\n \"eda.replay.events\": replay.length,\n \"eda.live.active_turn_events\": activeTurnReplay.events.length,\n \"eda.live.active_turn_overflowed\": activeTurnReplay.overflowed,\n \"eda.live.buffered_events\": pendingLive.length,\n });\n const follow: Stream.Stream<PositionedEvent> = Stream.fromEffectRepeat(\n PubSub.take(live),\n ).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));\n return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));\n }).pipe(\n Effect.withSpan(\"agent.events.follow\", {\n attributes: { \"eda.seq.after\": afterSeq },\n }),\n ),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n Effect.gen(function* () {\n const head = (yield* sessionState.snapshot()).lastSeq;\n if (limit <= 0 || afterSeq >= head) {\n return { events: [], head } satisfies EDASessionEventPage;\n }\n const events = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= head),\n Stream.take(limit),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n return { events, head } satisfies EDASessionEventPage;\n }).pipe(\n Effect.withSpan(\"agent.events.page\", {\n attributes: { \"eda.seq.after\": afterSeq, \"eda.page.limit\": limit },\n }),\n ),\n };\n }),\n );\n}\n\nconst shouldEmitLiveEvent = (event: PositionedEvent, replayHead: SequenceNumber): boolean =>\n event.event.durability === \"ephemeral\" || event.position.seq > replayHead;\n\nconst comparePositionedEvents = (left: PositionedEvent, right: PositionedEvent): number => {\n const seq = left.position.seq - right.position.seq;\n return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;\n};\n\nconst uniquePositionedEvents = (\n events: ReadonlyArray<PositionedEvent>,\n): ReadonlyArray<PositionedEvent> => {\n const seen = new Set<string>();\n const output: PositionedEvent[] = [];\n for (const event of events) {\n const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;\n if (seen.has(key)) {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,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,MAAM,GAAG,MAAM,SAAS,IAAI,GAAG,MAAM,SAAS,OAAO,GAAG,MAAM,MAAM;EAC1E,IAAI,KAAK,IAAI,GAAG,GACd;EAEF,KAAK,IAAI,GAAG;EACZ,OAAO,KAAK,KAAK;CACnB;CACA,OAAO;AACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _t as SessionStateShape, at as SessionCommandCompleted, ct as SessionCommandResult, dt as SessionForkedCommand, ft as SessionNoRunnableCommand, gt as SessionStateError, ht as SessionState, it as SessionCommandCancelled, lt as SessionDrainProcessed, mt as SessionRunInput, nt as SessionCommandAdmissionConflict, ot as SessionCommandFailed, pt as SessionNoRunnableReason, rt as SessionCommandAdmissionError, st as SessionCommandOutcome, tt as EDASubmittable, ut as SessionDrainResult, vt as SessionStateSnapshotData } from "../reduced-state-D50SR0qM.js";
|
|
2
2
|
export { EDASubmittable, SessionCommandAdmissionConflict, SessionCommandAdmissionError, SessionCommandCancelled, SessionCommandCompleted, SessionCommandFailed, SessionCommandOutcome, SessionCommandResult, SessionDrainProcessed, SessionDrainResult, SessionForkedCommand, SessionNoRunnableCommand, SessionNoRunnableReason, SessionRunInput, SessionState, SessionStateError, SessionStateShape, SessionStateSnapshotData };
|
|
@@ -5,7 +5,7 @@ import { CompactionSummaryArtifact } from "../domain/context-projection.js";
|
|
|
5
5
|
import { m as makeTranscriptDefinition, p as emptyTranscriptMappings } from "../interpreter-BdRoYrfL.js";
|
|
6
6
|
import { T as TranscriptLogIncarnation } from "../records-DWKEjuqb.js";
|
|
7
7
|
import { a as maintainTranscripts, i as initialTranscriptState, r as inMemoryTranscriptWindowSource } from "../in-memory-IgxnTbGb.js";
|
|
8
|
-
import {
|
|
8
|
+
import { a as EDATranscriptStore, n as inactiveTranscriptWindow, r as readTranscriptWindowFrom } from "../window-read-C8anZVdl.js";
|
|
9
9
|
import * as Context from "effect/Context";
|
|
10
10
|
import * as Effect from "effect/Effect";
|
|
11
11
|
import * as Layer from "effect/Layer";
|
|
@@ -189,7 +189,7 @@ const makeInMemoryTranscriptStore = (data) => ({
|
|
|
189
189
|
readTranscriptWindow: (selector, limits) => Effect.gen(function* () {
|
|
190
190
|
const { transcript } = yield* Ref.get(data);
|
|
191
191
|
const source = inMemoryTranscriptWindowSource(transcript);
|
|
192
|
-
if (source === void 0) return
|
|
192
|
+
if (source === void 0) return inactiveTranscriptWindow(transcript.incarnation, transcript.config.current.version, transcript.versions.find((version) => version.meta.role === "building")?.meta);
|
|
193
193
|
const window = readTranscriptWindowFrom(source, selector, limits);
|
|
194
194
|
return Result.isSuccess(window) ? window.success : yield* window.failure;
|
|
195
195
|
}),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-store.js","names":[],"sources":["../../src/services/session-store.ts"],"sourcesContent":["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 * as SchemaGetter from \"effect/SchemaGetter\";\nimport type * as SchemaAST from \"effect/SchemaAST\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n DecodedDurableEvent,\n decodeDurableEventSync,\n durableEventEnvelope,\n} from \"../types/events/durable\";\n\nimport { type CommandIdempotencyKey } from \"../types/commands\";\nimport { CompactionSummaryArtifact } from \"../domain/context-projection\";\nimport {\n CommandId,\n DurablePosition,\n SequenceNumber,\n SessionId,\n SummaryId,\n durablePosition,\n} from \"../types/core\";\nimport {\n DurableEventEnvelope,\n commandAdmittedEventType,\n contextRebasedEventType,\n summaryCreatedEventType,\n} from \"../types/events\";\nimport { decodeRetainingExcess } from \"../types/events/internal\";\nimport {\n initialTranscriptState,\n inMemoryTranscriptWindowSource,\n maintainTranscripts,\n type InMemoryTranscriptState,\n} from \"../transcript/in-memory\";\nimport { emptyTranscriptMappings, makeTranscriptDefinition } from \"../transcript/mapping\";\nimport { TranscriptLogIncarnation } from \"../transcript/records\";\nimport {\n EDATranscriptStore,\n type EDATranscriptStoreShape,\n type TranscriptMaintenanceConfig,\n} from \"../transcript/store\";\nimport { buildingTranscriptWindow, readTranscriptWindowFrom } from \"../transcript/window-read\";\n\nexport type CommittedDurableEvent<E = DecodedDurableEvent> = {\n readonly position: typeof DurablePosition.Type;\n readonly event: E;\n};\n\n/** A durable event after the store has assigned its replay position. */\nexport const CommittedDurableEvent: Schema.Codec<\n CommittedDurableEvent,\n {\n readonly position: typeof DurablePosition.Encoded;\n readonly event: typeof DurableEventEnvelope.Encoded;\n },\n never,\n never\n> = Schema.Struct({\n position: DurablePosition,\n event: DurableEventEnvelope.pipe(\n Schema.decodeTo(Schema.declare<DecodedDurableEvent>(Schema.is(DecodedDurableEvent)), {\n decode: SchemaGetter.transform(decodeDurableEventSync),\n encode: SchemaGetter.transform(durableEventEnvelope),\n }),\n ),\n});\n/**\n * Store-level failure surfaced by durable append, replay, and hydration APIs.\n *\n * The error intentionally stays storage-semantic rather than SQL-specific so\n * framework services can treat SQL-backed hosts, in-memory tests, and future adapters\n * as the same durability boundary.\n */\nexport class EDASessionStoreError extends Schema.TaggedError<EDASessionStoreError>()(\n \"EDASessionStoreError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** True when a Cause contains an escaped durable-store failure. */\nexport const hasEDASessionStoreError = (cause: Cause.Cause<unknown>): boolean =>\n cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError,\n );\n\n/**\n * One logical event to persist in the durable session log.\n *\n * Store adapters may split large logical payload fields into sidecar rows after\n * the event insert assigns `seq`, but callers still provide one fat event.\n */\nexport const DurableAppendEntry = Schema.Struct({\n event: DurableEventEnvelope,\n});\nexport type DurableAppendEntry = typeof DurableAppendEntry.Type;\n\n/**\n * Ordered durable append intent. Adapters assign positions in entry order.\n *\n * This is the single write shape exposed to framework services. It avoids raw\n * SQL and public transaction callbacks while still expressing the full atomic\n * transition EDA needs for events, normalized bodies, and metadata.\n */\nexport const DurableAppendBatch = Schema.Struct({\n entries: Schema.Array(DurableAppendEntry),\n});\nexport type DurableAppendBatch = typeof DurableAppendBatch.Type;\n\n/** Durable reducer checkpoint row used to hydrate framework and app projections cheaply. */\nexport interface EDAReducerCheckpoint {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Input for writing one durable reducer checkpoint. */\nexport interface SaveReducerCheckpointInput {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Indexed command-admission lookup used for idempotent ingress. */\nexport const FindCommandAdmissionInput = Schema.Struct({\n commandId: Schema.optionalKey(CommandId),\n idempotencyKey: Schema.optionalKey(Schema.String),\n});\n/** Typed command-admission lookup accepted by the semantic store port. */\nexport interface FindCommandAdmissionInput {\n readonly commandId?: CommandId;\n readonly idempotencyKey?: CommandIdempotencyKey;\n}\n\n/** Semantic durable store contract for one EDA session. */\nexport interface EDASessionStoreShape {\n /**\n * Append durable logical events atomically, preserving input order.\n *\n * Implementations must be idempotent by `eventId`: duplicates return the\n * original committed position and do not advance the durable head. Live publish\n * remains outside the store and is owned by `SessionState` after this succeeds.\n */\n readonly append: (\n batch: DurableAppendBatch,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Replay committed durable events with `seq > afterSeq`. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Stream.Stream<CommittedDurableEvent, EDASessionStoreError>;\n /** Load committed durable events by exact sequence number for checkpoint pointer hydration. */\n readonly loadCommittedEventsBySeq: (\n seqs: ReadonlyArray<SequenceNumber>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Lookup an admitted command without replaying the full journal. */\n readonly findCommandAdmission: (\n input: FindCommandAdmissionInput,\n ) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;\n /** Load one compacted summary artifact body by id, if it has been saved. */\n readonly loadSummaryArtifact: (\n summaryId: SummaryId,\n ) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;\n /** Load one framework or app reducer checkpoint, if it has been saved. */\n readonly loadReducerCheckpoint: (\n name: string,\n ) => Effect.Effect<EDAReducerCheckpoint | undefined, EDASessionStoreError>;\n /** Persist one framework or app reducer checkpoint as a derived cache. */\n readonly saveReducerCheckpoint: (\n checkpoint: SaveReducerCheckpointInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Persist a reducer checkpoint snapshot atomically across framework and app reducers. */\n readonly saveReducerCheckpoints: (\n checkpoints: ReadonlyArray<SaveReducerCheckpointInput>,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * SQL-agnostic durable storage port for one EDA session.\n *\n * Framework services depend on this semantic port rather than raw SQL. Host\n * adapters own physical tables and synchronous transaction mechanics; callers\n * only express durable append/replay/lookup intent.\n */\nexport class EDASessionStore extends Context.Service<EDASessionStore, EDASessionStoreShape>()(\n \"@effect-durable-agent/EDASessionStore\",\n) {\n /**\n * Deterministic in-memory implementation used by runtime and recovery tests.\n *\n * It also provides `EDATranscriptStore`, maintaining the transcript inside the same append\n * critical section. Without `options.transcript` it maintains the definition with no host\n * mappings.\n */\n static readonly InMemory = (sessionId: SessionId, options?: InMemoryStoreOptions) =>\n inMemoryStoreLayer(sessionId, () => [], options);\n\n /** In-memory store seeded with a durable prefix; its transcript is built from that prefix. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n options?: InMemoryStoreOptions,\n ) => inMemoryStoreLayer(sessionId, () => seedCommittedEvents(sessionId, events), options);\n}\n\n/** Construction options for the in-memory store. */\nexport interface InMemoryStoreOptions {\n /** Transcript definitions to maintain; defaults to the definition with no host mappings. */\n readonly transcript?: TranscriptMaintenanceConfig;\n}\n\nconst inMemoryStoreLayer = (\n sessionId: SessionId,\n seed: () => ReadonlyArray<CommittedDurableEvent>,\n options: InMemoryStoreOptions | undefined,\n) =>\n Layer.effectContext(\n Effect.gen(function* () {\n const committed = seed();\n const config = options?.transcript ?? {\n current: yield* makeTranscriptDefinition(emptyTranscriptMappings).pipe(Effect.orDie),\n };\n const data = yield* Ref.make<InMemoryStoreData>({\n committed,\n summaries: summariesFromCommittedEvents(committed),\n reducerCheckpoints: new Map(),\n transcript: initialTranscriptState(\n TranscriptLogIncarnation.make(`memory:${sessionId}`),\n config,\n committed,\n ),\n });\n return Context.make(EDASessionStore, makeInMemoryStore(sessionId, data)).pipe(\n Context.add(EDATranscriptStore, makeInMemoryTranscriptStore(data)),\n );\n }),\n );\n\ninterface InMemoryStoreData {\n readonly committed: ReadonlyArray<CommittedDurableEvent>;\n readonly summaries: ReadonlyMap<SummaryId, CompactionSummaryArtifact>;\n readonly reducerCheckpoints: ReadonlyMap<string, EDAReducerCheckpoint>;\n readonly transcript: InMemoryTranscriptState;\n}\n\nconst seedCommittedEvents = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n): ReadonlyArray<CommittedDurableEvent> => {\n const seen = new Set<string>();\n return events.map((event, index) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n if (seen.has(event.eventId)) {\n throw new Error(`Duplicate seed eventId ${event.eventId}`);\n }\n seen.add(event.eventId);\n return {\n position: durablePosition(SequenceNumber.make(index + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n });\n};\n\nconst summariesFromCommittedEvents = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<SummaryId, CompactionSummaryArtifact> => {\n const summaries = new Map<SummaryId, CompactionSummaryArtifact>();\n for (const { event } of events) {\n if (event.type !== summaryCreatedEventType) {\n continue;\n }\n const payload = event.payload;\n if (payload.summary !== undefined) {\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n summaries.set(summary.summaryId, summary);\n }\n }\n return summaries;\n};\n\n/**\n * Build an in-memory store with one `Ref.modify` append critical section.\n *\n * The fake models the semantic atomicity of the production adapter without\n * exposing SQL, so runtime tests exercise the same store contract.\n */\nconst makeInMemoryStore = (\n sessionId: SessionId,\n data: Ref.Ref<InMemoryStoreData>,\n): EDASessionStoreShape => {\n const ensureSession = (event: DurableEventEnvelope): Effect.Effect<void, EDASessionStoreError> =>\n Effect.gen(function* () {\n if (event.sessionId === sessionId) {\n return;\n }\n return yield* new EDASessionStoreError({\n message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}`,\n });\n });\n\n const append = (batch: DurableAppendBatch) =>\n Effect.gen(function* () {\n for (const entry of batch.entries) {\n yield* ensureSession(entry.event);\n }\n\n return yield* Ref.modify(data, (current) => {\n const nextEntries: Array<CommittedDurableEvent> = [...current.committed];\n const nextSummaries = new Map(current.summaries);\n const committedEvents: Array<CommittedDurableEvent> = [];\n const appended: Array<CommittedDurableEvent> = [];\n\n for (const entry of batch.entries) {\n const { event } = entry;\n const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);\n if (existing !== undefined) {\n committedEvents.push(existing);\n continue;\n }\n\n const committed: CommittedDurableEvent = {\n position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n nextEntries.push(committed);\n committedEvents.push(committed);\n appended.push(committed);\n\n if (committed.event.type === summaryCreatedEventType) {\n const payload = committed.event.payload;\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n if (payload.summaryId !== undefined && summary.summaryId !== payload.summaryId) {\n throw new Error(\"SummaryCreated summaryId does not match summary payload\");\n }\n nextSummaries.set(summary.summaryId, summary);\n }\n\n if (committed.event.type === contextRebasedEventType) {\n const payload = committed.event.payload;\n if (payload.summaryId === undefined || !nextSummaries.has(payload.summaryId)) {\n throw new Error(\n `ContextRebased references unknown summaryId ${String(payload.summaryId)}`,\n );\n }\n }\n }\n\n return [\n committedEvents,\n {\n committed: nextEntries,\n summaries: nextSummaries,\n reducerCheckpoints: current.reducerCheckpoints,\n // Projection staging commits with the events; a projection failure freezes only\n // the failed version and never fails the append.\n transcript:\n appended.length === 0\n ? current.transcript\n : maintainTranscripts(current.transcript, appended),\n },\n ];\n });\n });\n\n return {\n append,\n eventsAfter: (afterSeq) =>\n Stream.fromIterableEffect(\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)),\n ),\n ),\n loadCommittedEventsBySeq: (seqs) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => {\n const requested = new Set(seqs.map((seq) => Number(seq)));\n return committed.filter((entry) => requested.has(Number(entry.position.seq)));\n }),\n ),\n findCommandAdmission: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) =>\n committed.find((entry) => commandAdmissionMatches(entry, input)),\n ),\n ),\n loadSummaryArtifact: (summaryId) =>\n Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),\n loadReducerCheckpoint: (name) =>\n Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),\n saveReducerCheckpoint: (checkpoint) =>\n Ref.update(data, (current) => ({\n ...current,\n reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint),\n })),\n saveReducerCheckpoints: (checkpoints) =>\n Ref.update(data, (current) => {\n const reducerCheckpoints = new Map(current.reducerCheckpoints);\n for (const checkpoint of checkpoints) {\n reducerCheckpoints.set(checkpoint.name, checkpoint);\n }\n return { ...current, reducerCheckpoints };\n }),\n };\n};\n\n/** Transcript reads over the in-memory store's active version, at one `Ref` snapshot. */\nconst makeInMemoryTranscriptStore = (\n data: Ref.Ref<InMemoryStoreData>,\n): EDATranscriptStoreShape => ({\n readTranscriptWindow: (selector, limits) =>\n Effect.gen(function* () {\n const { transcript } = yield* Ref.get(data);\n const source = inMemoryTranscriptWindowSource(transcript);\n if (source === undefined) {\n return buildingTranscriptWindow(transcript.incarnation, transcript.config.current.version);\n }\n const window = readTranscriptWindowFrom(source, selector, limits);\n return Result.isSuccess(window) ? window.success : yield* window.failure;\n }),\n readTranscriptMeta: Ref.get(data).pipe(\n Effect.map(({ transcript }) => transcript.versions.map((version) => version.meta)),\n ),\n});\n\nconst commandAdmissionMatches = (\n entry: CommittedDurableEvent,\n input: FindCommandAdmissionInput,\n): boolean => {\n if (entry.event.type !== commandAdmittedEventType) {\n return false;\n }\n const admitted = entry.event.payload.command;\n if (admitted === undefined) {\n return false;\n }\n if (input.idempotencyKey !== undefined && admitted.idempotencyKey === input.idempotencyKey) {\n return true;\n }\n return input.commandId !== undefined && admitted.commandId === input.commandId;\n};\n\n/** App schemas are registered once; known namespaces fail at the store boundary when malformed. */\nexport type EDAAppEvents = Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\nconst eventNamespaces = (ast: SchemaAST.AST): ReadonlyArray<string> => {\n if (ast._tag === \"Union\") return ast.types.flatMap(eventNamespaces);\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/** Attach the app decoder to every event-returning store operation without changing storage bytes. */\nexport const registerAppEvents = (\n store: EDASessionStoreShape,\n schema: EDAAppEvents,\n): EDASessionStoreShape => {\n const namespaces = new Set(eventNamespaces(schema.ast));\n const decode = decodeRetainingExcess(schema);\n const envelopeKey = (event: DurableEventEnvelope): string =>\n JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));\n const decodeEntry = (\n entry: CommittedDurableEvent,\n prepared?: ReadonlyMap<string, DurableEventEnvelope>,\n ): CommittedDurableEvent => {\n if (entry.event.namespace !== \"__foreign\" || !namespaces.has(entry.event.envelope.namespace))\n return entry;\n return {\n ...entry,\n event: {\n ...entry.event,\n decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope),\n },\n };\n };\n const decodeEntryEffect = (entry: CommittedDurableEvent) =>\n Effect.try({\n try: () => decodeEntry(entry),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const decodeEntries = (entries: ReadonlyArray<CommittedDurableEvent>) =>\n Effect.forEach(entries, decodeEntryEffect);\n return {\n ...store,\n append: (batch) =>\n Effect.gen(function* () {\n // Idempotent append can return different retained bytes for the same event id.\n // Reuse a prepared decode only when the complete persisted envelope matches.\n const prepared = yield* Effect.try({\n try: () => {\n const decoded = new Map<string, DurableEventEnvelope>();\n for (const { event } of batch.entries) {\n if (!namespaces.has(event.namespace)) continue;\n const key = envelopeKey(event);\n if (!decoded.has(key)) {\n decoded.set(key, decode(event));\n }\n }\n return decoded;\n },\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const committed = yield* store.append(batch);\n return yield* Effect.forEach(committed, (entry) =>\n Effect.try({\n try: () => decodeEntry(entry, prepared),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n }),\n );\n }),\n eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),\n loadCommittedEventsBySeq: (seqs) =>\n store.loadCommittedEventsBySeq(seqs).pipe(Effect.flatMap(decodeEntries)),\n findCommandAdmission: (input) =>\n store\n .findCommandAdmission(input)\n .pipe(\n Effect.flatMap((entry) =>\n entry === undefined ? Effect.succeed(undefined) : decodeEntryEffect(entry),\n ),\n ),\n };\n};\n\n/** Narrow an already decoded fact from one schema, without decoding its payload again. */\nexport const selectCommittedEvent = <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n entry: CommittedDurableEvent,\n): CommittedDurableEvent<E> | undefined => {\n const event =\n entry.event.namespace === \"__foreign\"\n ? (entry.event.decoded ?? entry.event.envelope)\n : entry.event;\n return Schema.is(schema)(event) ? { position: entry.position, event } : undefined;\n};\n\n/** Typed journal read available to tools and application services without private SQL access. */\nexport const queryCommittedEvents = <E extends DurableEventEnvelope>(\n store: EDASessionStoreShape,\n schema: Schema.Codec<E, unknown, never, never>,\n options: { readonly afterSeq?: SequenceNumber; readonly limit?: number } = {},\n): Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError> =>\n store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(\n Stream.map((entry) => selectCommittedEvent(schema, entry)),\n Stream.filter((entry): entry is CommittedDurableEvent<E> => entry !== undefined),\n Stream.take(options.limit ?? Number.MAX_SAFE_INTEGER),\n Stream.runCollect,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuDA,MAAa,wBAQT,OAAO,OAAO;CAChB,UAAU;CACV,OAAO,qBAAqB,KAC1B,OAAO,SAAS,OAAO,QAA6B,OAAO,GAAG,mBAAmB,CAAC,GAAG;EACnF,QAAQ,aAAa,UAAU,sBAAsB;EACrD,QAAQ,aAAa,UAAU,oBAAoB;CACrD,CAAC,CACH;AACF,CAAC;;;;;;;;AAQD,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;;AAGH,MAAa,2BAA2B,UACtC,MAAM,QAAQ,MACX,WAAW,MAAM,aAAa,MAAM,KAAK,OAAO,iBAAiB,oBACpE;;;;;;;AAQF,MAAa,qBAAqB,OAAO,OAAO,EAC9C,OAAO,qBACT,CAAC;;;;;;;;AAUD,MAAa,qBAAqB,OAAO,OAAO,EAC9C,SAAS,OAAO,MAAM,kBAAkB,EAC1C,CAAC;;AAsBD,MAAa,4BAA4B,O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,YAAY,eAAe,KAAK,CAAC,CAAC,CAAC,CAAC,KAC5D,OAAO,KAAK,UAAU,qBAAqB,QAAQ,KAAK,CAAC,GACzD,OAAO,QAAQ,UAA6C,UAAU,KAAA,CAAS,GAC/E,OAAO,KAAK,QAAQ,SAAS,OAAO,gBAAgB,GACpD,OAAO,UACT"}
|
|
1
|
+
{"version":3,"file":"session-store.js","names":[],"sources":["../../src/services/session-store.ts"],"sourcesContent":["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 * as SchemaGetter from \"effect/SchemaGetter\";\nimport type * as SchemaAST from \"effect/SchemaAST\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n DecodedDurableEvent,\n decodeDurableEventSync,\n durableEventEnvelope,\n} from \"../types/events/durable\";\n\nimport { type CommandIdempotencyKey } from \"../types/commands\";\nimport { CompactionSummaryArtifact } from \"../domain/context-projection\";\nimport {\n CommandId,\n DurablePosition,\n SequenceNumber,\n SessionId,\n SummaryId,\n durablePosition,\n} from \"../types/core\";\nimport {\n DurableEventEnvelope,\n commandAdmittedEventType,\n contextRebasedEventType,\n summaryCreatedEventType,\n} from \"../types/events\";\nimport { decodeRetainingExcess } from \"../types/events/internal\";\nimport {\n initialTranscriptState,\n inMemoryTranscriptWindowSource,\n maintainTranscripts,\n type InMemoryTranscriptState,\n} from \"../transcript/in-memory\";\nimport { emptyTranscriptMappings, makeTranscriptDefinition } from \"../transcript/mapping\";\nimport { TranscriptLogIncarnation } from \"../transcript/records\";\nimport {\n EDATranscriptStore,\n type EDATranscriptStoreShape,\n type TranscriptMaintenanceConfig,\n} from \"../transcript/store\";\nimport { inactiveTranscriptWindow, readTranscriptWindowFrom } from \"../transcript/window-read\";\n\nexport type CommittedDurableEvent<E = DecodedDurableEvent> = {\n readonly position: typeof DurablePosition.Type;\n readonly event: E;\n};\n\n/** A durable event after the store has assigned its replay position. */\nexport const CommittedDurableEvent: Schema.Codec<\n CommittedDurableEvent,\n {\n readonly position: typeof DurablePosition.Encoded;\n readonly event: typeof DurableEventEnvelope.Encoded;\n },\n never,\n never\n> = Schema.Struct({\n position: DurablePosition,\n event: DurableEventEnvelope.pipe(\n Schema.decodeTo(Schema.declare<DecodedDurableEvent>(Schema.is(DecodedDurableEvent)), {\n decode: SchemaGetter.transform(decodeDurableEventSync),\n encode: SchemaGetter.transform(durableEventEnvelope),\n }),\n ),\n});\n/**\n * Store-level failure surfaced by durable append, replay, and hydration APIs.\n *\n * The error intentionally stays storage-semantic rather than SQL-specific so\n * framework services can treat SQL-backed hosts, in-memory tests, and future adapters\n * as the same durability boundary.\n */\nexport class EDASessionStoreError extends Schema.TaggedError<EDASessionStoreError>()(\n \"EDASessionStoreError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** True when a Cause contains an escaped durable-store failure. */\nexport const hasEDASessionStoreError = (cause: Cause.Cause<unknown>): boolean =>\n cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError,\n );\n\n/**\n * One logical event to persist in the durable session log.\n *\n * Store adapters may split large logical payload fields into sidecar rows after\n * the event insert assigns `seq`, but callers still provide one fat event.\n */\nexport const DurableAppendEntry = Schema.Struct({\n event: DurableEventEnvelope,\n});\nexport type DurableAppendEntry = typeof DurableAppendEntry.Type;\n\n/**\n * Ordered durable append intent. Adapters assign positions in entry order.\n *\n * This is the single write shape exposed to framework services. It avoids raw\n * SQL and public transaction callbacks while still expressing the full atomic\n * transition EDA needs for events, normalized bodies, and metadata.\n */\nexport const DurableAppendBatch = Schema.Struct({\n entries: Schema.Array(DurableAppendEntry),\n});\nexport type DurableAppendBatch = typeof DurableAppendBatch.Type;\n\n/** Durable reducer checkpoint row used to hydrate framework and app projections cheaply. */\nexport interface EDAReducerCheckpoint {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Input for writing one durable reducer checkpoint. */\nexport interface SaveReducerCheckpointInput {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Indexed command-admission lookup used for idempotent ingress. */\nexport const FindCommandAdmissionInput = Schema.Struct({\n commandId: Schema.optionalKey(CommandId),\n idempotencyKey: Schema.optionalKey(Schema.String),\n});\n/** Typed command-admission lookup accepted by the semantic store port. */\nexport interface FindCommandAdmissionInput {\n readonly commandId?: CommandId;\n readonly idempotencyKey?: CommandIdempotencyKey;\n}\n\n/** Semantic durable store contract for one EDA session. */\nexport interface EDASessionStoreShape {\n /**\n * Append durable logical events atomically, preserving input order.\n *\n * Implementations must be idempotent by `eventId`: duplicates return the\n * original committed position and do not advance the durable head. Live publish\n * remains outside the store and is owned by `SessionState` after this succeeds.\n */\n readonly append: (\n batch: DurableAppendBatch,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Replay committed durable events with `seq > afterSeq`. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Stream.Stream<CommittedDurableEvent, EDASessionStoreError>;\n /** Load committed durable events by exact sequence number for checkpoint pointer hydration. */\n readonly loadCommittedEventsBySeq: (\n seqs: ReadonlyArray<SequenceNumber>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Lookup an admitted command without replaying the full journal. */\n readonly findCommandAdmission: (\n input: FindCommandAdmissionInput,\n ) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;\n /** Load one compacted summary artifact body by id, if it has been saved. */\n readonly loadSummaryArtifact: (\n summaryId: SummaryId,\n ) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;\n /** Load one framework or app reducer checkpoint, if it has been saved. */\n readonly loadReducerCheckpoint: (\n name: string,\n ) => Effect.Effect<EDAReducerCheckpoint | undefined, EDASessionStoreError>;\n /** Persist one framework or app reducer checkpoint as a derived cache. */\n readonly saveReducerCheckpoint: (\n checkpoint: SaveReducerCheckpointInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Persist a reducer checkpoint snapshot atomically across framework and app reducers. */\n readonly saveReducerCheckpoints: (\n checkpoints: ReadonlyArray<SaveReducerCheckpointInput>,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * SQL-agnostic durable storage port for one EDA session.\n *\n * Framework services depend on this semantic port rather than raw SQL. Host\n * adapters own physical tables and synchronous transaction mechanics; callers\n * only express durable append/replay/lookup intent.\n */\nexport class EDASessionStore extends Context.Service<EDASessionStore, EDASessionStoreShape>()(\n \"@effect-durable-agent/EDASessionStore\",\n) {\n /**\n * Deterministic in-memory implementation used by runtime and recovery tests.\n *\n * It also provides `EDATranscriptStore`, maintaining the transcript inside the same append\n * critical section. Without `options.transcript` it maintains the definition with no host\n * mappings.\n */\n static readonly InMemory = (sessionId: SessionId, options?: InMemoryStoreOptions) =>\n inMemoryStoreLayer(sessionId, () => [], options);\n\n /** In-memory store seeded with a durable prefix; its transcript is built from that prefix. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n options?: InMemoryStoreOptions,\n ) => inMemoryStoreLayer(sessionId, () => seedCommittedEvents(sessionId, events), options);\n}\n\n/** Construction options for the in-memory store. */\nexport interface InMemoryStoreOptions {\n /** Transcript definitions to maintain; defaults to the definition with no host mappings. */\n readonly transcript?: TranscriptMaintenanceConfig;\n}\n\nconst inMemoryStoreLayer = (\n sessionId: SessionId,\n seed: () => ReadonlyArray<CommittedDurableEvent>,\n options: InMemoryStoreOptions | undefined,\n) =>\n Layer.effectContext(\n Effect.gen(function* () {\n const committed = seed();\n const config = options?.transcript ?? {\n current: yield* makeTranscriptDefinition(emptyTranscriptMappings).pipe(Effect.orDie),\n };\n const data = yield* Ref.make<InMemoryStoreData>({\n committed,\n summaries: summariesFromCommittedEvents(committed),\n reducerCheckpoints: new Map(),\n transcript: initialTranscriptState(\n TranscriptLogIncarnation.make(`memory:${sessionId}`),\n config,\n committed,\n ),\n });\n return Context.make(EDASessionStore, makeInMemoryStore(sessionId, data)).pipe(\n Context.add(EDATranscriptStore, makeInMemoryTranscriptStore(data)),\n );\n }),\n );\n\ninterface InMemoryStoreData {\n readonly committed: ReadonlyArray<CommittedDurableEvent>;\n readonly summaries: ReadonlyMap<SummaryId, CompactionSummaryArtifact>;\n readonly reducerCheckpoints: ReadonlyMap<string, EDAReducerCheckpoint>;\n readonly transcript: InMemoryTranscriptState;\n}\n\nconst seedCommittedEvents = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n): ReadonlyArray<CommittedDurableEvent> => {\n const seen = new Set<string>();\n return events.map((event, index) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n if (seen.has(event.eventId)) {\n throw new Error(`Duplicate seed eventId ${event.eventId}`);\n }\n seen.add(event.eventId);\n return {\n position: durablePosition(SequenceNumber.make(index + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n });\n};\n\nconst summariesFromCommittedEvents = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<SummaryId, CompactionSummaryArtifact> => {\n const summaries = new Map<SummaryId, CompactionSummaryArtifact>();\n for (const { event } of events) {\n if (event.type !== summaryCreatedEventType) {\n continue;\n }\n const payload = event.payload;\n if (payload.summary !== undefined) {\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n summaries.set(summary.summaryId, summary);\n }\n }\n return summaries;\n};\n\n/**\n * Build an in-memory store with one `Ref.modify` append critical section.\n *\n * The fake models the semantic atomicity of the production adapter without\n * exposing SQL, so runtime tests exercise the same store contract.\n */\nconst makeInMemoryStore = (\n sessionId: SessionId,\n data: Ref.Ref<InMemoryStoreData>,\n): EDASessionStoreShape => {\n const ensureSession = (event: DurableEventEnvelope): Effect.Effect<void, EDASessionStoreError> =>\n Effect.gen(function* () {\n if (event.sessionId === sessionId) {\n return;\n }\n return yield* new EDASessionStoreError({\n message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}`,\n });\n });\n\n const append = (batch: DurableAppendBatch) =>\n Effect.gen(function* () {\n for (const entry of batch.entries) {\n yield* ensureSession(entry.event);\n }\n\n return yield* Ref.modify(data, (current) => {\n const nextEntries: Array<CommittedDurableEvent> = [...current.committed];\n const nextSummaries = new Map(current.summaries);\n const committedEvents: Array<CommittedDurableEvent> = [];\n const appended: Array<CommittedDurableEvent> = [];\n\n for (const entry of batch.entries) {\n const { event } = entry;\n const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);\n if (existing !== undefined) {\n committedEvents.push(existing);\n continue;\n }\n\n const committed: CommittedDurableEvent = {\n position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n nextEntries.push(committed);\n committedEvents.push(committed);\n appended.push(committed);\n\n if (committed.event.type === summaryCreatedEventType) {\n const payload = committed.event.payload;\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n if (payload.summaryId !== undefined && summary.summaryId !== payload.summaryId) {\n throw new Error(\"SummaryCreated summaryId does not match summary payload\");\n }\n nextSummaries.set(summary.summaryId, summary);\n }\n\n if (committed.event.type === contextRebasedEventType) {\n const payload = committed.event.payload;\n if (payload.summaryId === undefined || !nextSummaries.has(payload.summaryId)) {\n throw new Error(\n `ContextRebased references unknown summaryId ${String(payload.summaryId)}`,\n );\n }\n }\n }\n\n return [\n committedEvents,\n {\n committed: nextEntries,\n summaries: nextSummaries,\n reducerCheckpoints: current.reducerCheckpoints,\n // Projection staging commits with the events; a projection failure freezes only\n // the failed version and never fails the append.\n transcript:\n appended.length === 0\n ? current.transcript\n : maintainTranscripts(current.transcript, appended),\n },\n ];\n });\n });\n\n return {\n append,\n eventsAfter: (afterSeq) =>\n Stream.fromIterableEffect(\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)),\n ),\n ),\n loadCommittedEventsBySeq: (seqs) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => {\n const requested = new Set(seqs.map((seq) => Number(seq)));\n return committed.filter((entry) => requested.has(Number(entry.position.seq)));\n }),\n ),\n findCommandAdmission: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) =>\n committed.find((entry) => commandAdmissionMatches(entry, input)),\n ),\n ),\n loadSummaryArtifact: (summaryId) =>\n Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),\n loadReducerCheckpoint: (name) =>\n Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),\n saveReducerCheckpoint: (checkpoint) =>\n Ref.update(data, (current) => ({\n ...current,\n reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint),\n })),\n saveReducerCheckpoints: (checkpoints) =>\n Ref.update(data, (current) => {\n const reducerCheckpoints = new Map(current.reducerCheckpoints);\n for (const checkpoint of checkpoints) {\n reducerCheckpoints.set(checkpoint.name, checkpoint);\n }\n return { ...current, reducerCheckpoints };\n }),\n };\n};\n\n/** Transcript reads over the in-memory store's active version, at one `Ref` snapshot. */\nconst makeInMemoryTranscriptStore = (\n data: Ref.Ref<InMemoryStoreData>,\n): EDATranscriptStoreShape => ({\n readTranscriptWindow: (selector, limits) =>\n Effect.gen(function* () {\n const { transcript } = yield* Ref.get(data);\n const source = inMemoryTranscriptWindowSource(transcript);\n if (source === undefined) {\n return inactiveTranscriptWindow(\n transcript.incarnation,\n transcript.config.current.version,\n transcript.versions.find((version) => version.meta.role === \"building\")?.meta,\n );\n }\n const window = readTranscriptWindowFrom(source, selector, limits);\n return Result.isSuccess(window) ? window.success : yield* window.failure;\n }),\n readTranscriptMeta: Ref.get(data).pipe(\n Effect.map(({ transcript }) => transcript.versions.map((version) => version.meta)),\n ),\n});\n\nconst commandAdmissionMatches = (\n entry: CommittedDurableEvent,\n input: FindCommandAdmissionInput,\n): boolean => {\n if (entry.event.type !== commandAdmittedEventType) {\n return false;\n }\n const admitted = entry.event.payload.command;\n if (admitted === undefined) {\n return false;\n }\n if (input.idempotencyKey !== undefined && admitted.idempotencyKey === input.idempotencyKey) {\n return true;\n }\n return input.commandId !== undefined && admitted.commandId === input.commandId;\n};\n\n/** App schemas are registered once; known namespaces fail at the store boundary when malformed. */\nexport type EDAAppEvents = Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\nconst eventNamespaces = (ast: SchemaAST.AST): ReadonlyArray<string> => {\n if (ast._tag === \"Union\") return ast.types.flatMap(eventNamespaces);\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/** Attach the app decoder to every event-returning store operation without changing storage bytes. */\nexport const registerAppEvents = (\n store: EDASessionStoreShape,\n schema: EDAAppEvents,\n): EDASessionStoreShape => {\n const namespaces = new Set(eventNamespaces(schema.ast));\n const decode = decodeRetainingExcess(schema);\n const envelopeKey = (event: DurableEventEnvelope): string =>\n JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));\n const decodeEntry = (\n entry: CommittedDurableEvent,\n prepared?: ReadonlyMap<string, DurableEventEnvelope>,\n ): CommittedDurableEvent => {\n if (entry.event.namespace !== \"__foreign\" || !namespaces.has(entry.event.envelope.namespace))\n return entry;\n return {\n ...entry,\n event: {\n ...entry.event,\n decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope),\n },\n };\n };\n const decodeEntryEffect = (entry: CommittedDurableEvent) =>\n Effect.try({\n try: () => decodeEntry(entry),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const decodeEntries = (entries: ReadonlyArray<CommittedDurableEvent>) =>\n Effect.forEach(entries, decodeEntryEffect);\n return {\n ...store,\n append: (batch) =>\n Effect.gen(function* () {\n // Idempotent append can return different retained bytes for the same event id.\n // Reuse a prepared decode only when the complete persisted envelope matches.\n const prepared = yield* Effect.try({\n try: () => {\n const decoded = new Map<string, DurableEventEnvelope>();\n for (const { event } of batch.entries) {\n if (!namespaces.has(event.namespace)) continue;\n const key = envelopeKey(event);\n if (!decoded.has(key)) {\n decoded.set(key, decode(event));\n }\n }\n return decoded;\n },\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const committed = yield* store.append(batch);\n return yield* Effect.forEach(committed, (entry) =>\n Effect.try({\n try: () => decodeEntry(entry, prepared),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n }),\n );\n }),\n eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),\n loadCommittedEventsBySeq: (seqs) =>\n store.loadCommittedEventsBySeq(seqs).pipe(Effect.flatMap(decodeEntries)),\n findCommandAdmission: (input) =>\n store\n .findCommandAdmission(input)\n .pipe(\n Effect.flatMap((entry) =>\n entry === undefined ? Effect.succeed(undefined) : decodeEntryEffect(entry),\n ),\n ),\n };\n};\n\n/** Narrow an already decoded fact from one schema, without decoding its payload again. */\nexport const selectCommittedEvent = <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n entry: CommittedDurableEvent,\n): CommittedDurableEvent<E> | undefined => {\n const event =\n entry.event.namespace === \"__foreign\"\n ? (entry.event.decoded ?? entry.event.envelope)\n : entry.event;\n return Schema.is(schema)(event) ? { position: entry.position, event } : undefined;\n};\n\n/** Typed journal read available to tools and application services without private SQL access. */\nexport const queryCommittedEvents = <E extends DurableEventEnvelope>(\n store: EDASessionStoreShape,\n schema: Schema.Codec<E, unknown, never, never>,\n options: { readonly afterSeq?: SequenceNumber; readonly limit?: number } = {},\n): Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError> =>\n store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(\n Stream.map((entry) => selectCommittedEvent(schema, entry)),\n Stream.filter((entry): entry is CommittedDurableEvent<E> => entry !== undefined),\n Stream.take(options.limit ?? Number.MAX_SAFE_INTEGER),\n Stream.runCollect,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuDA,MAAa,wBAQT,OAAO,OAAO;CAChB,UAAU;CACV,OAAO,qBAAqB,KAC1B,OAAO,SAAS,OAAO,QAA6B,OAAO,GAAG,mBAAmB,CAAC,GAAG;EACnF,QAAQ,aAAa,UAAU,sBAAsB;EACrD,QAAQ,aAAa,UAAU,oBAAoB;CACrD,CAAC,CACH;AACF,CAAC;;;;;;;;AAQD,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;;AAGH,MAAa,2BAA2B,UACtC,MAAM,QAAQ,MACX,WAAW,MAAM,aAAa,MAAM,KAAK,OAAO,iBAAiB,oBACpE;;;;;;;AAQF,MAAa,qBAAqB,OAAO,OAAO,EAC9C,OAAO,qBACT,CAAC;;;;;;;;AAUD,MAAa,qBAAqB,OAAO,OAAO,EAC9C,SAAS,OAAO,MAAM,kBAAkB,EAC1C,CAAC;;AAsBD,MAAa,4BAA4B,OAAO,OAAO;CACrD,WAAW,OAAO,YAAY,SAAS;CACvC,gBAAgB,OAAO,YAAY,OAAO,MAAM;AAClD,CAAC;;;;;;;;AAwDD,IAAa,kBAAb,cAAqC,QAAQ,QAA+C,CAAC,CAC3F,uCACF,CAAC,CAAC;;;;;;;;CAQA,OAAgB,YAAY,WAAsB,YAChD,mBA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O,KAAK,QAAQ,SAAS,OAAO,gBAAgB,GACpD,OAAO,UACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $t as
|
|
1
|
+
import { $t as EDASinkRawDurableBatch, Gt as EDAProjectedSink, Ht as EDADurableSinkDefinition, Jt as EDASink, Kt as EDARawDurableSinkDefinition, Qt as EDASinkInterests, Ut as EDAEphemeralSinkDefinition, Wt as EDAProjectedDurableSinkDefinition, Xt as EDASinkContext, Yt as EDASinkCheckpoint, Zt as EDASinkDurableBatch, en as EDASinkRegistry, nn as EDASinkRunnerStartInput, qt as EDARawSink, tn as EDASinkRegistryShape } from "../reduced-state-D50SR0qM.js";
|
|
2
2
|
export { EDADurableSinkDefinition, EDAEphemeralSinkDefinition, EDAProjectedDurableSinkDefinition, EDAProjectedSink, EDARawDurableSinkDefinition, EDARawSink, EDASink, EDASinkCheckpoint, EDASinkContext, EDASinkDurableBatch, EDASinkInterests, EDASinkRawDurableBatch, EDASinkRegistry, EDASinkRegistryShape, EDASinkRunnerStartInput };
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
*
|
|
21
21
|
* Application-specific operations belong in the application catalog, not this reusable catalog.
|
|
22
22
|
*/
|
|
23
|
-
declare const SpanNames: readonly ["agent.command.submit", "agent.command.submit.wait", "agent.command.wait", "agent.compaction", "agent.events.follow", "agent.events.page", "agent.events.stream", "agent.inference", "agent.
|
|
23
|
+
declare const SpanNames: readonly ["agent.command.submit", "agent.command.submit.wait", "agent.command.wait", "agent.compaction", "agent.events.follow", "agent.events.page", "agent.events.stream", "agent.inference", "agent.run", "agent.run.grant", "agent.run.request.outcome", "agent.session.hydrate", "agent.session.snapshot", "agent.sink.drain", "agent.sink.hydrate", "agent.sinks.initialize", "agent.tool", "agent.turn"];
|
|
24
24
|
/** Union of values admitted by the centralized EDA span-name catalog. */
|
|
25
25
|
type SpanName = (typeof SpanNames)[number];
|
|
26
26
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"span-names.js","names":[],"sources":["../../src/services/span-names.ts"],"sourcesContent":["type CanonicalSpanName = `${string}.${string}`;\n\nconst defineSpanNames = <const Names extends ReadonlyArray<CanonicalSpanName>>(\n names: Names,\n): Names => names;\n\n/**\n * Allowlist of meaningful spans owned by the reusable durable-agent runtime.\n *\n * Add a name only when the span:\n * - represents a recognizable agent operation in the end-to-end execution flow;\n * - owns non-trivial work whose duration, failure, or interruption is useful to diagnose; and\n * - has a lifetime that matches that work rather than acting as an instantaneous marker.\n *\n * Names are stable, lowercase, dot-separated semantic paths. Start with the owning subsystem and\n * move from general to specific, ending with the operation, for example `agent.command.submit`.\n * Describe domain work, not TypeScript symbols, class names, EDA prefixes, or helper mechanics.\n * Keep names low-cardinality: IDs, tool or sink names, providers, models, attempts, and outcomes are\n * span attributes, never name segments.\n *\n * Prefer `Effect.fn(\"...\")` when a function owns the operation and `Effect.withSpan(\"...\")` around\n * an existing effect boundary. Do not add spans for pure transforms, bookkeeping, condition checks,\n * retry-delay calculations, or other near-zero-width implementation steps. Use unnamed `Effect.fn`\n * when a function benefits from Effect structure but would not add a useful node to the trace.\n *\n * Application-specific operations belong in the application catalog, not this reusable catalog.\n */\nexport const SpanNames = defineSpanNames([\n \"agent.command.submit\",\n \"agent.command.submit.wait\",\n \"agent.command.wait\",\n \"agent.compaction\",\n \"agent.events.follow\",\n \"agent.events.page\",\n \"agent.events.stream\",\n \"agent.inference\",\n \"agent.
|
|
1
|
+
{"version":3,"file":"span-names.js","names":[],"sources":["../../src/services/span-names.ts"],"sourcesContent":["type CanonicalSpanName = `${string}.${string}`;\n\nconst defineSpanNames = <const Names extends ReadonlyArray<CanonicalSpanName>>(\n names: Names,\n): Names => names;\n\n/**\n * Allowlist of meaningful spans owned by the reusable durable-agent runtime.\n *\n * Add a name only when the span:\n * - represents a recognizable agent operation in the end-to-end execution flow;\n * - owns non-trivial work whose duration, failure, or interruption is useful to diagnose; and\n * - has a lifetime that matches that work rather than acting as an instantaneous marker.\n *\n * Names are stable, lowercase, dot-separated semantic paths. Start with the owning subsystem and\n * move from general to specific, ending with the operation, for example `agent.command.submit`.\n * Describe domain work, not TypeScript symbols, class names, EDA prefixes, or helper mechanics.\n * Keep names low-cardinality: IDs, tool or sink names, providers, models, attempts, and outcomes are\n * span attributes, never name segments.\n *\n * Prefer `Effect.fn(\"...\")` when a function owns the operation and `Effect.withSpan(\"...\")` around\n * an existing effect boundary. Do not add spans for pure transforms, bookkeeping, condition checks,\n * retry-delay calculations, or other near-zero-width implementation steps. Use unnamed `Effect.fn`\n * when a function benefits from Effect structure but would not add a useful node to the trace.\n *\n * Application-specific operations belong in the application catalog, not this reusable catalog.\n */\nexport const SpanNames = defineSpanNames([\n \"agent.command.submit\",\n \"agent.command.submit.wait\",\n \"agent.command.wait\",\n \"agent.compaction\",\n \"agent.events.follow\",\n \"agent.events.page\",\n \"agent.events.stream\",\n \"agent.inference\",\n \"agent.run\",\n \"agent.run.grant\",\n \"agent.run.request.outcome\",\n \"agent.session.hydrate\",\n \"agent.session.snapshot\",\n \"agent.sink.drain\",\n \"agent.sink.hydrate\",\n \"agent.sinks.initialize\",\n \"agent.tool\",\n \"agent.turn\",\n]);\n\n/** Union of values admitted by the centralized EDA span-name catalog. */\nexport type SpanName = (typeof SpanNames)[number];\n"],"mappings":";AAEA,MAAM,mBACJ,UACU;;;;;;;;;;;;;;;;;;;;;;AAuBZ,MAAa,YAAY,gBAAgB;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
|
|
@@ -67,11 +67,16 @@ const KnownReadiness = Schema.TaggedUnion({
|
|
|
67
67
|
* (a session re-enabled after it was disabled; clients receive a re-read when it gets there).
|
|
68
68
|
*/
|
|
69
69
|
UpdatingHistory: {},
|
|
70
|
-
/**
|
|
70
|
+
/**
|
|
71
|
+
* No version is servable yet and the build of the current definition can still finish; the
|
|
72
|
+
* window is empty.
|
|
73
|
+
*/
|
|
71
74
|
Building: {},
|
|
72
75
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
76
|
+
* Nothing can be served, and `error` says why; the window is empty. Either a stored row of the
|
|
77
|
+
* served version cannot be decoded by this release (nothing is served until a rebuild finishes,
|
|
78
|
+
* rather than a wrong view), or no version is active and the build of the current definition
|
|
79
|
+
* froze as failed, which is never retried (only a new definition repairs it).
|
|
75
80
|
*/
|
|
76
81
|
Unreadable: { error: Schema.String },
|
|
77
82
|
/** A readiness this reader does not know; treated as degraded. */
|
|
@@ -497,4 +502,4 @@ const evictOldest = Effect.fnUntraced(function* (read, from, to, maxRecords) {
|
|
|
497
502
|
//#endregion
|
|
498
503
|
export { TranscriptWindowSelector as _, defaultTranscriptSubscriptionPolicy as a, transcriptCoverageOf as c, TranscriptActivePart as d, TranscriptReadiness as f, TranscriptWindowLimits as g, TranscriptWindow as h, TranscriptUpdate as i, transcriptSubscriptionBaseOf as l, TranscriptVersionStatus as m, TranscriptRequestId as n, planTranscriptUpdate as o, TranscriptVersionMeta as p, TranscriptSubscriptionBase as r, readTranscriptSubscription as s, TranscriptCoverage as t, TranscriptActiveContent as u, defaultTranscriptWindowLimits as v, transcriptCursorOf as y };
|
|
499
504
|
|
|
500
|
-
//# sourceMappingURL=subscription-
|
|
505
|
+
//# sourceMappingURL=subscription-hkD4M3xp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subscription-hkD4M3xp.js","names":["PositiveInt"],"sources":["../src/transcript/window.ts","../src/transcript/subscription.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { NonNegativeInt } from \"../types/events/envelope\";\nimport {\n InferenceAssistantRecordId,\n TranscriptAssistantPart,\n TranscriptCursor,\n TranscriptLogIncarnation,\n TranscriptOrder,\n TranscriptRecordViewFromEnvelope,\n isPendingTranscriptUserRecord,\n isTopLevelTranscriptRecord,\n TranscriptVersion,\n type TranscriptOrderKey,\n type TranscriptRecordView,\n} from \"./records\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\n\nconst orderKeyOfCursor = (cursor: TranscriptCursor): TranscriptOrderKey => ({\n anchorSeq: cursor.anchorSeq,\n ordinal: cursor.ordinal,\n recordId: cursor.recordId,\n});\n\n/**\n * Which slice of history to read.\n *\n * `Latest` serves first paint (SSR, CLIs); `Page` walks either direction from a cursor;\n * `Range` re-reads exactly the span a client retains, inclusive of both ends, at one new cut.\n */\nexport const TranscriptWindowSelector = Schema.Union([\n Schema.TaggedStruct(\"Latest\", { count: PositiveInt }),\n Schema.TaggedStruct(\"Page\", {\n direction: Schema.Literals([\"before\", \"after\"]),\n cursor: TranscriptCursor,\n count: PositiveInt,\n }),\n Schema.TaggedStruct(\"Range\", { from: TranscriptCursor, to: TranscriptCursor }).check(\n Schema.makeFilter(\n (range) =>\n (range.from.incarnation === range.to.incarnation &&\n range.from.version === range.to.version) ||\n \"a range is scoped to one incarnation and version\",\n ),\n Schema.makeFilter(\n (range) =>\n TranscriptOrder(orderKeyOfCursor(range.from), orderKeyOfCursor(range.to)) <= 0 ||\n \"a range starts at or before its end\",\n ),\n ),\n]);\nexport type TranscriptWindowSelector = typeof TranscriptWindowSelector.Type;\n\n/**\n * Bounds on one window. `maxRecords` caps top-level records (a selector's `count` is further\n * capped by it); `maxBytes` caps the whole response, dependencies included; bodies above\n * `maxInlineBodyBytes` are sent as references.\n */\nexport const TranscriptWindowLimits = Schema.Struct({\n maxRecords: PositiveInt,\n maxBytes: PositiveInt,\n maxInlineBodyBytes: NonNegativeInt,\n});\nexport type TranscriptWindowLimits = typeof TranscriptWindowLimits.Type;\n\n/** Default bounds: the first window holds 100 top-level records (design decision 4). */\nexport const defaultTranscriptWindowLimits: TranscriptWindowLimits = {\n maxRecords: 100,\n maxBytes: 1_048_576,\n maxInlineBodyBytes: 16_384,\n};\n\n/**\n * Whether the window is the current interpretation of the log, and if not, why its cut is\n * behind.\n *\n * Every state other than `Ready` is a degraded read and obeys one rule: the response contains\n * nothing newer than `throughSeq` — no newer pending users, session context or live content.\n */\nconst KnownReadiness = Schema.TaggedUnion({\n /** The active version is healthy and projected through the log head at read time. */\n Ready: {},\n /** The active version failed while projecting `failedAtSeq`; this is its last good cut. */\n Degraded: { failedAtSeq: SequenceNumber, error: Schema.String },\n /**\n * The served cut is consistent but behind the log: either the active version is no longer\n * carried by this release and history is being rebuilt under the current definition (clients\n * receive one replacement when it activates), or the active version is catching up to the head\n * (a session re-enabled after it was disabled; clients receive a re-read when it gets there).\n */\n UpdatingHistory: {},\n /**\n * No version is servable yet and the build of the current definition can still finish; the\n * window is empty.\n */\n Building: {},\n /**\n * Nothing can be served, and `error` says why; the window is empty. Either a stored row of the\n * served version cannot be decoded by this release (nothing is served until a rebuild finishes,\n * rather than a wrong view), or no version is active and the build of the current definition\n * froze as failed, which is never retried (only a new definition repairs it).\n */\n Unreadable: { error: Schema.String },\n /** A readiness this reader does not know; treated as degraded. */\n Unknown: { readinessType: Schema.String },\n});\n\nconst knownReadinessTags: ReadonlySet<string> = new Set([\n \"Ready\",\n \"Degraded\",\n \"UpdatingHistory\",\n \"Building\",\n \"Unreadable\",\n \"Unknown\",\n]);\n\nconst UnrecognizedReadiness = Schema.Struct({\n _tag: Schema.String.check(\n Schema.makeFilter(\n (tag) => !knownReadinessTags.has(tag) || \"a known readiness must decode as that readiness\",\n ),\n ),\n}).pipe(\n Schema.decodeTo(Schema.toType(KnownReadiness.cases.Unknown), {\n decode: SchemaGetter.transform((readiness) => ({\n _tag: \"Unknown\" as const,\n readinessType: readiness._tag,\n })),\n encode: SchemaGetter.transform((readiness) => ({ _tag: readiness.readinessType })),\n }),\n);\n\n/**\n * Whether the window is the current interpretation of the log. A readiness this reader does not\n * know decodes as `Unknown` and is treated as degraded: it carries no live content. A malformed\n * readiness with a known tag is a decode failure.\n */\nexport const TranscriptReadiness = Schema.Union([KnownReadiness, UnrecognizedReadiness]);\nexport type TranscriptReadiness = typeof TranscriptReadiness.Type;\n\n/**\n * One live part of the inference streaming now.\n *\n * `id` is stable for the life of the part (`text:<providerPartId>`, `reasoning:<providerPartId>`,\n * `tool:<toolCallId>`), so a client keys a streaming part by it and replaces it in place as it\n * grows. `paramsText` is the tool-call parameter text streamed so far; it is speculative until\n * the call is sealed into a tool record.\n */\nexport const TranscriptActivePart = Schema.Struct({\n id: Schema.NonEmptyString,\n part: TranscriptAssistantPart,\n paramsText: Schema.optionalKey(Schema.String),\n}).check(\n Schema.makeFilter(\n (active) =>\n (active.part._tag === \"Text\"\n ? active.id.startsWith(\"text:\")\n : active.part._tag === \"Reasoning\"\n ? active.id.startsWith(\"reasoning:\")\n : active.part._tag === \"ToolCall\"\n ? active.id.startsWith(\"tool:\")\n : true) || \"a live part's id names its kind\",\n ),\n Schema.makeFilter(\n (active) =>\n active.paramsText === undefined ||\n active.part._tag === \"ToolCall\" ||\n \"only a tool call streams parameter text\",\n ),\n);\nexport type TranscriptActivePart = typeof TranscriptActivePart.Type;\n\n/**\n * Accumulated parts of the inference streaming now, captured at the same publication boundary as\n * the window. Owned by the live runtime; storage-level reads never include it.\n */\nexport const TranscriptActiveContent = Schema.Struct({\n assistantId: InferenceAssistantRecordId,\n parts: Schema.Array(TranscriptActivePart),\n});\nexport type TranscriptActiveContent = typeof TranscriptActiveContent.Type;\n\nconst recordUpdatedSeq = (record: TranscriptRecordView): number => record.updatedSeq;\n\nconst recordPosition = (record: TranscriptRecordView) =>\n \"position\" in record ? record.position : undefined;\n\n/** Positioned history, which is served only as a top-level record and never as a dependency. */\nconst isHistoryRecord = (record: TranscriptRecordView): boolean =>\n record.kind === \"unknown\" ? record.position !== undefined : isTopLevelTranscriptRecord(record);\n\n/**\n * One complete, consistent read of a transcript version.\n *\n * `records` are top-level records in transcript order; `dependencies` are the tools and run\n * groups they reference, the session context, and every pending user record. Every record is\n * projected through `throughSeq` and none is newer, which is what makes a cut complete. A client\n * replaces, never merges, what a window covers.\n */\nexport const TranscriptWindow = Schema.Struct({\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n throughSeq: SequenceNumber,\n records: Schema.Array(TranscriptRecordViewFromEnvelope),\n dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),\n activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),\n hasOlder: Schema.Boolean,\n hasNewer: Schema.Boolean,\n readiness: TranscriptReadiness,\n}).check(\n Schema.makeFilter(\n (window) =>\n [...window.records, ...window.dependencies].every(\n (record) => recordUpdatedSeq(record) <= window.throughSeq,\n ) || \"every record must be projected through throughSeq and none may be newer\",\n ),\n Schema.makeFilter(\n (window) =>\n window.readiness._tag === \"Ready\" ||\n window.activeContent === undefined ||\n \"a degraded read never attaches live content\",\n ),\n Schema.makeFilter(\n (window) =>\n window.readiness._tag !== \"Degraded\" ||\n window.readiness.failedAtSeq > window.throughSeq ||\n \"a degraded cut ends before the seq that failed\",\n ),\n Schema.makeFilter(\n (window) =>\n [...window.records, ...window.dependencies].every(\n (record) =>\n record.kind !== \"decorationBuffer\" &&\n (record.kind !== \"unknown\" || record.originalKind !== \"decorationBuffer\"),\n ) || \"decoration buffers are never served\",\n ),\n Schema.makeFilter((window) => {\n const ids = [...window.records, ...window.dependencies].map((record) => record.id);\n return new Set(ids).size === ids.length || \"a record is served at most once\";\n }),\n Schema.makeFilter(\n (window) =>\n window.records.every((record, index) => {\n const position = recordPosition(record);\n if (position === undefined || !isHistoryRecord(record)) return false;\n const previous = index === 0 ? undefined : window.records[index - 1];\n const previousPosition = previous === undefined ? undefined : recordPosition(previous);\n return (\n previous === undefined ||\n previousPosition === undefined ||\n TranscriptOrder(\n { ...previousPosition, recordId: previous.id },\n { ...position, recordId: record.id },\n ) < 0\n );\n }) || \"records are positioned history records in transcript order\",\n ),\n Schema.makeFilter(\n (window) =>\n window.dependencies.every((record) => !isHistoryRecord(record)) ||\n \"dependencies never contain history records\",\n ),\n Schema.makeFilter(\n (window) =>\n window.dependencies.every(\n (record) => record.kind !== \"user\" || isPendingTranscriptUserRecord(record),\n ) || \"the only user dependencies are pending users; cancelled users are never served\",\n ),\n Schema.makeFilter(\n (window) =>\n (window.readiness._tag !== \"Building\" && window.readiness._tag !== \"Unreadable\") ||\n (window.records.length === 0 &&\n window.dependencies.length === 0 &&\n !window.hasOlder &&\n !window.hasNewer) ||\n \"a building or unreadable window is empty\",\n ),\n);\nexport type TranscriptWindow = typeof TranscriptWindow.Type;\n\n/** Paging cursor for one top-level record of a window. */\nexport const transcriptCursorOf = (\n window: Pick<TranscriptWindow, \"incarnation\" | \"version\">,\n record: TranscriptRecordView,\n): TranscriptCursor | undefined => {\n const position = \"position\" in record ? record.position : undefined;\n return position === undefined\n ? undefined\n : {\n incarnation: window.incarnation,\n version: window.version,\n anchorSeq: position.anchorSeq,\n ordinal: position.ordinal,\n recordId: record.id,\n };\n};\n\n/** Health of one stored transcript version. A failed version is frozen at its last good cursor. */\nexport const TranscriptVersionStatus = Schema.TaggedUnion({\n Ok: {},\n Failed: { failedAtSeq: SequenceNumber, error: Schema.String },\n});\nexport type TranscriptVersionStatus = typeof TranscriptVersionStatus.Type;\n\n/**\n * Per-version maintenance state, one per version present in a session's storage.\n *\n * `cursor` is the last fully projected seq, committed together with that version's rows. At most\n * one version is `active` (served) and at most one is `building` (catching up from the log).\n */\nexport const TranscriptVersionMeta = Schema.Struct({\n version: TranscriptVersion,\n role: Schema.Literals([\"active\", \"building\"]),\n cursor: SequenceNumber,\n status: TranscriptVersionStatus,\n}).check(\n Schema.makeFilter(\n (meta) =>\n meta.status._tag !== \"Failed\" ||\n meta.status.failedAtSeq > meta.cursor ||\n \"a failed version is frozen before the seq that failed\",\n ),\n);\nexport type TranscriptVersionMeta = typeof TranscriptVersionMeta.Type;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { EDASessionStoreError } from \"../services/session-store\";\nimport {\n TranscriptCursor,\n TranscriptLogIncarnation,\n TranscriptOrder,\n TranscriptRecordViewFromEnvelope,\n TranscriptVersion,\n type TranscriptOrderKey,\n type TranscriptRecordView,\n} from \"./records\";\nimport type { EDATranscriptStoreShape, TranscriptCursorMismatch } from \"./store\";\nimport {\n TranscriptActiveContent,\n TranscriptReadiness,\n transcriptCursorOf,\n type TranscriptWindow,\n type TranscriptWindowLimits,\n type TranscriptWindowSelector,\n} from \"./window\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\n\n/** Client-chosen correlation id echoed on the update that answers a request. */\nexport const TranscriptRequestId = Schema.NonEmptyString.check(Schema.isMaxLength(64));\nexport type TranscriptRequestId = typeof TranscriptRequestId.Type;\n\n/**\n * The contiguous span of top-level records a subscriber holds, both ends inclusive. Absent when\n * the subscriber holds no top-level records (an empty session, or a window still building).\n */\nexport const TranscriptCoverage = Schema.Struct({\n from: TranscriptCursor,\n to: TranscriptCursor,\n});\nexport type TranscriptCoverage = typeof TranscriptCoverage.Type;\n\n/**\n * What a subscriber holds after its last complete update: the cut it was read at and the span it\n * covers. Every update is planned relative to this base, which is also persisted with the socket\n * so a hibernated subscription resumes without volatile state.\n *\n * `tail` is true when the coverage reaches the newest record of its cut; new history then joins\n * the coverage as it is committed. A subscriber that paged back past the tail sees `hasNewer`\n * instead and pages forward to rejoin it.\n */\nexport const TranscriptSubscriptionBase = Schema.Struct({\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n throughSeq: SequenceNumber,\n coverage: Schema.optionalKey(TranscriptCoverage),\n tail: Schema.Boolean,\n});\nexport type TranscriptSubscriptionBase = typeof TranscriptSubscriptionBase.Type;\n\n/**\n * One ordered, complete change to a subscriber's window: the only way a live client's window\n * changes.\n *\n * - `replace` discards everything the client holds and installs this window.\n * - `patch` is relative to the client's previous complete update: `records` and `dependencies`\n * carry every record that changed or newly entered the window, `dependencyIds` lists the\n * complete dependency membership of the new cut (the client drops any other dependency), and\n * the client drops top-level records outside `coverage`.\n *\n * Either way the client ends at exactly the window read at `throughSeq`: a complete cut. When\n * present, `activeContent` replaces the client's active content completely (an empty array\n * clears it); when absent, active content is unchanged. A degraded update carries no live\n * content, and a client shows none while readiness is not `Ready`.\n */\nexport const TranscriptUpdate = Schema.Struct({\n updateSeq: PositiveInt,\n mode: Schema.Literals([\"replace\", \"patch\"]),\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n throughSeq: SequenceNumber,\n coverage: Schema.optionalKey(TranscriptCoverage),\n hasOlder: Schema.Boolean,\n hasNewer: Schema.Boolean,\n readiness: TranscriptReadiness,\n records: Schema.Array(TranscriptRecordViewFromEnvelope),\n dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),\n dependencyIds: Schema.Array(Schema.NonEmptyString),\n activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),\n requestId: Schema.optionalKey(TranscriptRequestId),\n}).check(\n Schema.makeFilter(\n (update) =>\n [...update.records, ...update.dependencies].every(\n (record) => record.updatedSeq <= update.throughSeq,\n ) || \"every record must be projected through throughSeq and none may be newer\",\n ),\n Schema.makeFilter(\n (update) =>\n update.readiness._tag === \"Ready\" ||\n update.activeContent === undefined ||\n update.activeContent.length === 0 ||\n \"a degraded update never carries live content\",\n ),\n Schema.makeFilter((update) => {\n const dependencyIds = new Set(update.dependencyIds);\n return (\n update.dependencies.every((record) => dependencyIds.has(record.id)) ||\n \"every sent dependency is a member of the cut\"\n );\n }),\n);\nexport type TranscriptUpdate = typeof TranscriptUpdate.Type;\n\n/** Bounds of one subscription. Retained coverage never exceeds `limits.maxRecords`. */\nexport interface TranscriptSubscriptionPolicy {\n /** Top-level records of a fresh subscription (design decision 4). */\n readonly initialCount: number;\n /** Largest page a client may request at once. */\n readonly maxPageCount: number;\n readonly limits: TranscriptWindowLimits;\n}\n\nexport const defaultTranscriptSubscriptionPolicy: TranscriptSubscriptionPolicy = {\n initialCount: 100,\n maxPageCount: 100,\n limits: { maxRecords: 300, maxBytes: 2 * 1_048_576, maxInlineBodyBytes: 16_384 },\n};\n\n/** A subscriber's request, decoded from its socket and handled strictly in arrival order. */\nexport type TranscriptSubscriptionRequest =\n /** Re-read the held coverage at a new cut, after committed changes. */\n | { readonly _tag: \"Refresh\" }\n /**\n * Start (or restart) a subscription. With `range` and `since` (what SSR rendered, or what a\n * reconnecting client last applied), the first update is a patch over that range; otherwise\n * it is a replacement of the latest `count` records.\n */\n | {\n readonly _tag: \"Subscribe\";\n readonly range?: TranscriptCoverage;\n readonly tail: boolean;\n readonly since?: SequenceNumber;\n readonly count?: number;\n }\n /** Extend the coverage by `count` records from its `before` or `after` edge. */\n | {\n readonly _tag: \"Page\";\n readonly direction: \"before\" | \"after\";\n readonly cursor: TranscriptCursor;\n readonly count: number;\n }\n /** Narrow the coverage to a span inside it, releasing the rest. */\n | { readonly _tag: \"Retain\"; readonly from: TranscriptCursor; readonly to: TranscriptCursor };\n\n/** One window read at a single cut, and the base the update for it is relative to. */\nexport interface TranscriptSubscriptionRead {\n readonly window: TranscriptWindow;\n /** What the client holds; `undefined` makes the update a replacement. */\n readonly patchBase: TranscriptSubscriptionBase | undefined;\n}\n\nconst orderKey = (cursor: TranscriptCursor): TranscriptOrderKey => ({\n anchorSeq: cursor.anchorSeq,\n ordinal: cursor.ordinal,\n recordId: cursor.recordId,\n});\n\nconst sameCursor = (left: TranscriptCursor, right: TranscriptCursor): boolean =>\n left.incarnation === right.incarnation &&\n left.version === right.version &&\n TranscriptOrder(orderKey(left), orderKey(right)) === 0;\n\n/**\n * A cursor after every possible record of one version, so a `Range` ending at it reads from a\n * point to the newest record. Never sent to clients.\n */\nconst tailCursor = (from: TranscriptCursor): TranscriptCursor => ({\n incarnation: from.incarnation,\n version: from.version,\n anchorSeq: SequenceNumber.make(Number.MAX_SAFE_INTEGER),\n ordinal: Number.MAX_SAFE_INTEGER,\n recordId: \"\",\n});\n\n/** The span a window's top-level records cover, or `undefined` when it has none. */\nexport const transcriptCoverageOf = (window: TranscriptWindow): TranscriptCoverage | undefined => {\n const first = window.records[0];\n const last = window.records[window.records.length - 1];\n const from = first === undefined ? undefined : transcriptCursorOf(window, first);\n const to = last === undefined ? undefined : transcriptCursorOf(window, last);\n return from === undefined || to === undefined ? undefined : { from, to };\n};\n\nconst withinCoverage = (\n coverage: TranscriptCoverage | undefined,\n record: TranscriptRecordView,\n): boolean => {\n if (coverage === undefined || !(\"position\" in record) || record.position === undefined) {\n return false;\n }\n const key = { ...record.position, recordId: record.id };\n return (\n TranscriptOrder(orderKey(coverage.from), key) <= 0 &&\n TranscriptOrder(key, orderKey(coverage.to)) <= 0\n );\n};\n\n/** The base a client holds after applying an update for `window`. */\nexport const transcriptSubscriptionBaseOf = (\n window: TranscriptWindow,\n): TranscriptSubscriptionBase => {\n const coverage = transcriptCoverageOf(window);\n return {\n incarnation: window.incarnation,\n version: window.version,\n throughSeq: window.throughSeq,\n ...(coverage === undefined ? {} : { coverage }),\n tail: !window.hasNewer,\n };\n};\n\n/**\n * Plan the one update that moves a client from `patchBase` to `window`.\n *\n * A patch sends a top-level record when it changed after the base cut or was outside the base\n * coverage. It sends a tool dependency when the tool changed or its assistant is sent, and any\n * other dependency (run groups, session context, pending users) when it changed or any top-level\n * record is sent. Everything else the client already holds unchanged from the base cut, because\n * the base cut was itself complete. A different incarnation or version, or a base cut ahead of\n * the window, makes the update a replacement.\n */\nexport const planTranscriptUpdate = (input: {\n readonly patchBase: TranscriptSubscriptionBase | undefined;\n readonly window: TranscriptWindow;\n readonly updateSeq: number;\n /** The live content captured at the same publication boundary as `window`. */\n readonly activeContent: ReadonlyArray<TranscriptActiveContent>;\n /**\n * Whether the client's active content must be replaced. A replacement always carries it;\n * otherwise the caller sends it only when it changed since its last send.\n */\n readonly includeActiveContent: boolean;\n readonly requestId?: TranscriptRequestId;\n}): TranscriptUpdate => {\n const { window } = input;\n const base = input.patchBase;\n const patch =\n base !== undefined &&\n base.incarnation === window.incarnation &&\n base.version === window.version &&\n base.throughSeq <= window.throughSeq;\n const records = patch\n ? window.records.filter(\n (record) => record.updatedSeq > base.throughSeq || !withinCoverage(base.coverage, record),\n )\n : window.records;\n const sentIds = new Set(records.map((record) => record.id));\n const dependencies = patch\n ? window.dependencies.filter(\n (record) =>\n record.updatedSeq > base.throughSeq ||\n (record.kind === \"tool\" ? sentIds.has(record.assistantId) : records.length > 0),\n )\n : window.dependencies;\n const coverage = transcriptCoverageOf(window);\n const activeContent =\n patch && !input.includeActiveContent\n ? undefined\n : servedActiveContent(window, input.activeContent);\n return {\n updateSeq: input.updateSeq,\n mode: patch ? \"patch\" : \"replace\",\n incarnation: window.incarnation,\n version: window.version,\n throughSeq: window.throughSeq,\n ...(coverage === undefined ? {} : { coverage }),\n hasOlder: window.hasOlder,\n hasNewer: window.hasNewer,\n readiness: window.readiness,\n records,\n dependencies,\n dependencyIds: window.dependencies.map((record) => record.id),\n ...(activeContent === undefined ? {} : { activeContent }),\n ...(input.requestId === undefined ? {} : { requestId: input.requestId }),\n };\n};\n\n/**\n * Live content as served with a window: none on a degraded read, and never for an inference the\n * window already shows as committed or failed, so a stale live part cannot override a terminal.\n */\nconst servedActiveContent = (\n window: TranscriptWindow,\n activeContent: ReadonlyArray<TranscriptActiveContent>,\n): ReadonlyArray<TranscriptActiveContent> => {\n if (window.readiness._tag !== \"Ready\") return [];\n const settled = new Set(\n window.records.flatMap((record) =>\n record.kind === \"assistant\" && record.lifecycle._tag !== \"Streaming\" ? [record.id] : [],\n ),\n );\n return activeContent.filter((content) => !settled.has(content.assistantId));\n};\n\n/**\n * Read the window that answers one request, at one cut.\n *\n * Helper reads (to find a page's far edge) may see other cuts; only the final read is served,\n * so the update is always one synchronous read. Coverage stays within `limits.maxRecords`:\n * paging back evicts the newest records, paging forward evicts the oldest, and a tail that\n * outgrows the bound keeps its newest records. A cursor minted for another incarnation or version\n * falls back to a replacement of the latest records.\n */\nexport const readTranscriptSubscription = (\n store: EDATranscriptStoreShape,\n base: TranscriptSubscriptionBase | undefined,\n request: TranscriptSubscriptionRequest,\n policy: TranscriptSubscriptionPolicy,\n): Effect.Effect<TranscriptSubscriptionRead, EDASessionStoreError> => {\n const read = (selector: TranscriptWindowSelector) =>\n store.readTranscriptWindow(selector, policy.limits);\n const latest = read({\n _tag: \"Latest\",\n count: Math.min(policy.initialCount, policy.limits.maxRecords),\n }).pipe(Effect.map((window) => ({ window, patchBase: undefined })));\n\n const readCoverage = Effect.fnUntraced(function* (\n coverage: TranscriptCoverage | undefined,\n tail: boolean,\n overflowToNewest: boolean,\n ) {\n if (coverage === undefined) {\n return yield* read({\n _tag: \"Latest\",\n count: Math.min(policy.initialCount, policy.limits.maxRecords),\n });\n }\n if (!tail) return yield* read({ _tag: \"Range\", ...coverage });\n const window = yield* read({\n _tag: \"Range\",\n from: coverage.from,\n to: tailCursor(coverage.from),\n });\n // The span outgrew the bound: keep as many of its newest records as the Range read held.\n return window.hasNewer && overflowToNewest\n ? yield* read({ _tag: \"Latest\", count: Math.max(1, window.records.length) })\n : window;\n });\n\n const handle = Effect.fnUntraced(function* () {\n switch (request._tag) {\n case \"Subscribe\": {\n const count = Math.min(request.count ?? policy.initialCount, policy.limits.maxRecords);\n if (request.range === undefined) {\n const window = yield* read({ _tag: \"Latest\", count });\n return { window, patchBase: undefined };\n }\n const claimed: TranscriptSubscriptionBase = {\n incarnation: request.range.from.incarnation,\n version: request.range.from.version,\n throughSeq: request.since ?? SequenceNumber.make(0),\n coverage: request.range,\n tail: request.tail,\n };\n const window = yield* readCoverage(request.range, request.tail, true);\n return { window, patchBase: request.since === undefined ? undefined : claimed };\n }\n case \"Refresh\": {\n if (base === undefined) return yield* latest;\n const window = yield* readCoverage(base.coverage, base.tail, true);\n return { window, patchBase: base };\n }\n case \"Page\": {\n const coverage = base?.coverage;\n const edge = request.direction === \"before\" ? coverage?.from : coverage?.to;\n if (base === undefined || coverage === undefined || edge === undefined) {\n return base === undefined\n ? yield* latest\n : { window: yield* readCoverage(base.coverage, base.tail, true), patchBase: base };\n }\n if (!sameCursor(edge, request.cursor)) {\n return { window: yield* readCoverage(coverage, base.tail, true), patchBase: base };\n }\n const page = yield* read({\n _tag: \"Page\",\n direction: request.direction,\n cursor: request.cursor,\n count: Math.min(request.count, policy.maxPageCount, policy.limits.maxRecords),\n });\n const first = page.records[0];\n const last = page.records[page.records.length - 1];\n const pageFrom = first === undefined ? undefined : transcriptCursorOf(page, first);\n const pageTo = last === undefined ? undefined : transcriptCursorOf(page, last);\n if (pageFrom === undefined || pageTo === undefined) {\n return { window: yield* readCoverage(coverage, base.tail, true), patchBase: base };\n }\n if (request.direction === \"before\") {\n // A Range keeps its oldest records when it is over a bound, evicting the newest.\n const window = yield* readCoverage({ from: pageFrom, to: coverage.to }, base.tail, false);\n return { window, patchBase: base };\n }\n const from = yield* evictOldest(read, coverage.from, pageTo, policy.limits.maxRecords);\n const window = yield* readCoverage({ from, to: pageTo }, !page.hasNewer, false);\n return { window, patchBase: base };\n }\n case \"Retain\": {\n const coverage = base?.coverage;\n if (base === undefined || coverage === undefined) {\n return base === undefined\n ? yield* latest\n : { window: yield* readCoverage(base.coverage, base.tail, true), patchBase: base };\n }\n const inside =\n request.from.incarnation === base.incarnation &&\n request.from.version === base.version &&\n request.to.incarnation === base.incarnation &&\n request.to.version === base.version &&\n TranscriptOrder(orderKey(coverage.from), orderKey(request.from)) <= 0 &&\n TranscriptOrder(orderKey(request.from), orderKey(request.to)) <= 0 &&\n TranscriptOrder(orderKey(request.to), orderKey(coverage.to)) <= 0;\n const retained = inside ? { from: request.from, to: request.to } : coverage;\n const tail = base.tail && sameCursor(retained.to, coverage.to);\n return { window: yield* readCoverage(retained, tail, true), patchBase: base };\n }\n }\n });\n\n // A Latest read names no cursor, so it cannot mismatch.\n return handle().pipe(\n Effect.catchTag(\"TranscriptCursorMismatch\", () =>\n latest.pipe(Effect.catchTag(\"TranscriptCursorMismatch\", Effect.die)),\n ),\n );\n};\n\n/**\n * The oldest cursor a span ending at `to` may start from without exceeding `maxRecords`: the\n * current `from`, or later when the span would be over the bound.\n */\nconst evictOldest = Effect.fnUntraced(function* (\n read: (\n selector: TranscriptWindowSelector,\n ) => Effect.Effect<TranscriptWindow, EDASessionStoreError | TranscriptCursorMismatch>,\n from: TranscriptCursor,\n to: TranscriptCursor,\n maxRecords: number,\n) {\n if (maxRecords <= 1) return to;\n const before = yield* read({\n _tag: \"Page\",\n direction: \"before\",\n cursor: to,\n count: maxRecords - 1,\n });\n const first = before.records[0];\n const oldest = first === undefined ? undefined : transcriptCursorOf(before, first);\n return oldest === undefined || TranscriptOrder(orderKey(oldest), orderKey(from)) <= 0\n ? from\n : oldest;\n});\n"],"mappings":";;;;;;;AAmBA,MAAMA,gBAAc,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;AAErE,MAAM,oBAAoB,YAAkD;CAC1E,WAAW,OAAO;CAClB,SAAS,OAAO;CAChB,UAAU,OAAO;AACnB;;;;;;;AAQA,MAAa,2BAA2B,OAAO,MAAM;CACnD,OAAO,aAAa,UAAU,EAAE,OAAOA,cAAY,CAAC;CACpD,OAAO,aAAa,QAAQ;EAC1B,WAAW,OAAO,SAAS,CAAC,UAAU,OAAO,CAAC;EAC9C,QAAQ;EACR,OAAOA;CACT,CAAC;CACD,OAAO,aAAa,SAAS;EAAE,MAAM;EAAkB,IAAI;CAAiB,CAAC,CAAC,CAAC,MAC7E,OAAO,YACJ,UACE,MAAM,KAAK,gBAAgB,MAAM,GAAG,eACnC,MAAM,KAAK,YAAY,MAAM,GAAG,WAClC,kDACJ,GACA,OAAO,YACJ,UACC,gBAAgB,iBAAiB,MAAM,IAAI,GAAG,iBAAiB,MAAM,EAAE,CAAC,KAAK,KAC7E,qCACJ,CACF;AACF,CAAC;;;;;;AAQD,MAAa,yBAAyB,OAAO,OAAO;CAClD,YAAYA;CACZ,UAAUA;CACV,oBAAoB;AACtB,CAAC;;AAID,MAAa,gCAAwD;CACnE,YAAY;CACZ,UAAU;CACV,oBAAoB;AACtB;;;;;;;;AASA,MAAM,iBAAiB,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S,4BAA4B,OAAO,GAAG,CAAC,CACrE,CACF;AACF;;;;;AAMA,MAAM,cAAc,OAAO,WAAW,WACpC,MAGA,MACA,IACA,YACA;CACA,IAAI,cAAc,GAAG,OAAO;CAC5B,MAAM,SAAS,OAAO,KAAK;EACzB,MAAM;EACN,WAAW;EACX,QAAQ;EACR,OAAO,aAAa;CACtB,CAAC;CACD,MAAM,QAAQ,OAAO,QAAQ;CAC7B,MAAM,SAAS,UAAU,KAAA,IAAY,KAAA,IAAY,mBAAmB,QAAQ,KAAK;CACjF,OAAO,WAAW,KAAA,KAAa,gBAAgB,SAAS,MAAM,GAAG,SAAS,IAAI,CAAC,KAAK,IAChF,OACA;AACN,CAAC"}
|
package/dist/testkit/layers.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import "../events-BWuvzVml.js";
|
|
|
4
4
|
import { c as EDASessionStoreShape, o as EDASessionStore, s as EDASessionStoreError } from "../session-store-CWYZ29CV.js";
|
|
5
5
|
import { t as ModelResolver } from "../model-resolver-DUms5p6X.js";
|
|
6
6
|
import { r as EDAReducerRegistry, t as EDAReducer } from "../reducer-registry-CPObI3cs.js";
|
|
7
|
-
import {
|
|
7
|
+
import { An as EDAPromptProjector, Ct as RunScheduler, En as SessionContext, Jt as EDASink, Q as EDASessionQuery, St as ToolExecutor, Tn as EventFactory, bt as InferenceRunner, dn as CompactionPolicy, en as EDASinkRegistry, ht as SessionState, mn as CompactionRunner, on as CompactionExecutor, rn as LiveEventBus, xt as InferenceRunnerStreamPart, yt as TurnRunner } from "../reduced-state-D50SR0qM.js";
|
|
8
8
|
import { a as ToolParamsSchema, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-B_WE2ZwK.js";
|
|
9
9
|
import { t as IdGenerator } from "../id-generator-BKGoKjt-.js";
|
|
10
10
|
import { t as EDAKeepAlive } from "../keep-alive-_zFCUvt3.js";
|