effect-durable-agent 0.1.0-alpha.19 → 0.1.0-alpha.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{compaction-Bell28K8.js → compaction-GD1cTPTZ.js} +4 -4
- package/dist/compaction-GD1cTPTZ.js.map +1 -0
- package/dist/domain/command-queues.d.ts +1 -1
- package/dist/domain/context-projection.js +1 -1
- package/dist/domain/context-projection.js.map +1 -1
- package/dist/domain/message-transcript.d.ts +1 -1
- package/dist/domain/message-transcript.js +1 -1
- package/dist/domain/message-transcript.js.map +1 -1
- package/dist/domain/reduced-state-schema.d.ts +1 -1
- package/dist/domain/reduced-state-schema.js +2 -2
- package/dist/domain/reduced-state-schema.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +1 -1
- package/dist/domain/reduced-state.js +1 -1
- package/dist/domain/run-scheduling.d.ts +1 -1
- package/dist/{durable-DRY7AcsF.js → durable-CD__3ztN.js} +67 -4
- package/dist/durable-CD__3ztN.js.map +1 -0
- package/dist/{durable-DoG_e4iL.d.ts → durable-CKdCCqhw.d.ts} +54 -1
- package/dist/{event-factory-CKuWhjS4.js → event-factory-VAci3NJb.js} +2 -2
- package/dist/{event-factory-CKuWhjS4.js.map → event-factory-VAci3NJb.js.map} +1 -1
- package/dist/{events-sxIzJY26.d.ts → events-BWuvzVml.d.ts} +2 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/{model-resolver-BHYVHsam.d.ts → model-resolver-BfM5YA6A.d.ts} +4 -4
- package/dist/{reduced-state-DrSHn_47.d.ts → reduced-state-4FSWDdgT.d.ts} +654 -453
- package/dist/{reduced-state-DFIYylAq.js → reduced-state-Vuud6LCM.js} +2 -2
- package/dist/reduced-state-Vuud6LCM.js.map +1 -0
- package/dist/{reduced-state-schema-CPEmuHLY.d.ts → reduced-state-schema-jyZWJ0QS.d.ts} +19 -1
- package/dist/{reducer-registry-C3ZidOI1.d.ts → reducer-registry-BIhncOHH.d.ts} +4 -4
- package/dist/{run-scheduling-wakeup-COUj3r_B.d.ts → run-scheduling-wakeup-BH2pHE0U.d.ts} +2 -2
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/compaction.js +1 -1
- package/dist/services/id-generator.js +1 -1
- package/dist/services/id-generator.js.map +1 -1
- package/dist/services/model-resolver.d.ts +1 -1
- package/dist/services/model-resolver.js +1 -1
- package/dist/services/model-resolver.js.map +1 -1
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/prompt-projector.js +1 -1
- package/dist/services/prompt-projector.js.map +1 -1
- package/dist/services/reducer-registry.d.ts +1 -1
- package/dist/services/run-scheduler.d.ts +1 -1
- package/dist/services/run-scheduler.js +1 -1
- package/dist/services/run-scheduler.js.map +1 -1
- package/dist/services/run-scheduling-wakeup.d.ts +1 -1
- package/dist/services/runtime-layer.d.ts +12 -9
- package/dist/services/runtime-layer.js +6 -6
- package/dist/services/runtime-layer.js.map +1 -1
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +2 -2
- package/dist/services/session-event-observer.d.ts +1 -1
- package/dist/services/session-query.d.ts +1 -1
- package/dist/services/session-query.js +2 -2
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.d.ts +1 -1
- package/dist/services/session-store.js +5 -5
- package/dist/services/session-store.js.map +1 -1
- package/dist/services/sink-checkpoint-store.d.ts +1 -1
- package/dist/services/sink-registry.d.ts +1 -1
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/tool-registry.d.ts +1 -1
- package/dist/services/tool-registry.js +2 -2
- package/dist/services/tool-registry.js.map +1 -1
- package/dist/services/tracing.d.ts +1 -1
- package/dist/services/tracing.js +1 -1
- package/dist/{session-event-observer-BDwja1jX.d.ts → session-event-observer-BdZltdrK.d.ts} +2 -2
- package/dist/{session-state-BBzzJrDC.js → session-state-BAzdzqV4.js} +17 -12
- package/dist/session-state-BAzdzqV4.js.map +1 -0
- package/dist/{session-store-B_vh581h.d.ts → session-store-BpitF4Wg.d.ts} +3 -3
- package/dist/{sink-checkpoint-store-2SxoNMbI.d.ts → sink-checkpoint-store-C-SY0cG2.d.ts} +2 -2
- package/dist/{sink-registry-ogHu2Sw7.js → sink-registry-BnWfMABI.js} +4 -4
- package/dist/sink-registry-BnWfMABI.js.map +1 -0
- package/dist/testkit/layers.d.ts +10 -10
- package/dist/testkit/layers.js +9 -6
- package/dist/testkit/layers.js.map +1 -1
- package/dist/{tool-registry-DDxbmMpY.d.ts → tool-registry-wPsHagF_.d.ts} +5 -5
- package/dist/types/commands.js +1 -1
- package/dist/types/commands.js.map +1 -1
- package/dist/types/events/durable.d.ts +1 -1
- package/dist/types/events/durable.js +1 -1
- package/dist/types/events.d.ts +2 -2
- package/dist/types/events.js +1 -1
- package/dist/websocket.d.ts +9 -2
- package/dist/websocket.js +1 -1
- package/package.json +8 -8
- package/dist/compaction-Bell28K8.js.map +0 -1
- package/dist/durable-DRY7AcsF.js.map +0 -1
- package/dist/reduced-state-DFIYylAq.js.map +0 -1
- package/dist/session-state-BBzzJrDC.js.map +0 -1
- package/dist/sink-registry-ogHu2Sw7.js.map +0 -1
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { g as SessionId } from "../core-BcimKMIv.js";
|
|
2
|
-
import { i as EDAAppEvents, o as EDASessionStore, s as EDASessionStoreError } from "../session-store-
|
|
3
|
-
import { t as ModelResolver } from "../model-resolver-
|
|
4
|
-
import {
|
|
2
|
+
import { i as EDAAppEvents, o as EDASessionStore, s as EDASessionStoreError } from "../session-store-BpitF4Wg.js";
|
|
3
|
+
import { t as ModelResolver } from "../model-resolver-BfM5YA6A.js";
|
|
4
|
+
import { t as IdGenerator } from "../id-generator-BKGoKjt-.js";
|
|
5
|
+
import { K as EDARuntime, dt as SessionCommandAdmissionError, jt as RunScheduler, nn as EDASink, pn as EDAPromptProjector, q as EDARuntimeConfig, wn as CompactionPolicy, yn as CompactionExecutor } from "../reduced-state-4FSWDdgT.js";
|
|
5
6
|
import { t as EDAKeepAlive } from "../keep-alive-_zFCUvt3.js";
|
|
6
|
-
import { t as SessionEventObserver } from "../session-event-observer-
|
|
7
|
-
import { r as EDAReducerRegistry } from "../reducer-registry-
|
|
8
|
-
import { n as SinkCheckpointStore } from "../sink-checkpoint-store-
|
|
9
|
-
import { t as RunSchedulingWakeup } from "../run-scheduling-wakeup-
|
|
10
|
-
import { i as EDAToolRegistryShape, t as EDAModelToolkit } from "../tool-registry-
|
|
7
|
+
import { t as SessionEventObserver } from "../session-event-observer-BdZltdrK.js";
|
|
8
|
+
import { r as EDAReducerRegistry } from "../reducer-registry-BIhncOHH.js";
|
|
9
|
+
import { n as SinkCheckpointStore } from "../sink-checkpoint-store-C-SY0cG2.js";
|
|
10
|
+
import { t as RunSchedulingWakeup } from "../run-scheduling-wakeup-BH2pHE0U.js";
|
|
11
|
+
import { i as EDAToolRegistryShape, t as EDAModelToolkit } from "../tool-registry-wPsHagF_.js";
|
|
11
12
|
import * as Layer from "effect/Layer";
|
|
12
13
|
import * as Tracer from "effect/Tracer";
|
|
13
14
|
//#region src/services/runtime-layer.d.ts
|
|
@@ -21,6 +22,8 @@ interface EDARuntimeLayerOptions {
|
|
|
21
22
|
/** Complete application event union with literal namespaces, decoded once at the store boundary. */
|
|
22
23
|
readonly appEvents?: EDAAppEvents;
|
|
23
24
|
readonly config: EDARuntimeConfig;
|
|
25
|
+
/** Host-owned identity source, shared by every lifecycle service. Defaults to `IdGenerator.Live`. */
|
|
26
|
+
readonly idGeneratorLayer?: Layer.Layer<IdGenerator>;
|
|
24
27
|
readonly compactionExecutorLayer?: Layer.Layer<CompactionExecutor>;
|
|
25
28
|
readonly compactionPolicyLayer?: Layer.Layer<CompactionPolicy>;
|
|
26
29
|
readonly keepAliveLayer?: Layer.Layer<EDAKeepAlive>;
|
|
@@ -39,7 +42,7 @@ interface EDARuntimeLayerOptions {
|
|
|
39
42
|
readonly tracer?: Tracer.Tracer;
|
|
40
43
|
}
|
|
41
44
|
/** Compose the complete platform-neutral EDA service graph for one session. */
|
|
42
|
-
declare const makeEDARuntimeLayer: ({ appEvents, config, compactionExecutorLayer, compactionPolicyLayer, keepAliveLayer, modelResolverLayer, promptProjectorLayer, reducerRegistryLayer, runSchedulerLayer, runSchedulingWakeupLayer, sessionId, sessionEventObserverLayer, sessionStoreLayer, sinkCheckpointStoreLayer, sinks, toolkit, toolRegistry, tracer }: EDARuntimeLayerOptions) => Layer.Layer<EDARuntime, SessionCommandAdmissionError>;
|
|
45
|
+
declare const makeEDARuntimeLayer: ({ appEvents, config, idGeneratorLayer, compactionExecutorLayer, compactionPolicyLayer, keepAliveLayer, modelResolverLayer, promptProjectorLayer, reducerRegistryLayer, runSchedulerLayer, runSchedulingWakeupLayer, sessionId, sessionEventObserverLayer, sessionStoreLayer, sinkCheckpointStoreLayer, sinks, toolkit, toolRegistry, tracer }: EDARuntimeLayerOptions) => Layer.Layer<EDARuntime, SessionCommandAdmissionError>;
|
|
43
46
|
//#endregion
|
|
44
47
|
export { EDARuntimeLayerOptions, makeEDARuntimeLayer };
|
|
45
48
|
//# sourceMappingURL=runtime-layer.d.ts.map
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { RunSchedulingWakeup } from "./run-scheduling-wakeup.js";
|
|
2
2
|
import { RunScheduler } from "./run-scheduler.js";
|
|
3
|
-
import { d as TurnRunner, f as InferenceRunner, m as LiveEventBus, p as ToolExecutor, u as SessionState } from "../session-state-
|
|
3
|
+
import { d as TurnRunner, f as InferenceRunner, m as LiveEventBus, p as ToolExecutor, u as SessionState } from "../session-state-BAzdzqV4.js";
|
|
4
4
|
import { EDASessionStore, registerAppEvents } from "./session-store.js";
|
|
5
|
-
import { a as CompactionPolicy, n as CompactionExecutor, o as CompactionRunner } from "../compaction-
|
|
5
|
+
import { a as CompactionPolicy, n as CompactionExecutor, o as CompactionRunner } from "../compaction-GD1cTPTZ.js";
|
|
6
6
|
import { IdGenerator } from "./id-generator.js";
|
|
7
|
-
import { n as SessionContext, t as EventFactory } from "../event-factory-
|
|
7
|
+
import { n as SessionContext, t as EventFactory } from "../event-factory-VAci3NJb.js";
|
|
8
8
|
import { EDAKeepAlive } from "./keep-alive.js";
|
|
9
9
|
import { SessionEventObserver } from "./session-event-observer.js";
|
|
10
10
|
import { EDAPromptProjector } from "./prompt-projector.js";
|
|
11
11
|
import { EDAReducerRegistry } from "./reducer-registry.js";
|
|
12
|
-
import { n as EDASinkRegistry } from "../sink-registry-
|
|
12
|
+
import { n as EDASinkRegistry } from "../sink-registry-BnWfMABI.js";
|
|
13
13
|
import { EDAToolRegistry } from "./tool-registry.js";
|
|
14
14
|
import { EDASessionQuery } from "./session-query.js";
|
|
15
15
|
import { EDARuntime } from "./runtime.js";
|
|
@@ -18,7 +18,7 @@ import * as Layer from "effect/Layer";
|
|
|
18
18
|
import * as Tracer from "effect/Tracer";
|
|
19
19
|
//#region src/services/runtime-layer.ts
|
|
20
20
|
/** Compose the complete platform-neutral EDA service graph for one session. */
|
|
21
|
-
const makeEDARuntimeLayer = ({ appEvents, config, compactionExecutorLayer, compactionPolicyLayer, keepAliveLayer, modelResolverLayer, promptProjectorLayer, reducerRegistryLayer, runSchedulerLayer, runSchedulingWakeupLayer, sessionId, sessionEventObserverLayer, sessionStoreLayer, sinkCheckpointStoreLayer, sinks, toolkit, toolRegistry, tracer }) => {
|
|
21
|
+
const makeEDARuntimeLayer = ({ appEvents, config, idGeneratorLayer, compactionExecutorLayer, compactionPolicyLayer, keepAliveLayer, modelResolverLayer, promptProjectorLayer, reducerRegistryLayer, runSchedulerLayer, runSchedulingWakeupLayer, sessionId, sessionEventObserverLayer, sessionStoreLayer, sinkCheckpointStoreLayer, sinks, toolkit, toolRegistry, tracer }) => {
|
|
22
22
|
const Store = appEvents === void 0 ? sessionStoreLayer : Layer.effect(EDASessionStore, Effect.gen(function* () {
|
|
23
23
|
return registerAppEvents(yield* EDASessionStore, appEvents);
|
|
24
24
|
})).pipe(Layer.provide(sessionStoreLayer));
|
|
@@ -26,7 +26,7 @@ const makeEDARuntimeLayer = ({ appEvents, config, compactionExecutorLayer, compa
|
|
|
26
26
|
const EventObserver = sessionEventObserverLayer ?? SessionEventObserver.Noop;
|
|
27
27
|
const Bus = LiveEventBus.Live.pipe(Layer.provide(EventObserver));
|
|
28
28
|
const KeepAlive = keepAliveLayer ?? EDAKeepAlive.Noop;
|
|
29
|
-
const Ids = IdGenerator.Live;
|
|
29
|
+
const Ids = idGeneratorLayer ?? IdGenerator.Live;
|
|
30
30
|
const Session = SessionContext.Live(sessionId);
|
|
31
31
|
const Factory = EventFactory.Live.pipe(Layer.provideMerge(Layer.mergeAll(Session, Ids)));
|
|
32
32
|
const PromptProjector = promptProjectorLayer ?? EDAPromptProjector.Default;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-layer.js","names":[],"sources":["../../src/services/runtime-layer.ts"],"sourcesContent":["import { ModelResolver } from \"./model-resolver\";\nimport * as Layer from \"effect/Layer\";\nimport * as Tracer from \"effect/Tracer\";\n\nimport type { SessionId } from \"../types/core\";\nimport { CompactionExecutor, CompactionPolicy, CompactionRunner } from \"./compaction\";\nimport { EventFactory } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { InferenceRunner } from \"./inference-runner\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { EDAPromptProjector } from \"./prompt-projector\";\nimport { EDAReducerRegistry } from \"./reducer-registry\";\nimport { EDARuntime, type EDARuntimeConfig } from \"./runtime\";\nimport { RunScheduler } from \"./run-scheduler\";\nimport { RunSchedulingWakeup } from \"./run-scheduling-wakeup\";\nimport { SessionContext } from \"./session-context\";\nimport { SessionEventObserver } from \"./session-event-observer\";\nimport { EDASessionQuery } from \"./session-query\";\nimport * as Effect from \"effect/Effect\";\nimport {\n registerAppEvents,\n type EDAAppEvents,\n EDASessionStore,\n EDASessionStoreError,\n} from \"./session-store\";\nimport { SessionState, type SessionCommandAdmissionError } from \"./session-state\";\nimport { SinkCheckpointStore } from \"./sink-checkpoint-store\";\nimport { EDASinkRegistry, type EDASink } from \"./sink-registry\";\nimport { ToolExecutor } from \"./tool-executor\";\nimport { EDAToolRegistry, type EDAModelToolkit, type EDAToolRegistryShape } from \"./tool-registry\";\nimport { TurnRunner } from \"./turn-runner\";\n\n/**\n * Host-owned adapters and application policy needed to construct one EDA runtime.\n *\n * Core owns the service graph, while hosts supply only semantic persistence,\n * checkpoint, and lifecycle layers. Platform SDK types never cross this boundary.\n */\nexport interface EDARuntimeLayerOptions {\n /** Complete application event union with literal namespaces, decoded once at the store boundary. */\n readonly appEvents?: EDAAppEvents;\n readonly config: EDARuntimeConfig;\n readonly compactionExecutorLayer?: Layer.Layer<CompactionExecutor>;\n readonly compactionPolicyLayer?: Layer.Layer<CompactionPolicy>;\n readonly keepAliveLayer?: Layer.Layer<EDAKeepAlive>;\n readonly modelResolverLayer: Layer.Layer<ModelResolver>;\n readonly promptProjectorLayer?: Layer.Layer<EDAPromptProjector>;\n readonly reducerRegistryLayer?: Layer.Layer<EDAReducerRegistry>;\n readonly runSchedulerLayer?: Layer.Layer<RunScheduler>;\n readonly runSchedulingWakeupLayer?: Layer.Layer<RunSchedulingWakeup>;\n readonly sessionId: SessionId;\n readonly sessionEventObserverLayer?: Layer.Layer<SessionEventObserver>;\n readonly sessionStoreLayer: Layer.Layer<EDASessionStore, EDASessionStoreError>;\n readonly sinkCheckpointStoreLayer: Layer.Layer<SinkCheckpointStore, EDASessionStoreError>;\n readonly sinks?: ReadonlyArray<EDASink>;\n readonly toolkit?: EDAModelToolkit;\n readonly toolRegistry?: EDAToolRegistryShape;\n readonly tracer?: Tracer.Tracer;\n}\n\n/** Compose the complete platform-neutral EDA service graph for one session. */\nexport const makeEDARuntimeLayer = ({\n appEvents,\n config,\n compactionExecutorLayer,\n compactionPolicyLayer,\n keepAliveLayer,\n modelResolverLayer,\n promptProjectorLayer,\n reducerRegistryLayer,\n runSchedulerLayer,\n runSchedulingWakeupLayer,\n sessionId,\n sessionEventObserverLayer,\n sessionStoreLayer,\n sinkCheckpointStoreLayer,\n sinks,\n toolkit,\n toolRegistry,\n tracer,\n}: EDARuntimeLayerOptions): Layer.Layer<EDARuntime, SessionCommandAdmissionError> => {\n const Store =\n appEvents === undefined\n ? sessionStoreLayer\n : Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n return registerAppEvents(yield* EDASessionStore, appEvents);\n }),\n ).pipe(Layer.provide(sessionStoreLayer));\n const Models = modelResolverLayer;\n const EventObserver = sessionEventObserverLayer ?? SessionEventObserver.Noop;\n const Bus = LiveEventBus.Live.pipe(Layer.provide(EventObserver));\n const KeepAlive = keepAliveLayer ?? EDAKeepAlive.Noop;\n const Ids = IdGenerator.Live;\n const Session = SessionContext.Live(sessionId);\n const Factory = EventFactory.Live.pipe(Layer.provideMerge(Layer.mergeAll(Session, Ids)));\n const PromptProjector = promptProjectorLayer ?? EDAPromptProjector.Default;\n const ReducerRegistry = reducerRegistryLayer ?? EDAReducerRegistry.Empty;\n const CompactionPolicyLayer = compactionPolicyLayer ?? CompactionPolicy.Disabled;\n const CompactionExecutorLayer = compactionExecutorLayer ?? CompactionExecutor.Disabled;\n const Compaction = CompactionRunner.Live.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Store,\n Factory,\n Ids,\n KeepAlive,\n Models,\n CompactionPolicyLayer,\n CompactionExecutorLayer,\n ),\n ),\n );\n const SinkRegistry = EDASinkRegistry.Live(sinks ?? []).pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Session,\n Store,\n Bus,\n sinkCheckpointStoreLayer,\n Factory,\n Ids,\n ReducerRegistry,\n KeepAlive,\n ),\n ),\n );\n const State = SessionState.Live.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Store,\n Bus,\n Session,\n ReducerRegistry,\n SinkRegistry,\n KeepAlive,\n Compaction,\n PromptProjector,\n runSchedulerLayer ?? RunScheduler.Immediate,\n runSchedulingWakeupLayer ?? RunSchedulingWakeup.Unsupported,\n ),\n ),\n );\n const Registry =\n toolRegistry !== undefined\n ? EDAToolRegistry.FromShape(toolRegistry)\n : toolkit === undefined\n ? EDAToolRegistry.Empty\n : EDAToolRegistry.FromToolkit(toolkit);\n const InferenceRunnerLayer = InferenceRunner.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(Factory, Models, Registry, Ids)),\n );\n const ToolExec = ToolExecutor.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(Factory, Registry, Ids, Session, Store)),\n );\n const Turn = TurnRunner.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(InferenceRunnerLayer, ToolExec, Factory, Ids)),\n );\n const StateWithRun = State.pipe(Layer.provideMerge(Layer.mergeAll(Turn, Factory, Ids)));\n const Query = EDASessionQuery.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(StateWithRun, Store, Bus)),\n );\n const Runtime = EDARuntime.Live(config).pipe(\n Layer.provideMerge(Layer.mergeAll(StateWithRun, Query)),\n );\n\n return tracer === undefined\n ? Runtime\n : Runtime.pipe(Layer.provideMerge(Layer.succeed(Tracer.Tracer, tracer)));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"runtime-layer.js","names":[],"sources":["../../src/services/runtime-layer.ts"],"sourcesContent":["import { ModelResolver } from \"./model-resolver\";\nimport * as Layer from \"effect/Layer\";\nimport * as Tracer from \"effect/Tracer\";\n\nimport type { SessionId } from \"../types/core\";\nimport { CompactionExecutor, CompactionPolicy, CompactionRunner } from \"./compaction\";\nimport { EventFactory } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { InferenceRunner } from \"./inference-runner\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { EDAPromptProjector } from \"./prompt-projector\";\nimport { EDAReducerRegistry } from \"./reducer-registry\";\nimport { EDARuntime, type EDARuntimeConfig } from \"./runtime\";\nimport { RunScheduler } from \"./run-scheduler\";\nimport { RunSchedulingWakeup } from \"./run-scheduling-wakeup\";\nimport { SessionContext } from \"./session-context\";\nimport { SessionEventObserver } from \"./session-event-observer\";\nimport { EDASessionQuery } from \"./session-query\";\nimport * as Effect from \"effect/Effect\";\nimport {\n registerAppEvents,\n type EDAAppEvents,\n EDASessionStore,\n EDASessionStoreError,\n} from \"./session-store\";\nimport { SessionState, type SessionCommandAdmissionError } from \"./session-state\";\nimport { SinkCheckpointStore } from \"./sink-checkpoint-store\";\nimport { EDASinkRegistry, type EDASink } from \"./sink-registry\";\nimport { ToolExecutor } from \"./tool-executor\";\nimport { EDAToolRegistry, type EDAModelToolkit, type EDAToolRegistryShape } from \"./tool-registry\";\nimport { TurnRunner } from \"./turn-runner\";\n\n/**\n * Host-owned adapters and application policy needed to construct one EDA runtime.\n *\n * Core owns the service graph, while hosts supply only semantic persistence,\n * checkpoint, and lifecycle layers. Platform SDK types never cross this boundary.\n */\nexport interface EDARuntimeLayerOptions {\n /** Complete application event union with literal namespaces, decoded once at the store boundary. */\n readonly appEvents?: EDAAppEvents;\n readonly config: EDARuntimeConfig;\n /** Host-owned identity source, shared by every lifecycle service. Defaults to `IdGenerator.Live`. */\n readonly idGeneratorLayer?: Layer.Layer<IdGenerator>;\n readonly compactionExecutorLayer?: Layer.Layer<CompactionExecutor>;\n readonly compactionPolicyLayer?: Layer.Layer<CompactionPolicy>;\n readonly keepAliveLayer?: Layer.Layer<EDAKeepAlive>;\n readonly modelResolverLayer: Layer.Layer<ModelResolver>;\n readonly promptProjectorLayer?: Layer.Layer<EDAPromptProjector>;\n readonly reducerRegistryLayer?: Layer.Layer<EDAReducerRegistry>;\n readonly runSchedulerLayer?: Layer.Layer<RunScheduler>;\n readonly runSchedulingWakeupLayer?: Layer.Layer<RunSchedulingWakeup>;\n readonly sessionId: SessionId;\n readonly sessionEventObserverLayer?: Layer.Layer<SessionEventObserver>;\n readonly sessionStoreLayer: Layer.Layer<EDASessionStore, EDASessionStoreError>;\n readonly sinkCheckpointStoreLayer: Layer.Layer<SinkCheckpointStore, EDASessionStoreError>;\n readonly sinks?: ReadonlyArray<EDASink>;\n readonly toolkit?: EDAModelToolkit;\n readonly toolRegistry?: EDAToolRegistryShape;\n readonly tracer?: Tracer.Tracer;\n}\n\n/** Compose the complete platform-neutral EDA service graph for one session. */\nexport const makeEDARuntimeLayer = ({\n appEvents,\n config,\n idGeneratorLayer,\n compactionExecutorLayer,\n compactionPolicyLayer,\n keepAliveLayer,\n modelResolverLayer,\n promptProjectorLayer,\n reducerRegistryLayer,\n runSchedulerLayer,\n runSchedulingWakeupLayer,\n sessionId,\n sessionEventObserverLayer,\n sessionStoreLayer,\n sinkCheckpointStoreLayer,\n sinks,\n toolkit,\n toolRegistry,\n tracer,\n}: EDARuntimeLayerOptions): Layer.Layer<EDARuntime, SessionCommandAdmissionError> => {\n const Store =\n appEvents === undefined\n ? sessionStoreLayer\n : Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n return registerAppEvents(yield* EDASessionStore, appEvents);\n }),\n ).pipe(Layer.provide(sessionStoreLayer));\n const Models = modelResolverLayer;\n const EventObserver = sessionEventObserverLayer ?? SessionEventObserver.Noop;\n const Bus = LiveEventBus.Live.pipe(Layer.provide(EventObserver));\n const KeepAlive = keepAliveLayer ?? EDAKeepAlive.Noop;\n const Ids = idGeneratorLayer ?? IdGenerator.Live;\n const Session = SessionContext.Live(sessionId);\n const Factory = EventFactory.Live.pipe(Layer.provideMerge(Layer.mergeAll(Session, Ids)));\n const PromptProjector = promptProjectorLayer ?? EDAPromptProjector.Default;\n const ReducerRegistry = reducerRegistryLayer ?? EDAReducerRegistry.Empty;\n const CompactionPolicyLayer = compactionPolicyLayer ?? CompactionPolicy.Disabled;\n const CompactionExecutorLayer = compactionExecutorLayer ?? CompactionExecutor.Disabled;\n const Compaction = CompactionRunner.Live.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Store,\n Factory,\n Ids,\n KeepAlive,\n Models,\n CompactionPolicyLayer,\n CompactionExecutorLayer,\n ),\n ),\n );\n const SinkRegistry = EDASinkRegistry.Live(sinks ?? []).pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Session,\n Store,\n Bus,\n sinkCheckpointStoreLayer,\n Factory,\n Ids,\n ReducerRegistry,\n KeepAlive,\n ),\n ),\n );\n const State = SessionState.Live.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Store,\n Bus,\n Session,\n ReducerRegistry,\n SinkRegistry,\n KeepAlive,\n Compaction,\n PromptProjector,\n runSchedulerLayer ?? RunScheduler.Immediate,\n runSchedulingWakeupLayer ?? RunSchedulingWakeup.Unsupported,\n ),\n ),\n );\n const Registry =\n toolRegistry !== undefined\n ? EDAToolRegistry.FromShape(toolRegistry)\n : toolkit === undefined\n ? EDAToolRegistry.Empty\n : EDAToolRegistry.FromToolkit(toolkit);\n const InferenceRunnerLayer = InferenceRunner.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(Factory, Models, Registry, Ids)),\n );\n const ToolExec = ToolExecutor.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(Factory, Registry, Ids, Session, Store)),\n );\n const Turn = TurnRunner.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(InferenceRunnerLayer, ToolExec, Factory, Ids)),\n );\n const StateWithRun = State.pipe(Layer.provideMerge(Layer.mergeAll(Turn, Factory, Ids)));\n const Query = EDASessionQuery.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(StateWithRun, Store, Bus)),\n );\n const Runtime = EDARuntime.Live(config).pipe(\n Layer.provideMerge(Layer.mergeAll(StateWithRun, Query)),\n );\n\n return tracer === undefined\n ? Runtime\n : Runtime.pipe(Layer.provideMerge(Layer.succeed(Tracer.Tracer, tracer)));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgEA,MAAa,uBAAuB,EAClC,WACA,QACA,kBACA,yBACA,uBACA,gBACA,oBACA,sBACA,sBACA,mBACA,0BACA,WACA,2BACA,mBACA,0BACA,OACA,SACA,cAC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SAAS,QAAQ,UAAU,GAAG,CAAC,CACnE;CACA,MAAM,WAAW,aAAa,KAAK,KACjC,MAAM,aAAa,MAAM,SAAS,SAAS,UAAU,KAAK,SAAS,KAAK,CAAC,CAC3E;CACA,MAAM,OAAO,WAAW,KAAK,KAC3B,MAAM,aAAa,MAAM,SAAS,sBAAsB,UAAU,SAAS,GAAG,CAAC,CACjF;CACA,MAAM,eAAe,MAAM,KAAK,MAAM,aAAa,MAAM,SAAS,MAAM,SAAS,GAAG,CAAC,CAAC;CACtF,MAAM,QAAQ,gBAAgB,KAAK,KACjC,MAAM,aAAa,MAAM,SAAS,cAAc,OAAO,GAAG,CAAC,CAC7D;CACA,MAAM,UAAU,WAAW,KAAK,MAAM,CAAC,CAAC,KACtC,MAAM,aAAa,MAAM,SAAS,cAAc,KAAK,CAAC,CACxD;CAEA,OAAO,WAAW,KAAA,IACd,UACA,QAAQ,KAAK,MAAM,aAAa,MAAM,QAAQ,OAAO,QAAQ,MAAM,CAAC,CAAC;AAC3E"}
|
|
@@ -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-4FSWDdgT.js";
|
|
2
2
|
export { CommittedCommandTerminalEvent, EDACommandTerminalEvent, EDARuntime, EDARuntimeConfig, EDARuntimeError, EDARuntimeShape, EDARuntimeSubmit };
|
package/dist/services/runtime.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DurablePosition, SequenceNumber, durablePosition } from "../types/core.js";
|
|
2
2
|
import { l as ModelSelectionPayload, m as SystemPromptText, u as NonNegativeInt } from "../envelope-BCzKUq_z.js";
|
|
3
|
-
import { w as CommandFailedEvent, x as CommandCompletedEvent, y as CommandCancelledEvent } from "../durable-
|
|
4
|
-
import { u as SessionState } from "../session-state-
|
|
3
|
+
import { w as CommandFailedEvent, x as CommandCompletedEvent, y as CommandCancelledEvent } from "../durable-CD__3ztN.js";
|
|
4
|
+
import { u as SessionState } from "../session-state-BAzdzqV4.js";
|
|
5
5
|
import { annotateEdaSpan, committedBatchAttributes } from "./tracing.js";
|
|
6
6
|
import { EDASessionQuery } from "./session-query.js";
|
|
7
7
|
import * as Context from "effect/Context";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as SessionEventObserverShape, t as SessionEventObserver } from "../session-event-observer-
|
|
1
|
+
import { n as SessionEventObserverShape, t as SessionEventObserver } from "../session-event-observer-BdZltdrK.js";
|
|
2
2
|
export { SessionEventObserver, SessionEventObserverShape };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as EDASessionQuery, Q as EDASessionEventPage, Z as DurableTranscriptMessages, et as EDASessionQueryShape, tt as EDASessionSnapshot } from "../reduced-state-
|
|
1
|
+
import { $ as EDASessionQuery, Q as EDASessionEventPage, Z as DurableTranscriptMessages, et as EDASessionQueryShape, tt as EDASessionSnapshot } from "../reduced-state-4FSWDdgT.js";
|
|
2
2
|
export { DurableTranscriptMessages, EDASessionEventPage, EDASessionQuery, EDASessionQueryShape, EDASessionSnapshot };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { SequenceNumber } from "../types/core.js";
|
|
2
2
|
import { d as PositionedEvent } from "../envelope-BCzKUq_z.js";
|
|
3
|
-
import { qn as durableEventEnvelope } from "../durable-
|
|
4
|
-
import { m as LiveEventBus, u as SessionState } from "../session-state-
|
|
3
|
+
import { qn as durableEventEnvelope } from "../durable-CD__3ztN.js";
|
|
4
|
+
import { m as LiveEventBus, u as SessionState } from "../session-state-BAzdzqV4.js";
|
|
5
5
|
import { QueryMessageRecordSchema, ReducedStateSchema } from "../domain/reduced-state-schema.js";
|
|
6
6
|
import { EDASessionStore } from "./session-store.js";
|
|
7
7
|
import { durableMessageTranscript } from "../domain/message-transcript.js";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Ct as SessionState, Et as SessionStateSnapshotData, St as SessionRunInput, Tt as SessionStateShape, _t as SessionDrainProcessed, bt as SessionNoRunnableCommand, dt as SessionCommandAdmissionError, ft as SessionCommandCancelled, gt as SessionCommandResult, ht as SessionCommandOutcome, lt as EDASubmittable, mt as SessionCommandFailed, pt as SessionCommandCompleted, ut as SessionCommandAdmissionConflict, vt as SessionDrainResult, wt as SessionStateError, xt as SessionNoRunnableReason, yt as SessionForkedCommand } from "../reduced-state-
|
|
1
|
+
import { Ct as SessionState, Et as SessionStateSnapshotData, St as SessionRunInput, Tt as SessionStateShape, _t as SessionDrainProcessed, bt as SessionNoRunnableCommand, dt as SessionCommandAdmissionError, ft as SessionCommandCancelled, gt as SessionCommandResult, ht as SessionCommandOutcome, lt as EDASubmittable, mt as SessionCommandFailed, pt as SessionCommandCompleted, ut as SessionCommandAdmissionConflict, vt as SessionDrainResult, wt as SessionStateError, xt as SessionNoRunnableReason, yt as SessionForkedCommand } from "../reduced-state-4FSWDdgT.js";
|
|
2
2
|
export { EDASubmittable, SessionCommandAdmissionConflict, SessionCommandAdmissionError, SessionCommandCancelled, SessionCommandCompleted, SessionCommandFailed, SessionCommandOutcome, SessionCommandResult, SessionDrainProcessed, SessionDrainResult, SessionForkedCommand, SessionNoRunnableCommand, SessionNoRunnableReason, SessionRunInput, SessionState, SessionStateError, SessionStateShape, SessionStateSnapshotData };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as SessionCommandOutcome, c as SessionNoRunnableReason, i as SessionCommandFailed, l as SessionRunInput, n as SessionCommandCancelled, o as SessionForkedCommand, r as SessionCommandCompleted, s as SessionNoRunnableCommand, t as SessionCommandAdmissionConflict, u as SessionState } from "../session-state-
|
|
1
|
+
import { a as SessionCommandOutcome, c as SessionNoRunnableReason, i as SessionCommandFailed, l as SessionRunInput, n as SessionCommandCancelled, o as SessionForkedCommand, r as SessionCommandCompleted, s as SessionNoRunnableCommand, t as SessionCommandAdmissionConflict, u as SessionState } from "../session-state-BAzdzqV4.js";
|
|
2
2
|
export { SessionCommandAdmissionConflict, SessionCommandCancelled, SessionCommandCompleted, SessionCommandFailed, SessionCommandOutcome, SessionForkedCommand, SessionNoRunnableCommand, SessionNoRunnableReason, SessionRunInput, SessionState };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as EDAReducerCheckpoint, c as EDASessionStoreShape, d as hasEDASessionStoreError, f as queryCommittedEvents, i as EDAAppEvents, l as FindCommandAdmissionInput, m as selectCommittedEvent, n as DurableAppendBatch, o as EDASessionStore, p as registerAppEvents, r as DurableAppendEntry, s as EDASessionStoreError, t as CommittedDurableEvent, u as SaveReducerCheckpointInput } from "../session-store-
|
|
1
|
+
import { a as EDAReducerCheckpoint, c as EDASessionStoreShape, d as hasEDASessionStoreError, f as queryCommittedEvents, i as EDAAppEvents, l as FindCommandAdmissionInput, m as selectCommittedEvent, n as DurableAppendBatch, o as EDASessionStore, p as registerAppEvents, r as DurableAppendEntry, s as EDASessionStoreError, t as CommittedDurableEvent, u as SaveReducerCheckpointInput } from "../session-store-BpitF4Wg.js";
|
|
2
2
|
export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDAAppEvents, EDAReducerCheckpoint, EDASessionStore, EDASessionStoreError, EDASessionStoreShape, FindCommandAdmissionInput, SaveReducerCheckpointInput, hasEDASessionStoreError, queryCommittedEvents, registerAppEvents, selectCommittedEvent };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CommandId, DurablePosition, SequenceNumber, durablePosition } from "../types/core.js";
|
|
2
2
|
import { t as DurableEventEnvelope } from "../envelope-BCzKUq_z.js";
|
|
3
|
-
import { H as DecodedDurableEvent, Nn as commandAdmittedEventType, Un as contextRebasedEventType, Wn as decodeDurableEventSync, mr as summaryCreatedEventType, qn as durableEventEnvelope } from "../durable-
|
|
3
|
+
import { H as DecodedDurableEvent, Nn as commandAdmittedEventType, Un as contextRebasedEventType, Wn as decodeDurableEventSync, kr as decodeRetainingExcess, mr as summaryCreatedEventType, qn as durableEventEnvelope } from "../durable-CD__3ztN.js";
|
|
4
4
|
import { CompactionSummaryArtifact } from "../domain/context-projection.js";
|
|
5
5
|
import * as Context from "effect/Context";
|
|
6
6
|
import * as Effect from "effect/Effect";
|
|
@@ -26,7 +26,7 @@ const CommittedDurableEvent = Schema.Struct({
|
|
|
26
26
|
* framework services can treat SQL-backed hosts, in-memory tests, and future adapters
|
|
27
27
|
* as the same durability boundary.
|
|
28
28
|
*/
|
|
29
|
-
var EDASessionStoreError = class extends Schema.
|
|
29
|
+
var EDASessionStoreError = class extends Schema.TaggedError()("EDASessionStoreError", { message: Schema.String }) {};
|
|
30
30
|
/** True when a Cause contains an escaped durable-store failure. */
|
|
31
31
|
const hasEDASessionStoreError = (cause) => cause.reasons.some((reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError);
|
|
32
32
|
/**
|
|
@@ -193,7 +193,7 @@ const eventNamespaces = (ast) => {
|
|
|
193
193
|
/** Attach the app decoder to every event-returning store operation without changing storage bytes. */
|
|
194
194
|
const registerAppEvents = (store, schema) => {
|
|
195
195
|
const namespaces = new Set(eventNamespaces(schema.ast));
|
|
196
|
-
const decode =
|
|
196
|
+
const decode = decodeRetainingExcess(schema);
|
|
197
197
|
const envelopeKey = (event) => JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));
|
|
198
198
|
const decodeEntry = (entry, prepared) => {
|
|
199
199
|
if (entry.event.namespace !== "__foreign" || !namespaces.has(entry.event.envelope.namespace)) return entry;
|
|
@@ -201,7 +201,7 @@ const registerAppEvents = (store, schema) => {
|
|
|
201
201
|
...entry,
|
|
202
202
|
event: {
|
|
203
203
|
...entry.event,
|
|
204
|
-
decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope
|
|
204
|
+
decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope)
|
|
205
205
|
}
|
|
206
206
|
};
|
|
207
207
|
};
|
|
@@ -219,7 +219,7 @@ const registerAppEvents = (store, schema) => {
|
|
|
219
219
|
for (const { event } of batch.entries) {
|
|
220
220
|
if (!namespaces.has(event.namespace)) continue;
|
|
221
221
|
const key = envelopeKey(event);
|
|
222
|
-
if (!decoded.has(key)) decoded.set(key, decode(event
|
|
222
|
+
if (!decoded.has(key)) decoded.set(key, decode(event));
|
|
223
223
|
}
|
|
224
224
|
return decoded;
|
|
225
225
|
},
|
|
@@ -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 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\";\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.TaggedErrorClass<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 /** Deterministic in-memory implementation used by runtime and recovery tests. */\n static readonly InMemory = (sessionId: SessionId) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const data = yield* Ref.make<InMemoryStoreData>(emptyInMemoryStoreData());\n return makeInMemoryStore(sessionId, data);\n }),\n );\n\n /** In-memory store seeded with a durable prefix; intended for recovery tests. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n ) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const committed = seedCommittedEvents(sessionId, events);\n const data = yield* Ref.make<InMemoryStoreData>({\n ...emptyInMemoryStoreData(),\n committed,\n summaries: summariesFromCommittedEvents(committed),\n });\n return makeInMemoryStore(sessionId, 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}\n\nconst emptyInMemoryStoreData = (): InMemoryStoreData => ({\n committed: [],\n summaries: new Map(),\n reducerCheckpoints: new Map(),\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\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\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 },\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\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 = Schema.decodeUnknownSync(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:\n prepared?.get(envelopeKey(entry.event.envelope)) ??\n decode(entry.event.envelope, { onExcessProperty: \"preserve\" }),\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, { onExcessProperty: \"preserve\" }));\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":";;;;;;;;;;;;;;AAuCA,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,iBAAuC,CAAC,CACvF,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,MAAa,wBAA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ACG,qBAAqB,KAAK,CAAC,CAC3B,KACC,OAAO,SAAS,UACd,UAAU,KAAA,IAAY,OAAO,QAAQ,KAAA,CAAS,IAAI,kBAAkB,KAAK,CAC3E,CACF;CACN;AACF;;AAGA,MAAa,wBACX,QACA,UACyC;CACzC,MAAM,QACJ,MAAM,MAAM,cAAc,cACrB,MAAM,MAAM,WAAW,MAAM,MAAM,WACpC,MAAM;CACZ,OAAO,OAAO,GAAG,MAAM,CAAC,CAAC,KAAK,IAAI;EAAE,UAAU,MAAM;EAAU;CAAM,IAAI,KAAA;AAC1E;;AAGA,MAAa,wBACX,OACA,QACA,UAA2E,CAAC,MAE5E,MAAM,YAAY,QAAQ,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 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\";\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 /** Deterministic in-memory implementation used by runtime and recovery tests. */\n static readonly InMemory = (sessionId: SessionId) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const data = yield* Ref.make<InMemoryStoreData>(emptyInMemoryStoreData());\n return makeInMemoryStore(sessionId, data);\n }),\n );\n\n /** In-memory store seeded with a durable prefix; intended for recovery tests. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n ) =>\n Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const committed = seedCommittedEvents(sessionId, events);\n const data = yield* Ref.make<InMemoryStoreData>({\n ...emptyInMemoryStoreData(),\n committed,\n summaries: summariesFromCommittedEvents(committed),\n });\n return makeInMemoryStore(sessionId, 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}\n\nconst emptyInMemoryStoreData = (): InMemoryStoreData => ({\n committed: [],\n summaries: new Map(),\n reducerCheckpoints: new Map(),\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\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\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 },\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\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":";;;;;;;;;;;;;;AAwCA,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,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CAAC,KAAK,OAAO,UAAU,iBAAiB,CAAC;EACrF,2BAA2B,SACzB,MAAM,yBAAyB,IAAI,CAAC,CAAC,KAAK,OAAO,QAAQ,aAAa,CAAC;EACzE,uBAAuB,UACrB,MACG,qBAAqB,KAAK,CAAC,CAC3B,KACC,OAAO,SAAS,UACd,UAAU,KAAA,IAAY,OAAO,QAAQ,KAAA,CAAS,IAAI,kBAAkB,KAAK,CAC3E,CACF;CACN;AACF;;AAGA,MAAa,wBACX,QACA,UACyC;CACzC,MAAM,QACJ,MAAM,MAAM,cAAc,cACrB,MAAM,MAAM,WAAW,MAAM,MAAM,WACpC,MAAM;CACZ,OAAO,OAAO,GAAG,MAAM,CAAC,CAAC,KAAK,IAAI;EAAE,UAAU,MAAM;EAAU;CAAM,IAAI,KAAA;AAC1E;;AAGA,MAAa,wBACX,OACA,QACA,UAA2E,CAAC,MAE5E,MAAM,YAAY,QAAQ,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,2 +1,2 @@
|
|
|
1
|
-
import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-
|
|
1
|
+
import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-C-SY0cG2.js";
|
|
2
2
|
export { EDASinkName, SinkCheckpointStore, SinkCheckpointStoreShape, StoredSinkCheckpoint };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $t as EDAProjectedSink, Qt as EDAProjectedDurableSinkDefinition, Xt as EDADurableSinkDefinition, Zt as EDAEphemeralSinkDefinition, an as EDASinkDurableBatch, cn as EDASinkRegistry, en as EDARawDurableSinkDefinition, in as EDASinkContext, ln as EDASinkRegistryShape, nn as EDASink, on as EDASinkInterests, rn as EDASinkCheckpoint, sn as EDASinkRawDurableBatch, tn as EDARawSink, un as EDASinkRunnerStartInput } from "../reduced-state-
|
|
1
|
+
import { $t as EDAProjectedSink, Qt as EDAProjectedDurableSinkDefinition, Xt as EDADurableSinkDefinition, Zt as EDAEphemeralSinkDefinition, an as EDASinkDurableBatch, cn as EDASinkRegistry, en as EDARawDurableSinkDefinition, in as EDASinkContext, ln as EDASinkRegistryShape, nn as EDASink, on as EDASinkInterests, rn as EDASinkCheckpoint, sn as EDASinkRawDurableBatch, tn as EDARawSink, un as EDASinkRunnerStartInput } from "../reduced-state-4FSWDdgT.js";
|
|
2
2
|
export { EDADurableSinkDefinition, EDAEphemeralSinkDefinition, EDAProjectedDurableSinkDefinition, EDAProjectedSink, EDARawDurableSinkDefinition, EDARawSink, EDASink, EDASinkCheckpoint, EDASinkContext, EDASinkDurableBatch, EDASinkInterests, EDASinkRawDurableBatch, EDASinkRegistry, EDASinkRegistryShape, EDASinkRunnerStartInput };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as EDASinkRegistry, t as EDASink } from "../sink-registry-
|
|
1
|
+
import { n as EDASinkRegistry, t as EDASink } from "../sink-registry-BnWfMABI.js";
|
|
2
2
|
export { EDASink, EDASinkRegistry };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as ToolParamsSchema, i as EDAToolRegistryShape, n as EDAToolExecutionContext, o as makeEDAToolkit, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-
|
|
1
|
+
import { a as ToolParamsSchema, i as EDAToolRegistryShape, n as EDAToolExecutionContext, o as makeEDAToolkit, r as EDAToolRegistry, t as EDAModelToolkit } from "../tool-registry-wPsHagF_.js";
|
|
2
2
|
export { EDAModelToolkit, EDAToolExecutionContext, EDAToolRegistry, EDAToolRegistryShape, ToolParamsSchema, makeEDAToolkit };
|
|
@@ -3,8 +3,8 @@ import * as Effect from "effect/Effect";
|
|
|
3
3
|
import * as Layer from "effect/Layer";
|
|
4
4
|
import "effect/Schema";
|
|
5
5
|
import * as Stream from "effect/Stream";
|
|
6
|
-
import * as Tool from "effect/
|
|
7
|
-
import * as Toolkit from "effect/
|
|
6
|
+
import * as Tool from "effect/ai/Tool";
|
|
7
|
+
import * as Toolkit from "effect/ai/Toolkit";
|
|
8
8
|
//#region src/services/tool-registry.ts
|
|
9
9
|
/** Build a handler-backed Effect Toolkit from tools and handlers. */
|
|
10
10
|
const makeEDAToolkit = (tools, handlers) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-registry.js","names":[],"sources":["../../src/services/tool-registry.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\";\nimport * as Tool from \"effect/
|
|
1
|
+
{"version":3,"file":"tool-registry.js","names":[],"sources":["../../src/services/tool-registry.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\";\nimport * as Tool from \"effect/ai/Tool\";\nimport * as Toolkit from \"effect/ai/Toolkit\";\n\nimport { EventId, SessionId, ToolCallId, RunId, TurnId } from \"../types/core\";\nimport { DurableEventEnvelope, ToolName } from \"../types/events\";\nimport type { CommittedDurableEvent, EDASessionStoreError } from \"./session-store\";\n\n/** Runtime parameter schema associated with a provider-visible tool name. */\nexport type ToolParamsSchema = Schema.Top;\n\n/** Provider-visible Effect AI toolkit with handlers available for local execution. */\nexport type EDAModelToolkit = Toolkit.WithHandler<Record<string, Tool.Any>>;\n\n/** Framework context passed to product tool handlers without model-visible params. */\nexport interface EDAToolExecutionContext {\n /** Framework-owned tool-call identity for this execution. */\n readonly toolCallId: ToolCallId;\n /** Run and turn that durably created this tool call. */\n readonly runId: RunId;\n readonly turnId: TurnId;\n /** Read typed facts from this session journal. */\n readonly queryEvents: <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n options?: { readonly limit?: number },\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError>;\n /** Session identity fixed for this runtime instance. */\n readonly sessionId: SessionId;\n /** Mint an app durable event id for tool-emitted facts. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Emit an app durable event through `SessionState`, never directly through the store. */\n readonly emitDurable: (\n event: DurableEventEnvelope,\n ) => Effect.Effect<CommittedDurableEvent, EDASessionStoreError>;\n}\n\n/** Registry contract used by model streaming and post-finish tool execution. */\nexport interface EDAToolRegistryShape {\n /** Look up the parameter schema for a registered tool name. */\n readonly getParamsSchema: (toolName: ToolName) => Effect.Effect<ToolParamsSchema | undefined>;\n /** Build provider-visible tool definitions while keeping EDA in charge of lifecycle events. */\n readonly getModelToolkit: () => Effect.Effect<EDAModelToolkit | undefined>;\n /** Execute a tool. EDA records the durable lifecycle around this effect. */\n readonly execute: (\n toolName: ToolName,\n params: unknown,\n context: EDAToolExecutionContext,\n ) => Effect.Effect<unknown, unknown>;\n}\n\n/** Build a handler-backed Effect Toolkit from tools and handlers. */\nexport const makeEDAToolkit = <const Tools extends ReadonlyArray<Tool.Any>>(\n tools: Tools,\n handlers: Toolkit.HandlersFrom<Toolkit.ToolsByName<Tools>>,\n): Effect.Effect<EDAModelToolkit> => {\n const toolkit = Toolkit.make(...tools);\n return toolkit.pipe(\n Effect.provide(toolkit.toLayer(handlers)),\n Effect.map((withHandlers) => withHandlers as unknown as EDAModelToolkit),\n );\n};\n\nconst makeToolRegistry = (toolkit: EDAModelToolkit | undefined): EDAToolRegistryShape => ({\n getParamsSchema: (toolName) => Effect.succeed(toolkit?.tools[toolName]?.parametersSchema),\n getModelToolkit: () => Effect.succeed(toolkit),\n execute: (toolName, params, _context) =>\n Effect.gen(function* () {\n if (toolkit === undefined || toolkit.tools[toolName] === undefined) {\n return yield* Effect.fail(new Error(`No handler registered for tool ${toolName}`));\n }\n\n const results = yield* (yield* toolkit.handle(toolName, params)).pipe(Stream.runCollect);\n const final = Array.from(results)\n .filter((result) => !result.preliminary)\n .at(-1);\n if (final === undefined) {\n return yield* Effect.fail(new Error(`Tool ${toolName} completed without a final result`));\n }\n if (final.isFailure) {\n return yield* Effect.fail(final.result);\n }\n return final.encodedResult;\n }) as Effect.Effect<unknown, unknown>,\n});\n\nconst toolkitFromSchemas = (\n schemas: ReadonlyMap<string, ToolParamsSchema>,\n): EDAModelToolkit | undefined => {\n if (schemas.size === 0) {\n return undefined;\n }\n\n const tools = Object.fromEntries(\n Array.from(schemas.entries()).map(([name, schema]) => [\n name,\n Tool.dynamic(name, { parameters: schema }),\n ]),\n );\n\n return {\n tools,\n handle: ((name: string) =>\n Effect.die(\n new Error(`No test handler registered for schema-only tool ${name}`),\n )) as unknown as EDAModelToolkit[\"handle\"],\n };\n};\n\n/** Registry of Effect AI tools available to the model and EDA lifecycle executor. */\nexport class EDAToolRegistry extends Context.Service<EDAToolRegistry, EDAToolRegistryShape>()(\n \"@effect-durable-agent/EDAToolRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDAToolRegistry, makeToolRegistry(undefined));\n\n static readonly FromToolkit = (toolkit: EDAModelToolkit) =>\n Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkit));\n\n static readonly FromToolkitEffect = <E, R>(toolkit: Effect.Effect<EDAModelToolkit, E, R>) =>\n Layer.effect(\n EDAToolRegistry,\n toolkit.pipe(Effect.map((withHandlers) => makeToolRegistry(withHandlers))),\n );\n\n static readonly FromShape = (shape: EDAToolRegistryShape) =>\n Layer.succeed(EDAToolRegistry, shape);\n\n static readonly FromShapeEffect = <E, R>(shape: Effect.Effect<EDAToolRegistryShape, E, R>) =>\n Layer.effect(EDAToolRegistry, shape);\n\n /** Test/convenience schema-only tools. Runtime execution will fail unless a real Toolkit is provided. */\n static readonly FromSchemas = (schemas: ReadonlyMap<string, ToolParamsSchema>) =>\n Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkitFromSchemas(schemas)));\n}\n"],"mappings":";;;;;;;;;AAuDA,MAAa,kBACX,OACA,aACmC;CACnC,MAAM,UAAU,QAAQ,KAAK,GAAG,KAAK;CACrC,OAAO,QAAQ,KACb,OAAO,QAAQ,QAAQ,QAAQ,QAAQ,CAAC,GACxC,OAAO,KAAK,iBAAiB,YAA0C,CACzE;AACF;AAEA,MAAM,oBAAoB,aAAgE;CACxF,kBAAkB,aAAa,OAAO,QAAQ,SAAS,MAAM,SAAS,EAAE,gBAAgB;CACxF,uBAAuB,OAAO,QAAQ,OAAO;CAC7C,UAAU,UAAU,QAAQ,aAC1B,OAAO,IAAI,aAAa;EACtB,IAAI,YAAY,KAAA,KAAa,QAAQ,MAAM,cAAc,KAAA,GACvD,OAAO,OAAO,OAAO,qBAAK,IAAI,MAAM,kCAAkC,UAAU,CAAC;EAGnF,MAAM,UAAU,QAAQ,OAAO,QAAQ,OAAO,UAAU,MAAM,EAAA,CAAG,KAAK,OAAO,UAAU;EACvF,MAAM,QAAQ,MAAM,KAAK,OAAO,CAAC,CAC9B,QAAQ,WAAW,CAAC,OAAO,WAAW,CAAC,CACvC,GAAG,EAAE;EACR,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO,OAAO,qBAAK,IAAI,MAAM,QAAQ,SAAS,kCAAkC,CAAC;EAE1F,IAAI,MAAM,WACR,OAAO,OAAO,OAAO,KAAK,MAAM,MAAM;EAExC,OAAO,MAAM;CACf,CAAC;AACL;AAEA,MAAM,sBACJ,YACgC;CAChC,IAAI,QAAQ,SAAS,GACnB;CAUF,OAAO;EACL,OARY,OAAO,YACnB,MAAM,KAAK,QAAQ,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,YAAY,CACpD,MACA,KAAK,QAAQ,MAAM,EAAE,YAAY,OAAO,CAAC,CAC3C,CAAC,CAIG;EACJ,UAAU,SACR,OAAO,oBACL,IAAI,MAAM,mDAAmD,MAAM,CACrE;CACJ;AACF;;AAGA,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,CAAC,CAC3F,uCACF,CAAC,CAAC;CACA,OAAgB,QAAQ,MAAM,QAAQ,iBAAiB,iBAAiB,KAAA,CAAS,CAAC;CAElF,OAAgB,eAAe,YAC7B,MAAM,QAAQ,iBAAiB,iBAAiB,OAAO,CAAC;CAE1D,OAAgB,qBAA2B,YACzC,MAAM,OACJ,iBACA,QAAQ,KAAK,OAAO,KAAK,iBAAiB,iBAAiB,YAAY,CAAC,CAAC,CAC3E;CAEF,OAAgB,aAAa,UAC3B,MAAM,QAAQ,iBAAiB,KAAK;CAEtC,OAAgB,mBAAyB,UACvC,MAAM,OAAO,iBAAiB,KAAK;;CAGrC,OAAgB,eAAe,YAC7B,MAAM,QAAQ,iBAAiB,iBAAiB,mBAAmB,OAAO,CAAC,CAAC;AAChF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { _ as parseEDATraceparent, c as EDATraceLink, d as makeEDAEventTrace, f as makeEDARunTrace, g as makeRootEDATraceMetadata, h as makeRootEDAEventTrace, i as EDATraceAttributeValue, l as EDATraceMetadata, m as makeEDATraceMetadataFromParent, n as EDARunTrace, o as EDATraceContext, p as makeEDATraceContext, t as EDAEventTrace, u as buildEDATraceparent } from "../tracing-BwjbF285.js";
|
|
2
2
|
import { v as UsagePayload } from "../envelope-Che6KatU.js";
|
|
3
|
-
import "../events-
|
|
3
|
+
import "../events-BWuvzVml.js";
|
|
4
4
|
import * as Effect from "effect/Effect";
|
|
5
5
|
import * as Tracer from "effect/Tracer";
|
|
6
6
|
//#region src/services/tracing.d.ts
|
package/dist/services/tracing.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { EDAEventTrace, EDARunTrace, EDATraceContext, EDATraceLink, EDATraceMetadata, buildEDATraceparent, makeEDAEventTrace, makeEDARunTrace, makeEDATraceContext, makeEDATraceMetadataFromParent, makeRootEDAEventTrace, makeRootEDATraceMetadata, parseEDATraceparent } from "../types/tracing.js";
|
|
2
2
|
import * as Effect from "effect/Effect";
|
|
3
|
-
import * as Cause from "effect/Cause";
|
|
4
3
|
import * as Exit from "effect/Exit";
|
|
4
|
+
import * as Cause from "effect/Cause";
|
|
5
5
|
import * as Option from "effect/Option";
|
|
6
6
|
import * as Tracer from "effect/Tracer";
|
|
7
7
|
//#region src/services/tracing.ts
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { f as PositionedEvent } from "./envelope-Che6KatU.js";
|
|
2
|
-
import "./events-
|
|
2
|
+
import "./events-BWuvzVml.js";
|
|
3
3
|
import * as Context from "effect/Context";
|
|
4
4
|
import * as Effect from "effect/Effect";
|
|
5
5
|
import * as Layer from "effect/Layer";
|
|
@@ -21,4 +21,4 @@ declare class SessionEventObserver extends SessionEventObserver_base {
|
|
|
21
21
|
}
|
|
22
22
|
//#endregion
|
|
23
23
|
export { SessionEventObserverShape as n, SessionEventObserver as t };
|
|
24
|
-
//# sourceMappingURL=session-event-observer-
|
|
24
|
+
//# sourceMappingURL=session-event-observer-BdZltdrK.d.ts.map
|
|
@@ -6,29 +6,29 @@ import { ModelResolver } from "./services/model-resolver.js";
|
|
|
6
6
|
import { makeEDARunTrace } from "./types/tracing.js";
|
|
7
7
|
import { d as PositionedEvent, f as ProviderPartId, h as ToolName, l as ModelSelectionPayload, m as SystemPromptText, s as FailurePayload, u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
|
|
8
8
|
import { CancelPendingMessageCommand, PromotePendingMessageCommand, ResumePendingMessagesCommand, StopTurnCommand, SubmitMessageCommand } from "./types/commands.js";
|
|
9
|
-
import { Jn as inferenceCompletedEventType, Kt as ToolCallCreatedEvent, Sr as turnFailedEventType, Yn as inferenceFailedEventType, _ as CommandAdmittedEvent, _r as toolCallCreatedEventType, cn as TurnCompletedEvent, dn as TurnFailedEvent, hn as TurnStoppedEvent, pn as TurnStartedEvent, qn as durableEventEnvelope, yr as toolCallRejectedEventType } from "./durable-
|
|
10
|
-
import { a as encodeReducedStateCheckpoint, h as assertNeverError, i as decodeReducedStateCheckpoint, l as initialReducedState, m as assertNever, n as activeTurnIdentityForCommand, o as foldReducedState, p as reducedStateCheckpointEventSeqs, r as classifyRecoverableWork, s as frameworkReducedStateReducerName } from "./reduced-state-
|
|
9
|
+
import { Jn as inferenceCompletedEventType, Kt as ToolCallCreatedEvent, Sr as turnFailedEventType, Yn as inferenceFailedEventType, _ as CommandAdmittedEvent, _r as toolCallCreatedEventType, cn as TurnCompletedEvent, dn as TurnFailedEvent, hn as TurnStoppedEvent, pn as TurnStartedEvent, qn as durableEventEnvelope, yr as toolCallRejectedEventType } from "./durable-CD__3ztN.js";
|
|
10
|
+
import { a as encodeReducedStateCheckpoint, h as assertNeverError, i as decodeReducedStateCheckpoint, l as initialReducedState, m as assertNever, n as activeTurnIdentityForCommand, o as foldReducedState, p as reducedStateCheckpointEventSeqs, r as classifyRecoverableWork, s as frameworkReducedStateReducerName } from "./reduced-state-Vuud6LCM.js";
|
|
11
11
|
import { ContextProjection, emptyContextProjection } from "./domain/context-projection.js";
|
|
12
12
|
import { CommittedDurableEvent, EDASessionStore, EDASessionStoreError, hasEDASessionStoreError, queryCommittedEvents } from "./services/session-store.js";
|
|
13
|
-
import { d as makeUsagePayload, o as CompactionRunner } from "./compaction-
|
|
13
|
+
import { d as makeUsagePayload, o as CompactionRunner } from "./compaction-GD1cTPTZ.js";
|
|
14
14
|
import { IdGenerator } from "./services/id-generator.js";
|
|
15
|
-
import { n as SessionContext, t as EventFactory } from "./event-factory-
|
|
15
|
+
import { n as SessionContext, t as EventFactory } from "./event-factory-VAci3NJb.js";
|
|
16
16
|
import { annotateEdaSpan, committedBatchAttributes, edaTraceContextFromSpan, eventBatchAttributes, toEdaExternalSpan, usageAttributes } from "./services/tracing.js";
|
|
17
17
|
import { EDAKeepAlive } from "./services/keep-alive.js";
|
|
18
18
|
import { SessionEventObserver } from "./services/session-event-observer.js";
|
|
19
19
|
import { EDAPromptProjector, buildEDAPrompt } from "./services/prompt-projector.js";
|
|
20
20
|
import { EDAReducerRegistry, decodeReducerState, encodeReducerState, reducerSchemaVersion } from "./services/reducer-registry.js";
|
|
21
|
-
import { n as EDASinkRegistry } from "./sink-registry-
|
|
21
|
+
import { n as EDASinkRegistry } from "./sink-registry-BnWfMABI.js";
|
|
22
22
|
import { EDAToolRegistry } from "./services/tool-registry.js";
|
|
23
23
|
import * as Context from "effect/Context";
|
|
24
24
|
import * as Effect from "effect/Effect";
|
|
25
25
|
import * as Layer from "effect/Layer";
|
|
26
26
|
import * as Schema from "effect/Schema";
|
|
27
27
|
import * as Stream from "effect/Stream";
|
|
28
|
-
import * as Prompt from "effect/
|
|
28
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
29
|
+
import * as Exit from "effect/Exit";
|
|
29
30
|
import * as Cause from "effect/Cause";
|
|
30
31
|
import * as Clock from "effect/Clock";
|
|
31
|
-
import * as Exit from "effect/Exit";
|
|
32
32
|
import * as Fiber from "effect/Fiber";
|
|
33
33
|
import * as Queue from "effect/Queue";
|
|
34
34
|
import * as Ref from "effect/Ref";
|
|
@@ -36,7 +36,7 @@ import * as Scope from "effect/Scope";
|
|
|
36
36
|
import * as Semaphore from "effect/Semaphore";
|
|
37
37
|
import * as Option from "effect/Option";
|
|
38
38
|
import * as PubSub from "effect/PubSub";
|
|
39
|
-
import * as Response from "effect/
|
|
39
|
+
import * as Response from "effect/ai/Response";
|
|
40
40
|
//#region src/domain/dispatch-policy.ts
|
|
41
41
|
/** Durable/runtime evidence for active work blocking new queued commands. */
|
|
42
42
|
const DispatchActiveCommand = Schema.TaggedStruct("DispatchActiveCommand", {
|
|
@@ -373,7 +373,7 @@ Schema.Union([
|
|
|
373
373
|
ToolExecutionSkipped
|
|
374
374
|
]);
|
|
375
375
|
/** Failure when tool execution receives a committed event that is not ToolCallCreated. */
|
|
376
|
-
var ToolExecutionEventNotCreated = class extends Schema.
|
|
376
|
+
var ToolExecutionEventNotCreated = class extends Schema.TaggedError()("ToolExecutionEventNotCreated", { eventType: Schema.String }) {};
|
|
377
377
|
/** Construct the live tool-executor implementation. */
|
|
378
378
|
const makeLiveToolExecutor = Effect.gen(function* () {
|
|
379
379
|
const events = yield* EventFactory;
|
|
@@ -476,6 +476,7 @@ const toolCompletedPromptPart = (created, result) => ({
|
|
|
476
476
|
id: created.event.payload.promptPart.id,
|
|
477
477
|
name: created.event.payload.promptPart.name,
|
|
478
478
|
isFailure: false,
|
|
479
|
+
providerExecuted: false,
|
|
479
480
|
result
|
|
480
481
|
}),
|
|
481
482
|
id: created.event.payload.promptPart.id,
|
|
@@ -487,6 +488,7 @@ const toolFailedPromptPart = (created, error) => ({
|
|
|
487
488
|
id: created.event.payload.promptPart.id,
|
|
488
489
|
name: created.event.payload.promptPart.name,
|
|
489
490
|
isFailure: true,
|
|
491
|
+
providerExecuted: false,
|
|
490
492
|
result: error
|
|
491
493
|
}),
|
|
492
494
|
id: created.event.payload.promptPart.id,
|
|
@@ -786,6 +788,7 @@ const toolRejectedPromptPart = (decision) => ({
|
|
|
786
788
|
id: decision.providerPartId,
|
|
787
789
|
name: decision.toolName,
|
|
788
790
|
isFailure: true,
|
|
791
|
+
providerExecuted: false,
|
|
789
792
|
result: {
|
|
790
793
|
message: decision.error.message,
|
|
791
794
|
reason: decision.reason,
|
|
@@ -823,7 +826,7 @@ const InferenceRunResult = Schema.Struct({
|
|
|
823
826
|
partsRecorded: NonNegativeInt,
|
|
824
827
|
terminal: InferenceRunTerminal
|
|
825
828
|
});
|
|
826
|
-
Schema.
|
|
829
|
+
Schema.TaggedError()("UnsupportedInferencePart", {
|
|
827
830
|
partType: Schema.String,
|
|
828
831
|
reason: Schema.String
|
|
829
832
|
});
|
|
@@ -1456,6 +1459,7 @@ const toolFailurePromptPartFromCreated = (created, result) => {
|
|
|
1456
1459
|
id: created.event.payload.promptPart.id,
|
|
1457
1460
|
name: created.event.payload.promptPart.name,
|
|
1458
1461
|
isFailure: true,
|
|
1462
|
+
providerExecuted: false,
|
|
1459
1463
|
result
|
|
1460
1464
|
}),
|
|
1461
1465
|
id: created.event.payload.promptPart.id,
|
|
@@ -1516,7 +1520,7 @@ const SessionNoRunnableCommand = Schema.TaggedStruct("SessionNoRunnableCommand",
|
|
|
1516
1520
|
});
|
|
1517
1521
|
/** Control result when command execution was started in an active child scope. */
|
|
1518
1522
|
const SessionForkedCommand = Schema.TaggedStruct("SessionForkedCommand", { commandId: CommandId });
|
|
1519
|
-
var SessionCommandAdmissionConflict = class extends Schema.
|
|
1523
|
+
var SessionCommandAdmissionConflict = class extends Schema.TaggedError()("SessionCommandAdmissionConflict", {
|
|
1520
1524
|
code: Schema.Literals(["queue_paused", "paused_queue_changed"]),
|
|
1521
1525
|
message: Schema.String,
|
|
1522
1526
|
pausedMessageIds: Schema.Array(MessageId)
|
|
@@ -1535,6 +1539,7 @@ const toolCancelledPromptPartFromRecord = (tool, error) => {
|
|
|
1535
1539
|
id: decision.providerPartId,
|
|
1536
1540
|
name: decision.toolName,
|
|
1537
1541
|
isFailure: true,
|
|
1542
|
+
providerExecuted: false,
|
|
1538
1543
|
result: error
|
|
1539
1544
|
}),
|
|
1540
1545
|
id: decision.providerPartId,
|
|
@@ -3195,4 +3200,4 @@ const isSessionNoRunnableCommand = (result) => "_tag" in result && result._tag =
|
|
|
3195
3200
|
//#endregion
|
|
3196
3201
|
export { SessionCommandOutcome as a, SessionNoRunnableReason as c, TurnRunner as d, InferenceRunner as f, SessionCommandFailed as i, SessionRunInput as l, LiveEventBus as m, SessionCommandCancelled as n, SessionForkedCommand as o, ToolExecutor as p, SessionCommandCompleted as r, SessionNoRunnableCommand as s, SessionCommandAdmissionConflict as t, SessionState as u };
|
|
3197
3202
|
|
|
3198
|
-
//# sourceMappingURL=session-state-
|
|
3203
|
+
//# sourceMappingURL=session-state-BAzdzqV4.js.map
|