effect-durable-agent 0.1.0-alpha.19 → 0.1.0-alpha.21
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-ajHZ5l7f.js} +60 -8
- package/dist/compaction-ajHZ5l7f.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 +2 -2
- package/dist/domain/message-transcript.js +10 -2
- 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-DUms5p6X.d.ts} +10 -4
- package/dist/{reduced-state-DrSHn_47.d.ts → reduced-state-BGd_yCBT.d.ts} +308 -45
- 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 +2 -2
- package/dist/services/compaction.js +2 -2
- package/dist/services/id-generator.js +1 -1
- package/dist/services/id-generator.js.map +1 -1
- package/dist/services/model-call.d.ts +15 -0
- package/dist/services/model-call.js +15 -0
- package/dist/services/model-call.js.map +1 -0
- 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 +2 -2
- package/dist/services/prompt-projector.js +49 -5
- 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 +10 -10
- 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-C_1XxhvE.js} +61 -27
- package/dist/session-state-C_1XxhvE.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-CjK5MC90.js} +4 -4
- package/dist/sink-registry-CjK5MC90.js.map +1 -0
- package/dist/testkit/layers.d.ts +10 -10
- package/dist/testkit/layers.js +13 -10
- 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 +12 -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
|
@@ -2,7 +2,7 @@ import { contextProjectionPrompt } from "../domain/message-transcript.js";
|
|
|
2
2
|
import * as Context from "effect/Context";
|
|
3
3
|
import * as Effect from "effect/Effect";
|
|
4
4
|
import * as Layer from "effect/Layer";
|
|
5
|
-
import * as Prompt from "effect/
|
|
5
|
+
import * as Prompt from "effect/ai/Prompt";
|
|
6
6
|
//#region src/services/prompt-projector.ts
|
|
7
7
|
/** Build a provider prompt entirely from the current durable state projection. */
|
|
8
8
|
const buildEDAPrompt = (projector, input) => Effect.gen(function* () {
|
|
@@ -10,13 +10,33 @@ const buildEDAPrompt = (projector, input) => Effect.gen(function* () {
|
|
|
10
10
|
const context = yield* projector.projectContext(input);
|
|
11
11
|
const transcript = contextProjectionPrompt(state, input.context);
|
|
12
12
|
const instructionBoundary = firstNonSystemMessageIndex(transcript.content);
|
|
13
|
+
const instructions = [...transcript.content.slice(0, instructionBoundary), ...context.instructions];
|
|
14
|
+
const history = transcript.content.slice(instructionBoundary);
|
|
13
15
|
return Prompt.fromMessages([
|
|
14
|
-
...
|
|
15
|
-
...
|
|
16
|
-
...transcript.content.slice(instructionBoundary),
|
|
16
|
+
...markLast(instructions),
|
|
17
|
+
...markLast(history),
|
|
17
18
|
...context.messages
|
|
18
19
|
]);
|
|
19
20
|
});
|
|
21
|
+
/** Prompt option namespace EDA uses for provider-neutral request hints. */
|
|
22
|
+
const EDA_PROMPT_OPTIONS_KEY = "effect-durable-agent";
|
|
23
|
+
/**
|
|
24
|
+
* Whether a message ends a stable prefix worth caching. EDA marks the end of the instruction
|
|
25
|
+
* prefix and the end of durable history, never the per-request data messages after it; provider
|
|
26
|
+
* adapters translate the hint into their own cache breakpoints.
|
|
27
|
+
*/
|
|
28
|
+
const isEDACacheBreakpoint = (message) => {
|
|
29
|
+
const hint = message.options[EDA_PROMPT_OPTIONS_KEY];
|
|
30
|
+
return isHintRecord(hint) && hint.cacheBreakpoint === true;
|
|
31
|
+
};
|
|
32
|
+
const isHintRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
33
|
+
const markLast = (messages) => messages.map((message, index) => index === messages.length - 1 ? {
|
|
34
|
+
...message,
|
|
35
|
+
options: {
|
|
36
|
+
...message.options,
|
|
37
|
+
[EDA_PROMPT_OPTIONS_KEY]: { cacheBreakpoint: true }
|
|
38
|
+
}
|
|
39
|
+
} : message);
|
|
20
40
|
const firstNonSystemMessageIndex = (messages) => {
|
|
21
41
|
const index = messages.findIndex((message) => message.role !== "system");
|
|
22
42
|
return index === -1 ? messages.length : index;
|
|
@@ -31,7 +51,31 @@ var EDAPromptProjector = class EDAPromptProjector extends Context.Service()("@ef
|
|
|
31
51
|
projectState: (input) => Effect.succeed(input.state)
|
|
32
52
|
});
|
|
33
53
|
};
|
|
54
|
+
/** Summary prompt message carrying readable text plus the provider-native compaction items. */
|
|
55
|
+
const nativeCompactionSummaryMessage = (text, native) => Prompt.makeMessage("user", {
|
|
56
|
+
content: [Prompt.textPart({ text })],
|
|
57
|
+
options: { [EDA_PROMPT_OPTIONS_KEY]: { nativeCompaction: {
|
|
58
|
+
provider: native.provider,
|
|
59
|
+
modelId: native.modelId,
|
|
60
|
+
items: [...native.items]
|
|
61
|
+
} } }
|
|
62
|
+
});
|
|
63
|
+
/** Native compaction items stored on a prompt message, if any. */
|
|
64
|
+
const getNativeCompaction = (message) => {
|
|
65
|
+
const hint = message.options[EDA_PROMPT_OPTIONS_KEY];
|
|
66
|
+
if (!isHintRecord(hint)) return void 0;
|
|
67
|
+
const native = hint.nativeCompaction;
|
|
68
|
+
if (!isHintRecord(native)) return void 0;
|
|
69
|
+
const { provider, modelId, items } = native;
|
|
70
|
+
if (typeof provider !== "string" || typeof modelId !== "string" || !isJsonArray(items)) return;
|
|
71
|
+
return {
|
|
72
|
+
provider,
|
|
73
|
+
modelId,
|
|
74
|
+
items
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
const isJsonArray = (value) => Array.isArray(value);
|
|
34
78
|
//#endregion
|
|
35
|
-
export { EDAPromptProjector, buildEDAPrompt };
|
|
79
|
+
export { EDAPromptProjector, EDA_PROMPT_OPTIONS_KEY, buildEDAPrompt, getNativeCompaction, isEDACacheBreakpoint, nativeCompactionSummaryMessage };
|
|
36
80
|
|
|
37
81
|
//# sourceMappingURL=prompt-projector.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt-projector.js","names":[],"sources":["../../src/services/prompt-projector.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Prompt from \"effect/
|
|
1
|
+
{"version":3,"file":"prompt-projector.js","names":[],"sources":["../../src/services/prompt-projector.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Prompt from \"effect/ai/Prompt\";\nimport type * as Schema from \"effect/Schema\";\n\nimport { contextProjectionPrompt } from \"../domain/message-transcript\";\nimport type { ContextProjection } from \"../domain/context-projection\";\nimport type { ReducedState } from \"../domain/reduced-state\";\nimport type { SessionId } from \"../types/core\";\nimport type { EDAReducerStateSnapshot } from \"./reducer-registry\";\n\n/** Input for app-extensible state-to-LLM prompt projection. */\nexport interface EDAPromptProjectionInput {\n readonly sessionId: SessionId;\n readonly state: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n readonly context?: ContextProjection;\n}\n\n/** App-derived instructions and data inserted around the durable transcript. */\nexport interface EDAProjectedPromptContext {\n /** Instruction messages placed after durable system context and before transcript history. */\n readonly instructions: ReadonlyArray<Prompt.SystemMessage>;\n /** Data messages placed after transcript history and before scheduler-selected user messages. */\n readonly messages: ReadonlyArray<Prompt.UserMessage>;\n}\n\n/** Host-extensible projection from durable state into provider prompt context. */\nexport interface EDAPromptProjectorShape {\n readonly projectContext: (\n input: EDAPromptProjectionInput,\n ) => Effect.Effect<EDAProjectedPromptContext>;\n readonly projectState: (input: EDAPromptProjectionInput) => Effect.Effect<ReducedState>;\n}\n\n/** Build a provider prompt entirely from the current durable state projection. */\nexport const buildEDAPrompt = (\n projector: EDAPromptProjectorShape,\n input: EDAPromptProjectionInput,\n): Effect.Effect<Prompt.Prompt> =>\n Effect.gen(function* () {\n const state = yield* projector.projectState(input);\n const context = yield* projector.projectContext(input);\n const transcript = contextProjectionPrompt(state, input.context);\n const instructionBoundary = firstNonSystemMessageIndex(transcript.content);\n const instructions = [\n ...transcript.content.slice(0, instructionBoundary),\n ...context.instructions,\n ];\n const history = transcript.content.slice(instructionBoundary);\n return Prompt.fromMessages([\n ...markLast(instructions),\n ...markLast(history),\n ...context.messages,\n ]);\n });\n\n/** Prompt option namespace EDA uses for provider-neutral request hints. */\nexport const EDA_PROMPT_OPTIONS_KEY = \"effect-durable-agent\";\n\n/**\n * Whether a message ends a stable prefix worth caching. EDA marks the end of the instruction\n * prefix and the end of durable history, never the per-request data messages after it; provider\n * adapters translate the hint into their own cache breakpoints.\n */\nexport const isEDACacheBreakpoint = (message: Prompt.Message): boolean => {\n const hint: unknown = message.options[EDA_PROMPT_OPTIONS_KEY];\n return isHintRecord(hint) && hint.cacheBreakpoint === true;\n};\n\nconst isHintRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst markLast = <M extends Prompt.Message>(messages: ReadonlyArray<M>): ReadonlyArray<M> =>\n messages.map((message, index) =>\n index === messages.length - 1\n ? {\n ...message,\n options: { ...message.options, [EDA_PROMPT_OPTIONS_KEY]: { cacheBreakpoint: true } },\n }\n : message,\n );\n\nconst firstNonSystemMessageIndex = (messages: ReadonlyArray<Prompt.Message>): number => {\n const index = messages.findIndex((message) => message.role !== \"system\");\n return index === -1 ? messages.length : index;\n};\n\n/** Service that lets apps derive LLM context independently from UI projections. */\nexport class EDAPromptProjector extends Context.Service<\n EDAPromptProjector,\n EDAPromptProjectorShape\n>()(\"@effect-durable-agent/EDAPromptProjector\") {\n static readonly Default = Layer.succeed(EDAPromptProjector, {\n projectContext: () => Effect.succeed({ instructions: [], messages: [] }),\n projectState: (input) => Effect.succeed(input.state),\n } satisfies EDAPromptProjectorShape);\n}\n\n/**\n * Provider-native compaction output (an Anthropic `compaction` block, an OpenAI compacted window)\n * stored on the summary prompt message. The provider that produced it replays `items` verbatim in\n * place of the message; any other provider sees the message's readable summary text.\n */\nexport interface EDANativeCompaction {\n readonly provider: string;\n readonly modelId: string;\n readonly items: ReadonlyArray<Schema.Json>;\n}\n\n/** Summary prompt message carrying readable text plus the provider-native compaction items. */\nexport const nativeCompactionSummaryMessage = (\n text: string,\n native: EDANativeCompaction,\n): Prompt.UserMessage =>\n Prompt.makeMessage(\"user\", {\n content: [Prompt.textPart({ text })],\n options: {\n [EDA_PROMPT_OPTIONS_KEY]: {\n nativeCompaction: {\n provider: native.provider,\n modelId: native.modelId,\n items: [...native.items],\n },\n },\n },\n });\n\n/** Native compaction items stored on a prompt message, if any. */\nexport const getNativeCompaction = (message: Prompt.Message): EDANativeCompaction | undefined => {\n const hint: unknown = message.options[EDA_PROMPT_OPTIONS_KEY];\n if (!isHintRecord(hint)) return undefined;\n const native: unknown = hint.nativeCompaction;\n if (!isHintRecord(native)) return undefined;\n const { provider, modelId, items } = native;\n if (typeof provider !== \"string\" || typeof modelId !== \"string\" || !isJsonArray(items)) {\n return undefined;\n }\n return { provider, modelId, items };\n};\n\nconst isJsonArray = (value: unknown): value is ReadonlyArray<Schema.Json> => Array.isArray(value);\n"],"mappings":";;;;;;;AAqCA,MAAa,kBACX,WACA,UAEA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,UAAU,aAAa,KAAK;CACjD,MAAM,UAAU,OAAO,UAAU,eAAe,KAAK;CACrD,MAAM,aAAa,wBAAwB,OAAO,MAAM,OAAO;CAC/D,MAAM,sBAAsB,2BAA2B,WAAW,OAAO;CACzE,MAAM,eAAe,CACnB,GAAG,WAAW,QAAQ,MAAM,GAAG,mBAAmB,GAClD,GAAG,QAAQ,YACb;CACA,MAAM,UAAU,WAAW,QAAQ,MAAM,mBAAmB;CAC5D,OAAO,OAAO,aAAa;EACzB,GAAG,SAAS,YAAY;EACxB,GAAG,SAAS,OAAO;EACnB,GAAG,QAAQ;CACb,CAAC;AACH,CAAC;;AAGH,MAAa,yBAAyB;;;;;;AAOtC,MAAa,wBAAwB,YAAqC;CACxE,MAAM,OAAgB,QAAQ,QAAQ;CACtC,OAAO,aAAa,IAAI,KAAK,KAAK,oBAAoB;AACxD;AAEA,MAAM,gBAAgB,UACpB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,MAAM,YAAsC,aAC1C,SAAS,KAAK,SAAS,UAC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DAReducerState, i as EDAReducerRegistryShape, l as defineEDAReducerRegistry, n as EDAReducerDefinition, o as EDAReducersFor, p as reducerSchemaVersion, r as EDAReducerRegistry, s as EDATypedReducerRegistry, t as EDAReducer, u as edaReservedReducerNamePrefix } from "../reducer-registry-
|
|
1
|
+
import { a as EDAReducerStateSnapshot, c as decodeReducerState, d as encodeReducerState, f as getEDAReducerState, i as EDAReducerRegistryShape, l as defineEDAReducerRegistry, n as EDAReducerDefinition, o as EDAReducersFor, p as reducerSchemaVersion, r as EDAReducerRegistry, s as EDATypedReducerRegistry, t as EDAReducer, u as edaReservedReducerNamePrefix } from "../reducer-registry-BIhncOHH.js";
|
|
2
2
|
export { EDAReducer, EDAReducerDefinition, EDAReducerRegistry, EDAReducerRegistryShape, EDAReducerStateSnapshot, EDAReducersFor, EDATypedReducerRegistry, decodeReducerState, defineEDAReducerRegistry, edaReservedReducerNamePrefix, encodeReducerState, getEDAReducerState, reducerSchemaVersion };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Bt as RunResolution, Ft as RunSchedulingDeliveryError, Ht as RunSchedulingInput, It as DeferredRunResolution, Lt as LocalRunResolution, Mt as RunScheduler, Nt as RunSchedulerShape, Pt as RunSchedulingDelivery } from "../reduced-state-BGd_yCBT.js";
|
|
2
2
|
export { DeferredRunResolution, LocalRunResolution, type RunResolution, RunScheduler, RunSchedulerShape, RunSchedulingDelivery, RunSchedulingDeliveryError, type RunSchedulingInput };
|
|
@@ -5,7 +5,7 @@ import * as Layer from "effect/Layer";
|
|
|
5
5
|
import * as Schema from "effect/Schema";
|
|
6
6
|
//#region src/services/run-scheduler.ts
|
|
7
7
|
/** Recoverable failure delivering a persisted request; it never acknowledges that request. */
|
|
8
|
-
var RunSchedulingDeliveryError = class extends Schema.
|
|
8
|
+
var RunSchedulingDeliveryError = class extends Schema.TaggedError()("RunSchedulingDeliveryError", { message: Schema.String }) {};
|
|
9
9
|
/** Replaceable run-start integration, independent of persistence and host SDKs. */
|
|
10
10
|
var RunScheduler = class RunScheduler extends Context.Service()("@effect-durable-agent/RunScheduler") {
|
|
11
11
|
/** Preserve local execution without allocating IDs, issuing commands, or writing events. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-scheduler.js","names":[],"sources":["../../src/services/run-scheduler.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\";\n\nimport {\n DeferredRunResolution,\n LocalRunResolution,\n type RunResolution,\n type RunSchedulingInput,\n type RunSchedulingRequest,\n} from \"../domain/run-scheduling\";\nimport type { SessionId } from \"../types/core\";\n\nexport {\n DeferredRunResolution,\n LocalRunResolution,\n type RunResolution,\n type RunSchedulingInput,\n} from \"../domain/run-scheduling\";\n\n/** Recoverable failure delivering a persisted request; it never acknowledges that request. */\nexport class RunSchedulingDeliveryError extends Schema.
|
|
1
|
+
{"version":3,"file":"run-scheduler.js","names":[],"sources":["../../src/services/run-scheduler.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\";\n\nimport {\n DeferredRunResolution,\n LocalRunResolution,\n type RunResolution,\n type RunSchedulingInput,\n type RunSchedulingRequest,\n} from \"../domain/run-scheduling\";\nimport type { SessionId } from \"../types/core\";\n\nexport {\n DeferredRunResolution,\n LocalRunResolution,\n type RunResolution,\n type RunSchedulingInput,\n} from \"../domain/run-scheduling\";\n\n/** Recoverable failure delivering a persisted request; it never acknowledges that request. */\nexport class RunSchedulingDeliveryError extends Schema.TaggedError<RunSchedulingDeliveryError>()(\n \"RunSchedulingDeliveryError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** At-least-once outbound delivery, separate from the serialized run-start decision. */\nexport type RunSchedulingDelivery = (input: {\n readonly sessionId: SessionId;\n readonly request: RunSchedulingRequest;\n}) => Effect.Effect<void, RunSchedulingDeliveryError>;\n\n/**\n * Run-start boundary called by SessionState after pure dispatch or recovery policy\n * selects work, before allocating its run ID or committing RunStarted.\n *\n * Resolution must finish promptly with Local or Deferred intent and must not contact\n * an external scheduler. SessionState persists Deferred intent before calling deliver\n * outside the control loop. A successful delivery must mean the scheduler durably\n * accepted responsibility for the request and will retry its trusted grant callback.\n * Calls may repeat after a restart; command identity is not an exactly-once key.\n */\nexport interface RunSchedulerShape {\n readonly resolve: (input: RunSchedulingInput) => Effect.Effect<RunResolution>;\n readonly deliver: RunSchedulingDelivery;\n}\n\n/** Replaceable run-start integration, independent of persistence and host SDKs. */\nexport class RunScheduler extends Context.Service<RunScheduler, RunSchedulerShape>()(\n \"@effect-durable-agent/RunScheduler\",\n) {\n /** Preserve local execution without allocating IDs, issuing commands, or writing events. */\n static readonly Immediate = Layer.succeed(RunScheduler, {\n resolve: () => Effect.succeed(LocalRunResolution.make({})),\n deliver: () => Effect.die(new Error(\"Immediate RunScheduler cannot deliver deferred requests\")),\n });\n\n /** Defer every new run to a durable, idempotent external authorizer. */\n static readonly Deferred = (deliver: RunSchedulingDelivery) =>\n Layer.succeed(RunScheduler, {\n resolve: () => Effect.succeed(DeferredRunResolution.make({})),\n deliver,\n });\n}\n"],"mappings":";;;;;;;AAsBA,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;;AAwBH,IAAa,eAAb,MAAa,qBAAqB,QAAQ,QAAyC,CAAC,CAClF,oCACF,CAAC,CAAC;;CAEA,OAAgB,YAAY,MAAM,QAAQ,cAAc;EACtD,eAAe,OAAO,QAAQ,mBAAmB,KAAK,CAAC,CAAC,CAAC;EACzD,eAAe,OAAO,oBAAI,IAAI,MAAM,yDAAyD,CAAC;CAChG,CAAC;;CAGD,OAAgB,YAAY,YAC1B,MAAM,QAAQ,cAAc;EAC1B,eAAe,OAAO,QAAQ,sBAAsB,KAAK,CAAC,CAAC,CAAC;EAC5D;CACF,CAAC;AACL"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as RunSchedulingWakeupShape, t as RunSchedulingWakeup } from "../run-scheduling-wakeup-
|
|
1
|
+
import { n as RunSchedulingWakeupShape, t as RunSchedulingWakeup } from "../run-scheduling-wakeup-BH2pHE0U.js";
|
|
2
2
|
export { RunSchedulingWakeup, RunSchedulingWakeupShape };
|
|
@@ -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-DUms5p6X.js";
|
|
4
|
+
import { r as EDAReducerRegistry } from "../reducer-registry-BIhncOHH.js";
|
|
5
|
+
import { K as EDARuntime, Mt as RunScheduler, bn as CompactionPolicy, ft as SessionCommandAdmissionError, hn as CompactionExecutor, q as EDARuntimeConfig, rn as EDASink, zn as EDAPromptProjector } from "../reduced-state-BGd_yCBT.js";
|
|
6
|
+
import { i as EDAToolRegistryShape, t as EDAModelToolkit } from "../tool-registry-wPsHagF_.js";
|
|
7
|
+
import { t as IdGenerator } from "../id-generator-BKGoKjt-.js";
|
|
5
8
|
import { t as EDAKeepAlive } from "../keep-alive-_zFCUvt3.js";
|
|
6
|
-
import { t as SessionEventObserver } from "../session-event-observer-
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { t as RunSchedulingWakeup } from "../run-scheduling-wakeup-COUj3r_B.js";
|
|
10
|
-
import { i as EDAToolRegistryShape, t as EDAModelToolkit } from "../tool-registry-DDxbmMpY.js";
|
|
9
|
+
import { t as SessionEventObserver } from "../session-event-observer-BdZltdrK.js";
|
|
10
|
+
import { n as SinkCheckpointStore } from "../sink-checkpoint-store-C-SY0cG2.js";
|
|
11
|
+
import { t as RunSchedulingWakeup } from "../run-scheduling-wakeup-BH2pHE0U.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,16 +1,16 @@
|
|
|
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-C_1XxhvE.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-ajHZ5l7f.js";
|
|
6
|
+
import { EDAPromptProjector } from "./prompt-projector.js";
|
|
7
|
+
import { n as SessionContext, t as EventFactory } from "../event-factory-VAci3NJb.js";
|
|
8
|
+
import { EDAToolRegistry } from "./tool-registry.js";
|
|
6
9
|
import { IdGenerator } from "./id-generator.js";
|
|
7
|
-
import { n as SessionContext, t as EventFactory } from "../event-factory-CKuWhjS4.js";
|
|
8
10
|
import { EDAKeepAlive } from "./keep-alive.js";
|
|
9
11
|
import { SessionEventObserver } from "./session-event-observer.js";
|
|
10
|
-
import { EDAPromptProjector } from "./prompt-projector.js";
|
|
11
12
|
import { EDAReducerRegistry } from "./reducer-registry.js";
|
|
12
|
-
import { n as EDASinkRegistry } from "../sink-registry-
|
|
13
|
-
import { EDAToolRegistry } from "./tool-registry.js";
|
|
13
|
+
import { n as EDASinkRegistry } from "../sink-registry-CjK5MC90.js";
|
|
14
14
|
import { EDASessionQuery } from "./session-query.js";
|
|
15
15
|
import { EDARuntime } from "./runtime.js";
|
|
16
16
|
import * as Effect from "effect/Effect";
|
|
@@ -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,17 +26,17 @@ 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;
|
|
33
33
|
const ReducerRegistry = reducerRegistryLayer ?? EDAReducerRegistry.Empty;
|
|
34
34
|
const CompactionPolicyLayer = compactionPolicyLayer ?? CompactionPolicy.Disabled;
|
|
35
35
|
const CompactionExecutorLayer = compactionExecutorLayer ?? CompactionExecutor.Disabled;
|
|
36
|
-
const
|
|
36
|
+
const Registry = toolRegistry !== void 0 ? EDAToolRegistry.FromShape(toolRegistry) : toolkit === void 0 ? EDAToolRegistry.Empty : EDAToolRegistry.FromToolkit(toolkit);
|
|
37
|
+
const Compaction = CompactionRunner.Live.pipe(Layer.provideMerge(Layer.mergeAll(Store, Factory, Ids, KeepAlive, Models, Session, PromptProjector, Registry, CompactionPolicyLayer, CompactionExecutorLayer)));
|
|
37
38
|
const SinkRegistry = EDASinkRegistry.Live(sinks ?? []).pipe(Layer.provideMerge(Layer.mergeAll(Session, Store, Bus, sinkCheckpointStoreLayer, Factory, Ids, ReducerRegistry, KeepAlive)));
|
|
38
39
|
const State = SessionState.Live.pipe(Layer.provideMerge(Layer.mergeAll(Store, Bus, Session, ReducerRegistry, SinkRegistry, KeepAlive, Compaction, PromptProjector, runSchedulerLayer ?? RunScheduler.Immediate, runSchedulingWakeupLayer ?? RunSchedulingWakeup.Unsupported)));
|
|
39
|
-
const Registry = toolRegistry !== void 0 ? EDAToolRegistry.FromShape(toolRegistry) : toolkit === void 0 ? EDAToolRegistry.Empty : EDAToolRegistry.FromToolkit(toolkit);
|
|
40
40
|
const InferenceRunnerLayer = InferenceRunner.Live.pipe(Layer.provideMerge(Layer.mergeAll(Factory, Models, Registry, Ids)));
|
|
41
41
|
const ToolExec = ToolExecutor.Live.pipe(Layer.provideMerge(Layer.mergeAll(Factory, Registry, Ids, Session, Store)));
|
|
42
42
|
const Turn = TurnRunner.Live.pipe(Layer.provideMerge(Layer.mergeAll(InferenceRunnerLayer, ToolExec, Factory, Ids)));
|
|
@@ -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
|
|
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 Registry =\n toolRegistry !== undefined\n ? EDAToolRegistry.FromShape(toolRegistry)\n : toolkit === undefined\n ? EDAToolRegistry.Empty\n : EDAToolRegistry.FromToolkit(toolkit);\n const Compaction = CompactionRunner.Live.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Store,\n Factory,\n Ids,\n KeepAlive,\n Models,\n Session,\n PromptProjector,\n Registry,\n CompactionPolicyLayer,\n CompactionExecutorLayer,\n ),\n ),\n );\n const SinkRegistry = EDASinkRegistry.Live(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 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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ACA,WACA,YACA,iBACA,qBAAqB,aAAa,WAClC,4BAA4B,oBAAoB,WAClD,CACF,CACF;CACA,MAAM,uBAAuB,gBAAgB,KAAK,KAChD,MAAM,aAAa,MAAM,SAAS,SAAS,QAAQ,UAAU,GAAG,CAAC,CACnE;CACA,MAAM,WAAW,aAAa,KAAK,KACjC,MAAM,aAAa,MAAM,SAAS,SAAS,UAAU,KAAK,SAAS,KAAK,CAAC,CAC3E;CACA,MAAM,OAAO,WAAW,KAAK,KAC3B,MAAM,aAAa,MAAM,SAAS,sBAAsB,UAAU,SAAS,GAAG,CAAC,CACjF;CACA,MAAM,eAAe,MAAM,KAAK,MAAM,aAAa,MAAM,SAAS,MAAM,SAAS,GAAG,CAAC,CAAC;CACtF,MAAM,QAAQ,gBAAgB,KAAK,KACjC,MAAM,aAAa,MAAM,SAAS,cAAc,OAAO,GAAG,CAAC,CAC7D;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-BGd_yCBT.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-C_1XxhvE.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-BGd_yCBT.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-C_1XxhvE.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
|
|
1
|
+
import { Ct as SessionRunInput, Dt as SessionStateSnapshotData, Et as SessionStateShape, St as SessionNoRunnableReason, Tt as SessionStateError, _t as SessionCommandResult, bt as SessionForkedCommand, dt as SessionCommandAdmissionConflict, ft as SessionCommandAdmissionError, gt as SessionCommandOutcome, ht as SessionCommandFailed, mt as SessionCommandCompleted, pt as SessionCommandCancelled, ut as EDASubmittable, vt as SessionDrainProcessed, wt as SessionState, xt as SessionNoRunnableCommand, yt as SessionDrainResult } from "../reduced-state-BGd_yCBT.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-C_1XxhvE.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,wBAAwB,QAAQ,QAA+C,CAAC,CAC3F,uCACF,CAAC,CAAC;;CAEA,OAAgB,YAAY,cAC1B,MAAM,OACJ,iBACA,OAAO,IAAI,aAAa;EACtB,MAAM,OAAO,OAAO,IAAI,KAAwB,uBAA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X,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,EAC9C,SAAS,OAAO,MAAM,kBAAkB,EAC1C,CAAC;;AAsBD,MAAa,4BAA4B,OAAO,OAAO;CACrD,WAAW,OAAO,YAAY,SAAS;CACvC,gBAAgB,OAAO,YAAY,OAAO,MAAM;AAClD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,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
|
|
1
|
+
import { $t as EDAProjectedDurableSinkDefinition, Qt as EDAEphemeralSinkDefinition, Zt as EDADurableSinkDefinition, an as EDASinkContext, cn as EDASinkRawDurableBatch, dn as EDASinkRunnerStartInput, en as EDAProjectedSink, in as EDASinkCheckpoint, ln as EDASinkRegistry, nn as EDARawSink, on as EDASinkDurableBatch, rn as EDASink, sn as EDASinkInterests, tn as EDARawDurableSinkDefinition, un as EDASinkRegistryShape } from "../reduced-state-BGd_yCBT.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-CjK5MC90.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) => {
|