effect-durable-agent 0.1.0-alpha.17 → 0.1.0-alpha.19
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/{commands-p8venTWs.d.ts → commands-3OD-p8dD.d.ts} +7 -8
- package/dist/{compaction-Db6eoLce.js → compaction-Bell28K8.js} +2 -4
- package/dist/{compaction-Db6eoLce.js.map → compaction-Bell28K8.js.map} +1 -1
- package/dist/{context-projection-n6Rdup0N.d.ts → context-projection-D_uRtK3r.d.ts} +13 -14
- package/dist/{core-C-6xHzRx.d.ts → core-BcimKMIv.d.ts} +1 -2
- package/dist/domain/command-queues.d.ts +81 -2
- package/dist/domain/command-queues.js.map +1 -1
- package/dist/domain/context-projection.d.ts +1 -1
- package/dist/domain/message-transcript.d.ts +1 -1
- package/dist/domain/message-transcript.js.map +1 -1
- package/dist/domain/model-usage.d.ts +1 -1
- package/dist/domain/reduced-state-schema.d.ts +3 -992
- package/dist/domain/reduced-state-schema.js +114 -2
- package/dist/domain/reduced-state-schema.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +2 -2
- package/dist/domain/run-scheduling.d.ts +1 -1
- package/dist/domain/run-scheduling.js.map +1 -1
- package/dist/durable-DRY7AcsF.js.map +1 -1
- package/dist/{durable-Ceu9SC2D.d.ts → durable-DoG_e4iL.d.ts} +1486 -1487
- package/dist/envelope-BCzKUq_z.js.map +1 -1
- package/dist/{envelope-VXFEC8zr.d.ts → envelope-Che6KatU.d.ts} +29 -30
- package/dist/event-factory-CKuWhjS4.js.map +1 -1
- package/dist/{events-D3OAPXgS.d.ts → events-sxIzJY26.d.ts} +124 -122
- package/dist/{id-generator--x6itQZ2.d.ts → id-generator-BKGoKjt-.d.ts} +2 -3
- package/dist/index.d.ts +7 -7
- package/dist/index.js +2 -2
- package/dist/{keep-alive-Chl5SJxy.d.ts → keep-alive-_zFCUvt3.d.ts} +1 -2
- package/dist/{model-resolver-ci5D5WQv.d.ts → model-resolver-BHYVHsam.d.ts} +3 -3
- package/dist/{model-usage-CNcnhj72.d.ts → model-usage-0GeHwaaU.d.ts} +2 -3
- package/dist/reduced-state-DFIYylAq.js.map +1 -1
- package/dist/{index-DWC70Fsi.d.ts → reduced-state-DrSHn_47.d.ts} +12581 -9701
- package/dist/reduced-state-schema-CPEmuHLY.d.ts +2167 -0
- package/dist/{reducer-registry-nO4biZlg.d.ts → reducer-registry-C3ZidOI1.d.ts} +8 -7
- package/dist/{run-scheduling-wakeup-CXT5_CkI.d.ts → run-scheduling-wakeup-COUj3r_B.d.ts} +2 -3
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/compaction.js +1 -1
- package/dist/services/id-generator.d.ts +1 -1
- package/dist/services/id-generator.js +2 -1
- package/dist/services/id-generator.js.map +1 -1
- package/dist/services/keep-alive.d.ts +1 -1
- package/dist/services/keep-alive.js.map +1 -1
- package/dist/services/model-resolver.d.ts +1 -1
- package/dist/services/model-resolver.js.map +1 -1
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/prompt-projector.js.map +1 -1
- package/dist/services/reducer-registry.d.ts +1 -1
- package/dist/services/reducer-registry.js.map +1 -1
- package/dist/services/run-scheduler.d.ts +1 -2
- package/dist/services/run-scheduler.js.map +1 -1
- package/dist/services/run-scheduling-wakeup.d.ts +1 -1
- package/dist/services/run-scheduling-wakeup.js.map +1 -1
- package/dist/services/runtime-layer.d.ts +11 -35
- package/dist/services/runtime-layer.js +3 -3
- package/dist/services/runtime-layer.js.map +1 -1
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +12 -3
- package/dist/services/runtime.js.map +1 -1
- package/dist/services/session-event-observer.d.ts +1 -1
- package/dist/services/session-event-observer.js.map +1 -1
- package/dist/services/session-query.d.ts +2 -2
- package/dist/services/session-query.js +24 -8
- package/dist/services/session-query.js.map +1 -1
- 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 -3
- package/dist/services/session-store.js.map +1 -1
- package/dist/services/sink-checkpoint-store.d.ts +1 -1
- package/dist/services/sink-checkpoint-store.js +2 -1
- package/dist/services/sink-checkpoint-store.js.map +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.map +1 -1
- package/dist/services/tracing.d.ts +3 -3
- package/dist/services/tracing.js.map +1 -1
- package/dist/{session-event-observer-BWppl2Fr.d.ts → session-event-observer-BDwja1jX.d.ts} +3 -3
- package/dist/{session-state-8PJZvuR3.js → session-state-BBzzJrDC.js} +78 -50
- package/dist/{session-state-8PJZvuR3.js.map → session-state-BBzzJrDC.js.map} +1 -1
- package/dist/{session-store-DBa-TOVH.d.ts → session-store-B_vh581h.d.ts} +9 -9
- package/dist/{sink-checkpoint-store-BZGfJLve.d.ts → sink-checkpoint-store-2SxoNMbI.d.ts} +3 -4
- package/dist/{sink-registry-B4yxTmlI.js → sink-registry-ogHu2Sw7.js} +2 -2
- package/dist/{sink-registry-B4yxTmlI.js.map → sink-registry-ogHu2Sw7.js.map} +1 -1
- package/dist/testkit/layers.d.ts +13 -18
- package/dist/testkit/layers.js +3 -3
- package/dist/testkit/layers.js.map +1 -1
- package/dist/{tool-registry-NOP9aTHT.d.ts → tool-registry-DDxbmMpY.d.ts} +5 -5
- package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
- package/dist/types/commands.d.ts +1 -1
- package/dist/types/commands.js.map +1 -1
- package/dist/types/core.d.ts +1 -1
- package/dist/types/core.js.map +1 -1
- package/dist/types/events/durable.d.ts +1 -1
- package/dist/types/events.d.ts +4 -4
- package/dist/types/tracing.d.ts +1 -1
- package/dist/types/tracing.js.map +1 -1
- package/dist/websocket.d.ts +197 -187
- package/dist/websocket.js +4 -3
- package/dist/websocket.js.map +1 -1
- package/package.json +7 -7
- package/dist/command-queues-w9WUKTpM.d.ts +0 -556
- package/dist/compaction-DhIJ-sAH.d.ts +0 -165
- package/dist/event-factory-CHP1-DAF.d.ts +0 -91
- package/dist/message-transcript-BfuGCZhP.d.ts +0 -32
- package/dist/prompt-projector-DvNHsoEN.d.ts +0 -39
- package/dist/run-scheduler-DFBqIRzF.d.ts +0 -43
- package/dist/sink-registry-tpmJ-Dhf.d.ts +0 -148
|
@@ -1,16 +1,34 @@
|
|
|
1
1
|
import { SequenceNumber } from "../types/core.js";
|
|
2
2
|
import { d as PositionedEvent } from "../envelope-BCzKUq_z.js";
|
|
3
3
|
import { qn as durableEventEnvelope } from "../durable-DRY7AcsF.js";
|
|
4
|
-
import { m as LiveEventBus, u as SessionState } from "../session-state-
|
|
4
|
+
import { m as LiveEventBus, u as SessionState } from "../session-state-BBzzJrDC.js";
|
|
5
|
+
import { QueryMessageRecordSchema, ReducedStateSchema } from "../domain/reduced-state-schema.js";
|
|
5
6
|
import { EDASessionStore } from "./session-store.js";
|
|
6
7
|
import { durableMessageTranscript } from "../domain/message-transcript.js";
|
|
7
8
|
import { annotateEdaSpan } from "./tracing.js";
|
|
8
9
|
import * as Context from "effect/Context";
|
|
9
10
|
import * as Effect from "effect/Effect";
|
|
10
11
|
import * as Layer from "effect/Layer";
|
|
12
|
+
import * as Schema from "effect/Schema";
|
|
11
13
|
import * as Stream from "effect/Stream";
|
|
12
14
|
import * as PubSub from "effect/PubSub";
|
|
13
15
|
//#region src/services/session-query.ts
|
|
16
|
+
/** Reconnect-safe transcript query preserving the existing structured-clone Prompt parts. */
|
|
17
|
+
const DurableTranscriptMessages = Schema.Array(Schema.Union([
|
|
18
|
+
QueryMessageRecordSchema.members[1],
|
|
19
|
+
QueryMessageRecordSchema.members[3],
|
|
20
|
+
QueryMessageRecordSchema.members[4],
|
|
21
|
+
Schema.Struct({
|
|
22
|
+
...QueryMessageRecordSchema.members[2].fields,
|
|
23
|
+
consumedSeq: SequenceNumber
|
|
24
|
+
})
|
|
25
|
+
]));
|
|
26
|
+
/** Authoritative live snapshot for one EDA session plus its derived durable transcript. */
|
|
27
|
+
const EDASessionSnapshot = Schema.Struct({
|
|
28
|
+
state: ReducedStateSchema,
|
|
29
|
+
reducerStates: Schema.ReadonlyMap(Schema.String, Schema.Unknown),
|
|
30
|
+
messages: DurableTranscriptMessages
|
|
31
|
+
});
|
|
14
32
|
/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */
|
|
15
33
|
var EDASessionQuery = class EDASessionQuery extends Context.Service()("@effect-durable-agent/EDASessionQuery") {
|
|
16
34
|
static Live = Layer.effect(EDASessionQuery, Effect.gen(function* () {
|
|
@@ -60,12 +78,10 @@ var EDASessionQuery = class EDASessionQuery extends Context.Service()("@effect-d
|
|
|
60
78
|
status: "Failed"
|
|
61
79
|
};
|
|
62
80
|
break;
|
|
63
|
-
case "RunInterrupted":
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
};
|
|
68
|
-
break;
|
|
81
|
+
case "RunInterrupted": if (outcome._tag === "Granted" && event.payload.runId === outcome.runId) outcome = {
|
|
82
|
+
...outcome,
|
|
83
|
+
status: "Interrupted"
|
|
84
|
+
};
|
|
69
85
|
}
|
|
70
86
|
})));
|
|
71
87
|
return outcome;
|
|
@@ -134,6 +150,6 @@ const uniquePositionedEvents = (events) => {
|
|
|
134
150
|
return output;
|
|
135
151
|
};
|
|
136
152
|
//#endregion
|
|
137
|
-
export { EDASessionQuery };
|
|
153
|
+
export { DurableTranscriptMessages, EDASessionQuery, EDASessionSnapshot };
|
|
138
154
|
|
|
139
155
|
//# sourceMappingURL=session-query.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-query.js","names":[],"sources":["../../src/services/session-query.ts"],"sourcesContent":["import { durableEventEnvelope } from \"../types/events/durable\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { durableMessageTranscript } from \"../domain/message-transcript\";\nimport type { DurableTranscriptMessage } from \"../domain/message-transcript\";\nimport type { ReducedState } from \"../domain/reduced-state\";\nimport type { EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { RunRequestOutcome } from \"../domain/run-scheduling\";\nimport { effectDurableAgentNamespace } from \"../types/events\";\nimport { type RunRequestId, SequenceNumber } from \"../types/core\";\nimport { PositionedEvent } from \"../types/events\";\nimport { EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { SessionState } from \"./session-state\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Authoritative live snapshot for one EDA session plus its derived durable transcript. */\nexport interface EDASessionSnapshot {\n readonly state: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n readonly messages: ReadonlyArray<DurableTranscriptMessage>;\n}\n\n/** Read-only query facade over authoritative live state and reconnect-safe event streams. */\nexport interface EDASessionQueryShape {\n /** Reconcile one request against committed facts, including after reducer history pruning. */\n readonly runRequestOutcome: (\n requestId: RunRequestId,\n ) => Effect.Effect<RunRequestOutcome, EDASessionStoreError>;\n /** Read the authoritative live state and derive its durable transcript. */\n readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;\n /** Read durable user/assistant messages in committed sequence order from the live snapshot. */\n readonly messages: () => Effect.Effect<\n ReadonlyArray<DurableTranscriptMessage>,\n EDASessionStoreError\n >;\n /** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Effect.Effect<\n Stream.Stream<PositionedEvent, EDASessionStoreError>,\n EDASessionStoreError,\n Scope.Scope\n >;\n /** Read one bounded committed durable slice after `afterSeq` plus the committed head. */\n readonly readEventPage: (\n afterSeq: SequenceNumber,\n limit: number,\n ) => Effect.Effect<EDASessionEventPage, EDASessionStoreError>;\n}\n\n/** Bounded committed durable event page for pull-based host delivery. */\nexport interface EDASessionEventPage {\n readonly events: ReadonlyArray<PositionedEvent>;\n readonly head: SequenceNumber;\n}\n\n/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */\nexport class EDASessionQuery extends Context.Service<EDASessionQuery, EDASessionQueryShape>()(\n \"@effect-durable-agent/EDASessionQuery\",\n) {\n static readonly Live = Layer.effect(\n EDASessionQuery,\n Effect.gen(function* () {\n const store = yield* EDASessionStore;\n const liveBus = yield* LiveEventBus;\n const sessionState = yield* SessionState;\n\n const snapshot = Effect.gen(function* () {\n const data = yield* sessionState.snapshotData();\n return {\n state: data.reduced,\n reducerStates: data.reducerStates,\n messages: durableMessageTranscript(data.reduced),\n } satisfies EDASessionSnapshot;\n });\n\n return {\n runRequestOutcome: Effect.fn(\"agent.run.request.outcome\")(function* (\n requestId: RunRequestId,\n ) {\n const head = (yield* sessionState.snapshot()).lastSeq;\n let outcome: RunRequestOutcome = { _tag: \"Unknown\" };\n yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((entry) => entry.position.seq <= head),\n Stream.runForEach((entry) =>\n Effect.sync(() => {\n const event = entry.event;\n if (event.namespace !== effectDurableAgentNamespace) return;\n switch (event.type) {\n case \"RunSchedulingRequested\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Waiting\" };\n break;\n case \"RunSchedulingInvalidated\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Invalidated\" };\n break;\n case \"RunSchedulingGranted\": {\n const grant = event.payload;\n if (grant.requestId === requestId)\n outcome = { _tag: \"Granted\", runId: grant.runId, status: \"Running\" };\n break;\n }\n case \"RunCompleted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Completed\" };\n break;\n case \"RunFailed\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Failed\" };\n break;\n case \"RunInterrupted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Interrupted\" };\n break;\n }\n }),\n ),\n );\n return outcome;\n }),\n snapshot: () => snapshot,\n messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),\n eventsAfter: (afterSeq: SequenceNumber) =>\n Effect.gen(function* () {\n const live = yield* liveBus.subscribeQueue();\n const replayHead = (yield* sessionState.snapshot()).lastSeq;\n // TODO(backpressure): this runCollect drains the store stream eagerly and buffers the\n // whole durable reconnect prefix, defeating host-level paged replay/backpressure for\n // slow clients. Stream this prefix into the live follow stream instead.\n const replay = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= replayHead),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n const activeTurnReplay = yield* liveBus.activeTurnReplay();\n const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter(\n (event) => shouldEmitLiveEvent(event, replayHead),\n );\n const reconnectPrefix: ReadonlyArray<PositionedEvent> = Array.from(\n uniquePositionedEvents([...replay, ...activeTurnReplay.events, ...pendingLive]),\n ).sort(comparePositionedEvents);\n yield* annotateEdaSpan({\n \"eda.seq.after\": afterSeq,\n \"eda.seq.head\": replayHead,\n \"eda.replay.events\": replay.length,\n \"eda.live.active_turn_events\": activeTurnReplay.events.length,\n \"eda.live.active_turn_overflowed\": activeTurnReplay.overflowed,\n \"eda.live.buffered_events\": pendingLive.length,\n });\n const follow: Stream.Stream<PositionedEvent> = Stream.fromEffectRepeat(\n PubSub.take(live),\n ).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));\n return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));\n }).pipe(\n Effect.withSpan(\"agent.events.follow\", {\n attributes: { \"eda.seq.after\": afterSeq },\n }),\n ),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n Effect.gen(function* () {\n const head = (yield* sessionState.snapshot()).lastSeq;\n if (limit <= 0 || afterSeq >= head) {\n return { events: [], head } satisfies EDASessionEventPage;\n }\n const events = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= head),\n Stream.take(limit),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n return { events, head } satisfies EDASessionEventPage;\n }).pipe(\n Effect.withSpan(\"agent.events.page\", {\n attributes: { \"eda.seq.after\": afterSeq, \"eda.page.limit\": limit },\n }),\n ),\n };\n }),\n );\n}\n\nconst shouldEmitLiveEvent = (event: PositionedEvent, replayHead: SequenceNumber): boolean =>\n event.event.durability === \"ephemeral\" || event.position.seq > replayHead;\n\nconst comparePositionedEvents = (left: PositionedEvent, right: PositionedEvent): number => {\n const seq = left.position.seq - right.position.seq;\n return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;\n};\n\nconst uniquePositionedEvents = (\n events: ReadonlyArray<PositionedEvent>,\n): ReadonlyArray<PositionedEvent> => {\n const seen = new Set<string>();\n const output: PositionedEvent[] = [];\n for (const event of events) {\n const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n output.push(event);\n }\n return output;\n};\n"],"mappings":";;;;;;;;;;;;;;AA+DA,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,EAC1F,uCACF,EAAE;CACA,OAAgB,OAAO,MAAM,OAC3B,iBACA,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO;EACrB,MAAM,UAAU,OAAO;EACvB,MAAM,eAAe,OAAO;EAE5B,MAAM,WAAW,OAAO,IAAI,aAAa;GACvC,MAAM,OAAO,OAAO,aAAa,aAAa;GAC9C,OAAO;IACL,OAAO,KAAK;IACZ,eAAe,KAAK;IACpB,UAAU,yBAAyB,KAAK,OAAO;GACjD;EACF,CAAC;EAED,OAAO;GACL,mB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,SAAS,OAAO,IAAI,GACnD,OAAO,KAAK,KAAK,GACjB,OAAO,KAAK,UACV,gBAAgB,KAAK;MACnB,UAAU,MAAM;MAChB,OAAO,qBAAqB,MAAM,KAAK;KACzC,CAAC,CACH,GACA,OAAO,YACP,OAAO,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,CAC3C;KACiB;IAAK;GACxB,CAAC,EAAE,KACD,OAAO,SAAS,qBAAqB,EACnC,YAAY;IAAE,iBAAiB;IAAU,kBAAkB;GAAM,EACnE,CAAC,CACH;EACJ;CACF,CAAC,CACH;AACF;AAEA,MAAM,uBAAuB,OAAwB,eACnD,MAAM,MAAM,eAAe,eAAe,MAAM,SAAS,MAAM;AAEjE,MAAM,2BAA2B,MAAuB,UAAmC;CACzF,MAAM,MAAM,KAAK,SAAS,MAAM,MAAM,SAAS;CAC/C,OAAO,QAAQ,IAAI,KAAK,SAAS,SAAS,MAAM,SAAS,SAAS;AACpE;AAEA,MAAM,0BACJ,WACmC;CACnC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAA4B,CAAC;CACnC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,MAAM,GAAG,MAAM,SAAS,IAAI,GAAG,MAAM,SAAS,OAAO,GAAG,MAAM,MAAM;EAC1E,IAAI,KAAK,IAAI,GAAG,GACd;EAEF,KAAK,IAAI,GAAG;EACZ,OAAO,KAAK,KAAK;CACnB;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"session-query.js","names":[],"sources":["../../src/services/session-query.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\nimport { ReducedStateSchema, QueryMessageRecordSchema } from \"../domain/reduced-state-schema\";\nimport { durableEventEnvelope } from \"../types/events/durable\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { durableMessageTranscript } from \"../domain/message-transcript\";\nimport type { DurableTranscriptMessage } from \"../domain/message-transcript\";\nimport { RunRequestOutcome } from \"../domain/run-scheduling\";\nimport { effectDurableAgentNamespace } from \"../types/events\";\nimport { type RunRequestId, SequenceNumber } from \"../types/core\";\nimport { PositionedEvent } from \"../types/events\";\nimport { EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { SessionState } from \"./session-state\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Reconnect-safe transcript query preserving the existing structured-clone Prompt parts. */\nexport const DurableTranscriptMessages = Schema.Array(\n Schema.Union([\n QueryMessageRecordSchema.members[1],\n QueryMessageRecordSchema.members[3],\n QueryMessageRecordSchema.members[4],\n Schema.Struct({ ...QueryMessageRecordSchema.members[2].fields, consumedSeq: SequenceNumber }),\n ]),\n);\n/** Authoritative live snapshot for one EDA session plus its derived durable transcript. */\nexport const EDASessionSnapshot = Schema.Struct({\n state: ReducedStateSchema,\n reducerStates: Schema.ReadonlyMap(Schema.String, Schema.Unknown),\n messages: DurableTranscriptMessages,\n});\nexport type EDASessionSnapshot = typeof EDASessionSnapshot.Type;\n\n/** Read-only query facade over authoritative live state and reconnect-safe event streams. */\nexport interface EDASessionQueryShape {\n /** Reconcile one request against committed facts, including after reducer history pruning. */\n readonly runRequestOutcome: (\n requestId: RunRequestId,\n ) => Effect.Effect<RunRequestOutcome, EDASessionStoreError>;\n /** Read the authoritative live state and derive its durable transcript. */\n readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;\n /** Read durable user/assistant messages in committed sequence order from the live snapshot. */\n readonly messages: () => Effect.Effect<\n ReadonlyArray<DurableTranscriptMessage>,\n EDASessionStoreError\n >;\n /** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Effect.Effect<\n Stream.Stream<PositionedEvent, EDASessionStoreError>,\n EDASessionStoreError,\n Scope.Scope\n >;\n /** Read one bounded committed durable slice after `afterSeq` plus the committed head. */\n readonly readEventPage: (\n afterSeq: SequenceNumber,\n limit: number,\n ) => Effect.Effect<EDASessionEventPage, EDASessionStoreError>;\n}\n\n/** Bounded committed durable event page for pull-based host delivery. */\nexport interface EDASessionEventPage {\n readonly events: ReadonlyArray<PositionedEvent>;\n readonly head: SequenceNumber;\n}\n\n/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */\nexport class EDASessionQuery extends Context.Service<EDASessionQuery, EDASessionQueryShape>()(\n \"@effect-durable-agent/EDASessionQuery\",\n) {\n static readonly Live = Layer.effect(\n EDASessionQuery,\n Effect.gen(function* () {\n const store = yield* EDASessionStore;\n const liveBus = yield* LiveEventBus;\n const sessionState = yield* SessionState;\n\n const snapshot = Effect.gen(function* () {\n const data = yield* sessionState.snapshotData();\n return {\n state: data.reduced,\n reducerStates: data.reducerStates,\n messages: durableMessageTranscript(data.reduced),\n } satisfies EDASessionSnapshot;\n });\n\n return {\n runRequestOutcome: Effect.fn(\"agent.run.request.outcome\")(function* (\n requestId: RunRequestId,\n ) {\n const head = (yield* sessionState.snapshot()).lastSeq;\n let outcome: RunRequestOutcome = { _tag: \"Unknown\" };\n yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((entry) => entry.position.seq <= head),\n Stream.runForEach((entry) =>\n Effect.sync(() => {\n const event = entry.event;\n if (event.namespace !== effectDurableAgentNamespace) return;\n switch (event.type) {\n case \"RunSchedulingRequested\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Waiting\" };\n break;\n case \"RunSchedulingInvalidated\":\n if (event.payload.requestId === requestId) outcome = { _tag: \"Invalidated\" };\n break;\n case \"RunSchedulingGranted\": {\n const grant = event.payload;\n if (grant.requestId === requestId)\n outcome = { _tag: \"Granted\", runId: grant.runId, status: \"Running\" };\n break;\n }\n case \"RunCompleted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Completed\" };\n break;\n case \"RunFailed\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Failed\" };\n break;\n case \"RunInterrupted\":\n if (outcome._tag === \"Granted\" && event.payload.runId === outcome.runId)\n outcome = { ...outcome, status: \"Interrupted\" };\n break;\n }\n }),\n ),\n );\n return outcome;\n }),\n snapshot: () => snapshot,\n messages: () => snapshot.pipe(Effect.map((snapshot) => snapshot.messages)),\n eventsAfter: (afterSeq: SequenceNumber) =>\n Effect.gen(function* () {\n const live = yield* liveBus.subscribeQueue();\n const replayHead = (yield* sessionState.snapshot()).lastSeq;\n // TODO(backpressure): this runCollect drains the store stream eagerly and buffers the\n // whole durable reconnect prefix, defeating host-level paged replay/backpressure for\n // slow clients. Stream this prefix into the live follow stream instead.\n const replay = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= replayHead),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n const activeTurnReplay = yield* liveBus.activeTurnReplay();\n const pendingLive = (yield* PubSub.takeUpTo(live, Number.POSITIVE_INFINITY)).filter(\n (event) => shouldEmitLiveEvent(event, replayHead),\n );\n const reconnectPrefix: ReadonlyArray<PositionedEvent> = Array.from(\n uniquePositionedEvents([...replay, ...activeTurnReplay.events, ...pendingLive]),\n ).sort(comparePositionedEvents);\n yield* annotateEdaSpan({\n \"eda.seq.after\": afterSeq,\n \"eda.seq.head\": replayHead,\n \"eda.replay.events\": replay.length,\n \"eda.live.active_turn_events\": activeTurnReplay.events.length,\n \"eda.live.active_turn_overflowed\": activeTurnReplay.overflowed,\n \"eda.live.buffered_events\": pendingLive.length,\n });\n const follow: Stream.Stream<PositionedEvent> = Stream.fromEffectRepeat(\n PubSub.take(live),\n ).pipe(Stream.filter((event) => shouldEmitLiveEvent(event, replayHead)));\n return Stream.fromIterable(reconnectPrefix).pipe(Stream.concat(follow));\n }).pipe(\n Effect.withSpan(\"agent.events.follow\", {\n attributes: { \"eda.seq.after\": afterSeq },\n }),\n ),\n readEventPage: (afterSeq: SequenceNumber, limit: number) =>\n Effect.gen(function* () {\n const head = (yield* sessionState.snapshot()).lastSeq;\n if (limit <= 0 || afterSeq >= head) {\n return { events: [], head } satisfies EDASessionEventPage;\n }\n const events = yield* store.eventsAfter(afterSeq).pipe(\n Stream.filter((entry) => entry.position.seq <= head),\n Stream.take(limit),\n Stream.map((entry) =>\n PositionedEvent.make({\n position: entry.position,\n event: durableEventEnvelope(entry.event),\n }),\n ),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n return { events, head } satisfies EDASessionEventPage;\n }).pipe(\n Effect.withSpan(\"agent.events.page\", {\n attributes: { \"eda.seq.after\": afterSeq, \"eda.page.limit\": limit },\n }),\n ),\n };\n }),\n );\n}\n\nconst shouldEmitLiveEvent = (event: PositionedEvent, replayHead: SequenceNumber): boolean =>\n event.event.durability === \"ephemeral\" || event.position.seq > replayHead;\n\nconst comparePositionedEvents = (left: PositionedEvent, right: PositionedEvent): number => {\n const seq = left.position.seq - right.position.seq;\n return seq === 0 ? left.position.subSeq - right.position.subSeq : seq;\n};\n\nconst uniquePositionedEvents = (\n events: ReadonlyArray<PositionedEvent>,\n): ReadonlyArray<PositionedEvent> => {\n const seen = new Set<string>();\n const output: PositionedEvent[] = [];\n for (const event of events) {\n const key = `${event.position.seq}:${event.position.subSeq}:${event.event.eventId}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n output.push(event);\n }\n return output;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,MAAa,4BAA4B,OAAO,MAC9C,OAAO,MAAM;CACX,yBAAyB,QAAQ;CACjC,yBAAyB,QAAQ;CACjC,yBAAyB,QAAQ;CACjC,OAAO,OAAO;EAAE,GAAG,yBAAyB,QAAQ,EAAE,CAAC;EAAQ,aAAa;CAAe,CAAC;AAC9F,CAAC,CACH;;A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AY;CAC7B,MAAM,SAA4B,CAAC;CACnC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,MAAM,GAAG,MAAM,SAAS,IAAI,GAAG,MAAM,SAAS,OAAO,GAAG,MAAM,MAAM;EAC1E,IAAI,KAAK,IAAI,GAAG,GACd;EAEF,KAAK,IAAI,GAAG;EACZ,OAAO,KAAK,KAAK;CACnB;CACA,OAAO;AACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ct as SessionState, Et as SessionStateSnapshotData, St as SessionRunInput, Tt as SessionStateShape, _t as SessionDrainProcessed, bt as SessionNoRunnableCommand, dt as SessionCommandAdmissionError, ft as SessionCommandCancelled, gt as SessionCommandResult, ht as SessionCommandOutcome, lt as EDASubmittable, mt as SessionCommandFailed, pt as SessionCommandCompleted, ut as SessionCommandAdmissionConflict, vt as SessionDrainResult, wt as SessionStateError, xt as SessionNoRunnableReason, yt as SessionForkedCommand } from "../reduced-state-DrSHn_47.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-BBzzJrDC.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-B_vh581h.js";
|
|
2
2
|
export { CommittedDurableEvent, DurableAppendBatch, DurableAppendEntry, EDAAppEvents, EDAReducerCheckpoint, EDASessionStore, EDASessionStoreError, EDASessionStoreShape, FindCommandAdmissionInput, SaveReducerCheckpointInput, hasEDASessionStoreError, queryCommittedEvents, registerAppEvents, selectCommittedEvent };
|
|
@@ -59,16 +59,18 @@ const FindCommandAdmissionInput = Schema.Struct({
|
|
|
59
59
|
var EDASessionStore = class EDASessionStore extends Context.Service()("@effect-durable-agent/EDASessionStore") {
|
|
60
60
|
/** Deterministic in-memory implementation used by runtime and recovery tests. */
|
|
61
61
|
static InMemory = (sessionId) => Layer.effect(EDASessionStore, Effect.gen(function* () {
|
|
62
|
-
|
|
62
|
+
const data = yield* Ref.make(emptyInMemoryStoreData());
|
|
63
|
+
return makeInMemoryStore(sessionId, data);
|
|
63
64
|
}));
|
|
64
65
|
/** In-memory store seeded with a durable prefix; intended for recovery tests. */
|
|
65
66
|
static InMemorySeeded = (sessionId, events) => Layer.effect(EDASessionStore, Effect.gen(function* () {
|
|
66
67
|
const committed = seedCommittedEvents(sessionId, events);
|
|
67
|
-
|
|
68
|
+
const data = yield* Ref.make({
|
|
68
69
|
...emptyInMemoryStoreData(),
|
|
69
70
|
committed,
|
|
70
71
|
summaries: summariesFromCommittedEvents(committed)
|
|
71
|
-
})
|
|
72
|
+
});
|
|
73
|
+
return makeInMemoryStore(sessionId, data);
|
|
72
74
|
}));
|
|
73
75
|
};
|
|
74
76
|
const emptyInMemoryStoreData = () => ({
|
|
@@ -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,EACtF,wBACA,EACE,SAAS,OAAO,OAClB,CACF,EAAE,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,EAC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,MAAa,wBACX,QACA,UACyC;CACzC,MAAM,QACJ,MAAM,MAAM,cAAc,cACrB,MAAM,MAAM,WAAW,MAAM,MAAM,WACpC,MAAM;CACZ,OAAO,OAAO,GAAG,MAAM,EAAE,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,EAAE,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\";\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,Y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AI,CAAC,CAAC,KAAK,OAAO,QAAQ,aAAa,CAAC;EACzE,uBAAuB,UACrB,MACG,qBAAqB,KAAK,CAAC,CAC3B,KACC,OAAO,SAAS,UACd,UAAU,KAAA,IAAY,OAAO,QAAQ,KAAA,CAAS,IAAI,kBAAkB,KAAK,CAC3E,CACF;CACN;AACF;;AAGA,MAAa,wBACX,QACA,UACyC;CACzC,MAAM,QACJ,MAAM,MAAM,cAAc,cACrB,MAAM,MAAM,WAAW,MAAM,MAAM,WACpC,MAAM;CACZ,OAAO,OAAO,GAAG,MAAM,CAAC,CAAC,KAAK,IAAI;EAAE,UAAU,MAAM;EAAU;CAAM,IAAI,KAAA;AAC1E;;AAGA,MAAa,wBACX,OACA,QACA,UAA2E,CAAC,MAE5E,MAAM,YAAY,QAAQ,YAAY,eAAe,KAAK,CAAC,CAAC,CAAC,CAAC,KAC5D,OAAO,KAAK,UAAU,qBAAqB,QAAQ,KAAK,CAAC,GACzD,OAAO,QAAQ,UAA6C,UAAU,KAAA,CAAS,GAC/E,OAAO,KAAK,QAAQ,SAAS,OAAO,gBAAgB,GACpD,OAAO,UACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-
|
|
1
|
+
import { i as StoredSinkCheckpoint, n as SinkCheckpointStore, r as SinkCheckpointStoreShape, t as EDASinkName } from "../sink-checkpoint-store-2SxoNMbI.js";
|
|
2
2
|
export { EDASinkName, SinkCheckpointStore, SinkCheckpointStoreShape, StoredSinkCheckpoint };
|
|
@@ -17,7 +17,8 @@ const EDASinkName = Schema.NonEmptyString.pipe(Schema.brand("EDASinkName"));
|
|
|
17
17
|
var SinkCheckpointStore = class SinkCheckpointStore extends Context.Service()("@effect-durable-agent/SinkCheckpointStore") {
|
|
18
18
|
/** In-memory checkpoint implementation for store/runtime tests. */
|
|
19
19
|
static InMemory = Layer.effect(SinkCheckpointStore, Effect.gen(function* () {
|
|
20
|
-
|
|
20
|
+
const checkpoints = yield* Ref.make(/* @__PURE__ */ new Map());
|
|
21
|
+
return makeInMemorySinkCheckpointStore(checkpoints);
|
|
21
22
|
}));
|
|
22
23
|
};
|
|
23
24
|
/** Build a ref-backed checkpoint map with the same public semantics as host adapters. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sink-checkpoint-store.js","names":[],"sources":["../../src/services/sink-checkpoint-store.ts"],"sourcesContent":["import * 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\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { EDASessionStoreError } from \"./session-store\";\n\n/** Stable sink name used as the durable checkpoint key. */\nexport const EDASinkName = Schema.NonEmptyString.pipe(Schema.brand(\"EDASinkName\"));\nexport type EDASinkName = typeof EDASinkName.Type;\n\n/** Persisted cursor and sink-owned payload for one registered sink. */\nexport interface StoredSinkCheckpoint {\n readonly afterSeq: SequenceNumber;\n readonly payload: unknown | undefined;\n}\n\n/** Durable checkpoint persistence port for at-least-once sink runners. */\nexport interface SinkCheckpointStoreShape {\n /** Read the latest committed cursor and sink-owned payload. */\n readonly load: (\n sinkName: EDASinkName,\n ) => Effect.Effect<StoredSinkCheckpoint, EDASessionStoreError>;\n /** Save sink-owned state without advancing the durable cursor. */\n readonly saveState: (\n sinkName: EDASinkName,\n payload: unknown,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Atomically commit the processed cursor together with current sink-owned state. */\n readonly commit: (\n sinkName: EDASinkName,\n afterSeq: SequenceNumber,\n payload: unknown | undefined,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * Semantic checkpoint store for registered EDA sinks.\n *\n * Checkpoints are intentionally exposed as load/save/commit operations rather\n * than SQL. Sink side effects happen outside event append transactions, and the\n * cursor advances only after the sink finishes its own external work.\n */\nexport class SinkCheckpointStore extends Context.Service<\n SinkCheckpointStore,\n SinkCheckpointStoreShape\n>()(\"@effect-durable-agent/SinkCheckpointStore\") {\n /** In-memory checkpoint implementation for store/runtime tests. */\n static readonly InMemory = Layer.effect(\n SinkCheckpointStore,\n Effect.gen(function* () {\n const checkpoints = yield* Ref.make<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>(\n new Map(),\n );\n return makeInMemorySinkCheckpointStore(checkpoints);\n }),\n );\n}\n\n/** Build a ref-backed checkpoint map with the same public semantics as host adapters. */\nconst makeInMemorySinkCheckpointStore = (\n checkpoints: Ref.Ref<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>,\n): SinkCheckpointStoreShape => ({\n load: (sinkName) =>\n Ref.get(checkpoints).pipe(\n Effect.map(\n (map) =>\n map.get(sinkName) ?? {\n afterSeq: SequenceNumber.make(0),\n payload: undefined,\n },\n ),\n ),\n saveState: (sinkName, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, {\n afterSeq: map.get(sinkName)?.afterSeq ?? SequenceNumber.make(0),\n payload,\n });\n return next;\n }),\n commit: (sinkName, afterSeq, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, { afterSeq, payload });\n return next;\n }),\n});\n"],"mappings":";;;;;;;;AAUA,MAAa,cAAc,OAAO,eAAe,KAAK,OAAO,MAAM,aAAa,CAAC;;;;;;;;AAmCjF,IAAa,sBAAb,MAAa,4BAA4B,QAAQ,QAG/C,
|
|
1
|
+
{"version":3,"file":"sink-checkpoint-store.js","names":[],"sources":["../../src/services/sink-checkpoint-store.ts"],"sourcesContent":["import * 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\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { EDASessionStoreError } from \"./session-store\";\n\n/** Stable sink name used as the durable checkpoint key. */\nexport const EDASinkName = Schema.NonEmptyString.pipe(Schema.brand(\"EDASinkName\"));\nexport type EDASinkName = typeof EDASinkName.Type;\n\n/** Persisted cursor and sink-owned payload for one registered sink. */\nexport interface StoredSinkCheckpoint {\n readonly afterSeq: SequenceNumber;\n readonly payload: unknown | undefined;\n}\n\n/** Durable checkpoint persistence port for at-least-once sink runners. */\nexport interface SinkCheckpointStoreShape {\n /** Read the latest committed cursor and sink-owned payload. */\n readonly load: (\n sinkName: EDASinkName,\n ) => Effect.Effect<StoredSinkCheckpoint, EDASessionStoreError>;\n /** Save sink-owned state without advancing the durable cursor. */\n readonly saveState: (\n sinkName: EDASinkName,\n payload: unknown,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Atomically commit the processed cursor together with current sink-owned state. */\n readonly commit: (\n sinkName: EDASinkName,\n afterSeq: SequenceNumber,\n payload: unknown | undefined,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * Semantic checkpoint store for registered EDA sinks.\n *\n * Checkpoints are intentionally exposed as load/save/commit operations rather\n * than SQL. Sink side effects happen outside event append transactions, and the\n * cursor advances only after the sink finishes its own external work.\n */\nexport class SinkCheckpointStore extends Context.Service<\n SinkCheckpointStore,\n SinkCheckpointStoreShape\n>()(\"@effect-durable-agent/SinkCheckpointStore\") {\n /** In-memory checkpoint implementation for store/runtime tests. */\n static readonly InMemory = Layer.effect(\n SinkCheckpointStore,\n Effect.gen(function* () {\n const checkpoints = yield* Ref.make<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>(\n new Map(),\n );\n return makeInMemorySinkCheckpointStore(checkpoints);\n }),\n );\n}\n\n/** Build a ref-backed checkpoint map with the same public semantics as host adapters. */\nconst makeInMemorySinkCheckpointStore = (\n checkpoints: Ref.Ref<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>,\n): SinkCheckpointStoreShape => ({\n load: (sinkName) =>\n Ref.get(checkpoints).pipe(\n Effect.map(\n (map) =>\n map.get(sinkName) ?? {\n afterSeq: SequenceNumber.make(0),\n payload: undefined,\n },\n ),\n ),\n saveState: (sinkName, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, {\n afterSeq: map.get(sinkName)?.afterSeq ?? SequenceNumber.make(0),\n payload,\n });\n return next;\n }),\n commit: (sinkName, afterSeq, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, { afterSeq, payload });\n return next;\n }),\n});\n"],"mappings":";;;;;;;;AAUA,MAAa,cAAc,OAAO,eAAe,KAAK,OAAO,MAAM,aAAa,CAAC;;;;;;;;AAmCjF,IAAa,sBAAb,MAAa,4BAA4B,QAAQ,QAG/C,CAAC,CAAC,2CAA2C,CAAC,CAAC;;CAE/C,OAAgB,WAAW,MAAM,OAC/B,qBACA,OAAO,IAAI,aAAa;EACtB,MAAM,cAAc,OAAO,IAAI,qBAC7B,IAAI,IAAI,CACV;EACA,OAAO,gCAAgC,WAAW;CACpD,CAAC,CACH;AACF;;AAGA,MAAM,mCACJ,iBAC8B;CAC9B,OAAO,aACL,IAAI,IAAI,WAAW,CAAC,CAAC,KACnB,OAAO,KACJ,QACC,IAAI,IAAI,QAAQ,KAAK;EACnB,UAAU,eAAe,KAAK,CAAC;EAC/B,SAAS,KAAA;CACX,CACJ,CACF;CACF,YAAY,UAAU,YACpB,IAAI,OAAO,cAAc,QAAQ;EAC/B,MAAM,OAAO,IAAI,IAAI,GAAG;EACxB,KAAK,IAAI,UAAU;GACjB,UAAU,IAAI,IAAI,QAAQ,CAAC,EAAE,YAAY,eAAe,KAAK,CAAC;GAC9D;EACF,CAAC;EACD,OAAO;CACT,CAAC;CACH,SAAS,UAAU,UAAU,YAC3B,IAAI,OAAO,cAAc,QAAQ;EAC/B,MAAM,OAAO,IAAI,IAAI,GAAG;EACxB,KAAK,IAAI,UAAU;GAAE;GAAU;EAAQ,CAAC;EACxC,OAAO;CACT,CAAC;AACL"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $t as EDAProjectedSink, Qt as EDAProjectedDurableSinkDefinition, Xt as EDADurableSinkDefinition, Zt as EDAEphemeralSinkDefinition, an as EDASinkDurableBatch, cn as EDASinkRegistry, en as EDARawDurableSinkDefinition, in as EDASinkContext, ln as EDASinkRegistryShape, nn as EDASink, on as EDASinkInterests, rn as EDASinkCheckpoint, sn as EDASinkRawDurableBatch, tn as EDARawSink, un as EDASinkRunnerStartInput } from "../reduced-state-DrSHn_47.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-ogHu2Sw7.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-DDxbmMpY.js";
|
|
2
2
|
export { EDAModelToolkit, EDAToolExecutionContext, EDAToolRegistry, EDAToolRegistryShape, ToolParamsSchema, makeEDAToolkit };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-registry.js","names":[],"sources":["../../src/services/tool-registry.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as Tool from \"effect/unstable/ai/Tool\";\nimport * as Toolkit from \"effect/unstable/ai/Toolkit\";\n\nimport { EventId, SessionId, ToolCallId, RunId, TurnId } from \"../types/core\";\nimport { DurableEventEnvelope, ToolName } from \"../types/events\";\nimport type { CommittedDurableEvent, EDASessionStoreError } from \"./session-store\";\n\n/** Runtime parameter schema associated with a provider-visible tool name. */\nexport type ToolParamsSchema = Schema.Top;\n\n/** Provider-visible Effect AI toolkit with handlers available for local execution. */\nexport type EDAModelToolkit = Toolkit.WithHandler<Record<string, Tool.Any>>;\n\n/** Framework context passed to product tool handlers without model-visible params. */\nexport interface EDAToolExecutionContext {\n /** Framework-owned tool-call identity for this execution. */\n readonly toolCallId: ToolCallId;\n /** Run and turn that durably created this tool call. */\n readonly runId: RunId;\n readonly turnId: TurnId;\n /** Read typed facts from this session journal. */\n readonly queryEvents: <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n options?: { readonly limit?: number },\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError>;\n /** Session identity fixed for this runtime instance. */\n readonly sessionId: SessionId;\n /** Mint an app durable event id for tool-emitted facts. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Emit an app durable event through `SessionState`, never directly through the store. */\n readonly emitDurable: (\n event: DurableEventEnvelope,\n ) => Effect.Effect<CommittedDurableEvent, EDASessionStoreError>;\n}\n\n/** Registry contract used by model streaming and post-finish tool execution. */\nexport interface EDAToolRegistryShape {\n /** Look up the parameter schema for a registered tool name. */\n readonly getParamsSchema: (toolName: ToolName) => Effect.Effect<ToolParamsSchema | undefined>;\n /** Build provider-visible tool definitions while keeping EDA in charge of lifecycle events. */\n readonly getModelToolkit: () => Effect.Effect<EDAModelToolkit | undefined>;\n /** Execute a tool. EDA records the durable lifecycle around this effect. */\n readonly execute: (\n toolName: ToolName,\n params: unknown,\n context: EDAToolExecutionContext,\n ) => Effect.Effect<unknown, unknown>;\n}\n\n/** Build a handler-backed Effect Toolkit from tools and handlers. */\nexport const makeEDAToolkit = <const Tools extends ReadonlyArray<Tool.Any>>(\n tools: Tools,\n handlers: Toolkit.HandlersFrom<Toolkit.ToolsByName<Tools>>,\n): Effect.Effect<EDAModelToolkit> => {\n const toolkit = Toolkit.make(...tools);\n return toolkit.pipe(\n Effect.provide(toolkit.toLayer(handlers)),\n Effect.map((withHandlers) => withHandlers as unknown as EDAModelToolkit),\n );\n};\n\nconst makeToolRegistry = (toolkit: EDAModelToolkit | undefined): EDAToolRegistryShape => ({\n getParamsSchema: (toolName) => Effect.succeed(toolkit?.tools[toolName]?.parametersSchema),\n getModelToolkit: () => Effect.succeed(toolkit),\n execute: (toolName, params, _context) =>\n Effect.gen(function* () {\n if (toolkit === undefined || toolkit.tools[toolName] === undefined) {\n return yield* Effect.fail(new Error(`No handler registered for tool ${toolName}`));\n }\n\n const results = yield* (yield* toolkit.handle(toolName, params)).pipe(Stream.runCollect);\n const final = Array.from(results)\n .filter((result) => !result.preliminary)\n .at(-1);\n if (final === undefined) {\n return yield* Effect.fail(new Error(`Tool ${toolName} completed without a final result`));\n }\n if (final.isFailure) {\n return yield* Effect.fail(final.result);\n }\n return final.encodedResult;\n }) as Effect.Effect<unknown, unknown>,\n});\n\nconst toolkitFromSchemas = (\n schemas: ReadonlyMap<string, ToolParamsSchema>,\n): EDAModelToolkit | undefined => {\n if (schemas.size === 0) {\n return undefined;\n }\n\n const tools = Object.fromEntries(\n Array.from(schemas.entries()).map(([name, schema]) => [\n name,\n Tool.dynamic(name, { parameters: schema }),\n ]),\n );\n\n return {\n tools,\n handle: ((name: string) =>\n Effect.die(\n new Error(`No test handler registered for schema-only tool ${name}`),\n )) as unknown as EDAModelToolkit[\"handle\"],\n };\n};\n\n/** Registry of Effect AI tools available to the model and EDA lifecycle executor. */\nexport class EDAToolRegistry extends Context.Service<EDAToolRegistry, EDAToolRegistryShape>()(\n \"@effect-durable-agent/EDAToolRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDAToolRegistry, makeToolRegistry(undefined));\n\n static readonly FromToolkit = (toolkit: EDAModelToolkit) =>\n Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkit));\n\n static readonly FromToolkitEffect = <E, R>(toolkit: Effect.Effect<EDAModelToolkit, E, R>) =>\n Layer.effect(\n EDAToolRegistry,\n toolkit.pipe(Effect.map((withHandlers) => makeToolRegistry(withHandlers))),\n );\n\n static readonly FromShape = (shape: EDAToolRegistryShape) =>\n Layer.succeed(EDAToolRegistry, shape);\n\n static readonly FromShapeEffect = <E, R>(shape: Effect.Effect<EDAToolRegistryShape, E, R>) =>\n Layer.effect(EDAToolRegistry, shape);\n\n /** Test/convenience schema-only tools. Runtime execution will fail unless a real Toolkit is provided. */\n static readonly FromSchemas = (schemas: ReadonlyMap<string, ToolParamsSchema>) =>\n Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkitFromSchemas(schemas)));\n}\n"],"mappings":";;;;;;;;;AAuDA,MAAa,kBACX,OACA,aACmC;CACnC,MAAM,UAAU,QAAQ,KAAK,GAAG,KAAK;CACrC,OAAO,QAAQ,KACb,OAAO,QAAQ,QAAQ,QAAQ,QAAQ,CAAC,GACxC,OAAO,KAAK,iBAAiB,YAA0C,CACzE;AACF;AAEA,MAAM,oBAAoB,aAAgE;CACxF,kBAAkB,aAAa,OAAO,QAAQ,SAAS,MAAM,
|
|
1
|
+
{"version":3,"file":"tool-registry.js","names":[],"sources":["../../src/services/tool-registry.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as Tool from \"effect/unstable/ai/Tool\";\nimport * as Toolkit from \"effect/unstable/ai/Toolkit\";\n\nimport { EventId, SessionId, ToolCallId, RunId, TurnId } from \"../types/core\";\nimport { DurableEventEnvelope, ToolName } from \"../types/events\";\nimport type { CommittedDurableEvent, EDASessionStoreError } from \"./session-store\";\n\n/** Runtime parameter schema associated with a provider-visible tool name. */\nexport type ToolParamsSchema = Schema.Top;\n\n/** Provider-visible Effect AI toolkit with handlers available for local execution. */\nexport type EDAModelToolkit = Toolkit.WithHandler<Record<string, Tool.Any>>;\n\n/** Framework context passed to product tool handlers without model-visible params. */\nexport interface EDAToolExecutionContext {\n /** Framework-owned tool-call identity for this execution. */\n readonly toolCallId: ToolCallId;\n /** Run and turn that durably created this tool call. */\n readonly runId: RunId;\n readonly turnId: TurnId;\n /** Read typed facts from this session journal. */\n readonly queryEvents: <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n options?: { readonly limit?: number },\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError>;\n /** Session identity fixed for this runtime instance. */\n readonly sessionId: SessionId;\n /** Mint an app durable event id for tool-emitted facts. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Emit an app durable event through `SessionState`, never directly through the store. */\n readonly emitDurable: (\n event: DurableEventEnvelope,\n ) => Effect.Effect<CommittedDurableEvent, EDASessionStoreError>;\n}\n\n/** Registry contract used by model streaming and post-finish tool execution. */\nexport interface EDAToolRegistryShape {\n /** Look up the parameter schema for a registered tool name. */\n readonly getParamsSchema: (toolName: ToolName) => Effect.Effect<ToolParamsSchema | undefined>;\n /** Build provider-visible tool definitions while keeping EDA in charge of lifecycle events. */\n readonly getModelToolkit: () => Effect.Effect<EDAModelToolkit | undefined>;\n /** Execute a tool. EDA records the durable lifecycle around this effect. */\n readonly execute: (\n toolName: ToolName,\n params: unknown,\n context: EDAToolExecutionContext,\n ) => Effect.Effect<unknown, unknown>;\n}\n\n/** Build a handler-backed Effect Toolkit from tools and handlers. */\nexport const makeEDAToolkit = <const Tools extends ReadonlyArray<Tool.Any>>(\n tools: Tools,\n handlers: Toolkit.HandlersFrom<Toolkit.ToolsByName<Tools>>,\n): Effect.Effect<EDAModelToolkit> => {\n const toolkit = Toolkit.make(...tools);\n return toolkit.pipe(\n Effect.provide(toolkit.toLayer(handlers)),\n Effect.map((withHandlers) => withHandlers as unknown as EDAModelToolkit),\n );\n};\n\nconst makeToolRegistry = (toolkit: EDAModelToolkit | undefined): EDAToolRegistryShape => ({\n getParamsSchema: (toolName) => Effect.succeed(toolkit?.tools[toolName]?.parametersSchema),\n getModelToolkit: () => Effect.succeed(toolkit),\n execute: (toolName, params, _context) =>\n Effect.gen(function* () {\n if (toolkit === undefined || toolkit.tools[toolName] === undefined) {\n return yield* Effect.fail(new Error(`No handler registered for tool ${toolName}`));\n }\n\n const results = yield* (yield* toolkit.handle(toolName, params)).pipe(Stream.runCollect);\n const final = Array.from(results)\n .filter((result) => !result.preliminary)\n .at(-1);\n if (final === undefined) {\n return yield* Effect.fail(new Error(`Tool ${toolName} completed without a final result`));\n }\n if (final.isFailure) {\n return yield* Effect.fail(final.result);\n }\n return final.encodedResult;\n }) as Effect.Effect<unknown, unknown>,\n});\n\nconst toolkitFromSchemas = (\n schemas: ReadonlyMap<string, ToolParamsSchema>,\n): EDAModelToolkit | undefined => {\n if (schemas.size === 0) {\n return undefined;\n }\n\n const tools = Object.fromEntries(\n Array.from(schemas.entries()).map(([name, schema]) => [\n name,\n Tool.dynamic(name, { parameters: schema }),\n ]),\n );\n\n return {\n tools,\n handle: ((name: string) =>\n Effect.die(\n new Error(`No test handler registered for schema-only tool ${name}`),\n )) as unknown as EDAModelToolkit[\"handle\"],\n };\n};\n\n/** Registry of Effect AI tools available to the model and EDA lifecycle executor. */\nexport class EDAToolRegistry extends Context.Service<EDAToolRegistry, EDAToolRegistryShape>()(\n \"@effect-durable-agent/EDAToolRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDAToolRegistry, makeToolRegistry(undefined));\n\n static readonly FromToolkit = (toolkit: EDAModelToolkit) =>\n Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkit));\n\n static readonly FromToolkitEffect = <E, R>(toolkit: Effect.Effect<EDAModelToolkit, E, R>) =>\n Layer.effect(\n EDAToolRegistry,\n toolkit.pipe(Effect.map((withHandlers) => makeToolRegistry(withHandlers))),\n );\n\n static readonly FromShape = (shape: EDAToolRegistryShape) =>\n Layer.succeed(EDAToolRegistry, shape);\n\n static readonly FromShapeEffect = <E, R>(shape: Effect.Effect<EDAToolRegistryShape, E, R>) =>\n Layer.effect(EDAToolRegistry, shape);\n\n /** Test/convenience schema-only tools. Runtime execution will fail unless a real Toolkit is provided. */\n static readonly FromSchemas = (schemas: ReadonlyMap<string, ToolParamsSchema>) =>\n Layer.succeed(EDAToolRegistry, makeToolRegistry(toolkitFromSchemas(schemas)));\n}\n"],"mappings":";;;;;;;;;AAuDA,MAAa,kBACX,OACA,aACmC;CACnC,MAAM,UAAU,QAAQ,KAAK,GAAG,KAAK;CACrC,OAAO,QAAQ,KACb,OAAO,QAAQ,QAAQ,QAAQ,QAAQ,CAAC,GACxC,OAAO,KAAK,iBAAiB,YAA0C,CACzE;AACF;AAEA,MAAM,oBAAoB,aAAgE;CACxF,kBAAkB,aAAa,OAAO,QAAQ,SAAS,MAAM,SAAS,EAAE,gBAAgB;CACxF,uBAAuB,OAAO,QAAQ,OAAO;CAC7C,UAAU,UAAU,QAAQ,aAC1B,OAAO,IAAI,aAAa;EACtB,IAAI,YAAY,KAAA,KAAa,QAAQ,MAAM,cAAc,KAAA,GACvD,OAAO,OAAO,OAAO,qBAAK,IAAI,MAAM,kCAAkC,UAAU,CAAC;EAGnF,MAAM,UAAU,QAAQ,OAAO,QAAQ,OAAO,UAAU,MAAM,EAAA,CAAG,KAAK,OAAO,UAAU;EACvF,MAAM,QAAQ,MAAM,KAAK,OAAO,CAAC,CAC9B,QAAQ,WAAW,CAAC,OAAO,WAAW,CAAC,CACvC,GAAG,EAAE;EACR,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO,OAAO,qBAAK,IAAI,MAAM,QAAQ,SAAS,kCAAkC,CAAC;EAE1F,IAAI,MAAM,WACR,OAAO,OAAO,OAAO,KAAK,MAAM,MAAM;EAExC,OAAO,MAAM;CACf,CAAC;AACL;AAEA,MAAM,sBACJ,YACgC;CAChC,IAAI,QAAQ,SAAS,GACnB;CAUF,OAAO;EACL,OARY,OAAO,YACnB,MAAM,KAAK,QAAQ,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,YAAY,CACpD,MACA,KAAK,QAAQ,MAAM,EAAE,YAAY,OAAO,CAAC,CAC3C,CAAC,CAIG;EACJ,UAAU,SACR,OAAO,oBACL,IAAI,MAAM,mDAAmD,MAAM,CACrE;CACJ;AACF;;AAGA,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAA+C,CAAC,CAC3F,uCACF,CAAC,CAAC;CACA,OAAgB,QAAQ,MAAM,QAAQ,iBAAiB,iBAAiB,KAAA,CAAS,CAAC;CAElF,OAAgB,eAAe,YAC7B,MAAM,QAAQ,iBAAiB,iBAAiB,OAAO,CAAC;CAE1D,OAAgB,qBAA2B,YACzC,MAAM,OACJ,iBACA,QAAQ,KAAK,OAAO,KAAK,iBAAiB,iBAAiB,YAAY,CAAC,CAAC,CAC3E;CAEF,OAAgB,aAAa,UAC3B,MAAM,QAAQ,iBAAiB,KAAK;CAEtC,OAAgB,mBAAyB,UACvC,MAAM,OAAO,iBAAiB,KAAK;;CAGrC,OAAgB,eAAe,YAC7B,MAAM,QAAQ,iBAAiB,iBAAiB,mBAAmB,OAAO,CAAC,CAAC;AAChF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { _ as parseEDATraceparent, c as EDATraceLink, d as makeEDAEventTrace, f as makeEDARunTrace, g as makeRootEDATraceMetadata, h as makeRootEDAEventTrace, i as EDATraceAttributeValue, l as EDATraceMetadata, m as makeEDATraceMetadataFromParent, n as EDARunTrace, o as EDATraceContext, p as makeEDATraceContext, t as EDAEventTrace, u as buildEDATraceparent } from "../tracing-BwjbF285.js";
|
|
2
|
+
import { v as UsagePayload } from "../envelope-Che6KatU.js";
|
|
3
|
+
import "../events-sxIzJY26.js";
|
|
3
4
|
import * as Effect from "effect/Effect";
|
|
4
5
|
import * as Tracer from "effect/Tracer";
|
|
5
|
-
|
|
6
6
|
//#region src/services/tracing.d.ts
|
|
7
7
|
/** Attribute value types accepted by Effect span annotations after compaction. */
|
|
8
8
|
type EdaSpanAttributeValue = EDATraceAttributeValue | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracing.js","names":["#emit"],"sources":["../../src/services/tracing.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Tracer from \"effect/Tracer\";\n\nimport type { UsagePayload } from \"../types/events\";\nimport {\n EDATraceContext,\n type EDAEventTrace,\n type EDATraceAttributeValue,\n type EDATraceMetadata,\n makeEDAEventTrace,\n makeEDATraceContext,\n makeRootEDAEventTrace,\n} from \"../types/tracing\";\n\nexport {\n EDATraceContext,\n EDARunTrace,\n EDATraceLink,\n EDATraceMetadata,\n EDAEventTrace,\n makeEDAEventTrace,\n makeEDARunTrace,\n makeEDATraceContext,\n makeEDATraceMetadataFromParent,\n makeRootEDAEventTrace,\n makeRootEDATraceMetadata,\n} from \"../types/tracing\";\n\nexport { buildEDATraceparent, parseEDATraceparent } from \"../types/tracing\";\n\n/** Attribute value types accepted by Effect span annotations after compaction. */\nexport type EdaSpanAttributeValue = EDATraceAttributeValue | undefined;\n\n/** EDA span attribute map; undefined values are intentionally dropped before annotation. */\nexport type EdaSpanAttributes = Record<string, EdaSpanAttributeValue>;\n\nexport interface EDATracingOptions {\n readonly disableTracing?: boolean;\n readonly disableSpanPropagation?: boolean;\n readonly spanAttributes?: EdaSpanAttributes;\n readonly spanPrefix?: string;\n}\n\nexport interface EDAExportedSpanLink {\n readonly attributes: Record<string, string | number | boolean>;\n readonly sampled: boolean;\n readonly spanId: string;\n readonly traceId: string;\n}\n\nexport interface EDAExportedSpan {\n readonly attributes: Record<string, string | number | boolean>;\n readonly endedAtMs: number;\n readonly endedAtUnixNano: string;\n readonly kind: Tracer.SpanKind;\n readonly links: ReadonlyArray<EDAExportedSpanLink>;\n readonly name: string;\n readonly outcome: \"ok\" | \"error\" | \"timeout\" | \"canceled\";\n readonly parentSpanId?: string;\n readonly sampled: boolean;\n readonly spanId: string;\n readonly startedAtMs: number;\n readonly startedAtUnixNano: string;\n readonly statusCode: \"OK\" | \"ERROR\";\n readonly statusMessage?: string;\n readonly traceId: string;\n}\n\n/** Maximum primitive attributes copied from one native Effect span or link. */\nconst MAX_EXPORTED_SPAN_ATTRIBUTES = 256;\n\ninterface EventLike {\n readonly event?: { readonly type?: unknown; readonly durability?: unknown };\n readonly type?: unknown;\n}\n\ninterface PositionedEventLike {\n readonly position?: { readonly seq?: unknown; readonly subSeq?: unknown };\n readonly event?: { readonly type?: unknown; readonly durability?: unknown };\n}\n\n/** Compact undefined tracing attributes before handing them to Effect spans. */\nexport const compactSpanAttributes = (\n attributes: EdaSpanAttributes,\n): Record<string, string | number | boolean> => {\n const compacted: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n compacted[key] = value;\n }\n }\n return compacted;\n};\n\nconst compactUnknownAttributes = (\n attributes: Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>,\n): Record<string, string | number | boolean> => {\n const compacted: Record<string, string | number | boolean> = {};\n try {\n if (attributes instanceof Map) {\n let count = 0;\n for (const [key, value] of attributes) {\n if (count >= MAX_EXPORTED_SPAN_ATTRIBUTES) {\n break;\n }\n count += 1;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n compacted[key] = value;\n }\n }\n return compacted;\n }\n\n const keys = Object.keys(attributes).slice(0, MAX_EXPORTED_SPAN_ATTRIBUTES);\n for (const key of keys) {\n let value: unknown;\n try {\n value = Reflect.get(attributes, key);\n } catch {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n compacted[key] = value;\n }\n }\n } catch {\n // Tracing diagnostics must not replace the operation whose span is ending.\n }\n return compacted;\n};\n\nexport const toEdaExternalSpan = (context: EDATraceContext): Tracer.ExternalSpan =>\n Tracer.externalSpan({\n traceId: context.traceId,\n spanId: context.spanId,\n sampled: context.sampled,\n });\n\nexport const edaTraceContextFromSpan = (span: Tracer.AnySpan): EDATraceContext =>\n makeEDATraceContext({\n traceId: span.traceId,\n spanId: span.spanId,\n sampled: span.sampled,\n tracestate: null,\n });\n\nexport const currentEDATraceContext: Effect.Effect<EDATraceContext, unknown> =\n Effect.currentSpan.pipe(Effect.map(edaTraceContextFromSpan));\n\nexport const currentOrRootEDAEventTrace: Effect.Effect<EDAEventTrace> = Effect.currentSpan.pipe(\n Effect.map((span) => makeEDAEventTrace(edaTraceContextFromSpan(span))),\n Effect.catch(() => Effect.sync(makeRootEDAEventTrace)),\n);\n\nexport const withEdaTraceMetadata =\n (metadata: EDATraceMetadata) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n effect.pipe(Effect.annotateSpans(metadata.attributes));\n\n/** Add EDA attributes to the currently active span. */\nexport const annotateEdaSpan = (attributes: EdaSpanAttributes): Effect.Effect<void> =>\n Effect.annotateCurrentSpan(compactSpanAttributes(attributes));\n\nconst nanosToMillis = (nanos: bigint): number => Number(nanos / 1_000_000n);\n\nconst outcomeFromExit = (exit: Exit.Exit<unknown, unknown>): EDAExportedSpan[\"outcome\"] => {\n if (Exit.isSuccess(exit)) {\n return \"ok\";\n }\n return Cause.hasInterruptsOnly(exit.cause) ? \"canceled\" : \"error\";\n};\n\nconst statusMessageFromExit = (exit: Exit.Exit<unknown, unknown>): string | undefined => {\n if (Exit.isSuccess(exit)) {\n return undefined;\n }\n const error = Cause.squash(exit.cause);\n return error instanceof Error ? error.message : String(error);\n};\n\nclass ExportingNativeSpan extends Tracer.NativeSpan {\n readonly #emit: (span: EDAExportedSpan) => void;\n\n constructor(\n options: ConstructorParameters<typeof Tracer.NativeSpan>[0],\n emit: (span: EDAExportedSpan) => void,\n ) {\n super(options);\n this.#emit = emit;\n }\n\n override end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {\n super.end(endTime, exit);\n // Keep the two startup summaries even within one clock tick: their checkpoint\n // and reuse counts explain why initialization was fast. Other zero-duration\n // spans add noise without describing execution.\n if (\n endTime <= this.startTime &&\n this.name !== \"agent.session.hydrate\" &&\n this.name !== \"agent.sinks.initialize\"\n ) {\n return;\n }\n const parent = Option.getOrUndefined(this.parent);\n this.#emit({\n attributes: compactUnknownAttributes(this.attributes),\n endedAtMs: nanosToMillis(endTime),\n endedAtUnixNano: endTime.toString(),\n kind: this.kind,\n links: this.links.map((link) => ({\n attributes: compactUnknownAttributes(link.attributes),\n traceId: link.span.traceId,\n spanId: link.span.spanId,\n sampled: link.span.sampled,\n })),\n name: this.name,\n outcome: outcomeFromExit(exit),\n ...(parent === undefined ? {} : { parentSpanId: parent.spanId }),\n sampled: this.sampled,\n spanId: this.spanId,\n startedAtMs: nanosToMillis(this.startTime),\n startedAtUnixNano: this.startTime.toString(),\n statusCode: Exit.isSuccess(exit) ? \"OK\" : \"ERROR\",\n ...(statusMessageFromExit(exit) === undefined\n ? {}\n : { statusMessage: statusMessageFromExit(exit) }),\n traceId: this.traceId,\n });\n }\n}\n\n/** Create an Effect tracer that exports only spans with observable duration. */\nexport const makeEdaExportingTracer = (emit: (span: EDAExportedSpan) => void): Tracer.Tracer =>\n Tracer.make({\n span: (options) => new ExportingNativeSpan(options, emit),\n });\n\n/** Summarize a durable/logical event collection for span attributes. */\nexport const eventBatchAttributes = (events: ReadonlyArray<EventLike>): EdaSpanAttributes => ({\n \"eda.event.count\": events.length,\n \"eda.event.types\": eventTypeSummary(events),\n});\n\n/** Summarize a committed positioned event collection for span attributes. */\nexport const committedBatchAttributes = (\n events: ReadonlyArray<PositionedEventLike>,\n): EdaSpanAttributes => {\n const seqs = events\n .map((entry) => entry.position?.seq)\n .filter((seq): seq is number => typeof seq === \"number\");\n return {\n ...eventBatchAttributes(events),\n \"eda.seq.min\": seqs.length === 0 ? undefined : Math.min(...seqs),\n \"eda.seq.max\": seqs.length === 0 ? undefined : Math.max(...seqs),\n };\n};\n\n/** Stable, low-cardinality usage attributes for model lifecycle spans. */\nexport const usageAttributes = (usage: UsagePayload | undefined): EdaSpanAttributes => ({\n \"eda.usage.input_tokens\": usage?.inputTokens,\n \"eda.usage.cached_input_tokens\": usage?.cachedInputTokens,\n \"eda.usage.output_tokens\": usage?.outputTokens,\n \"eda.usage.text_tokens\": usage?.textTokens,\n \"eda.usage.reasoning_tokens\": usage?.reasoningTokens,\n});\n\nconst eventTypeSummary = (events: ReadonlyArray<EventLike>): string | undefined => {\n if (events.length === 0) {\n return undefined;\n }\n const seen = new Set<string>();\n for (const event of events) {\n const type = event.event?.type ?? event.type;\n if (typeof type === \"string\") {\n seen.add(type);\n }\n }\n return seen.size === 0 ? undefined : Array.from(seen).join(\",\");\n};\n"],"mappings":";;;;;;;;AAwEA,MAAM,+BAA+B;;AAarC,MAAa,yBACX,eAC8C;CAC9C,MAAM,YAAuD,CAAC;CAC9D,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,GAClD,IAAI,UAAU,KAAA,GACZ,UAAU,OAAO;CAGrB,OAAO;AACT;AAEA,MAAM,4BACJ,eAC8C;CAC9C,MAAM,YAAuD,CAAC;CAC9D,IAAI;EACF,IAAI,sBAAsB,KAAK;GAC7B,IAAI,QAAQ;GACZ,KAAK,MAAM,CAAC,KAAK,UAAU,YAAY;IACrC,IAAI,SAAS,8BACX;IAEF,SAAS;IACT,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,WAC7E,UAAU,OAAO;GAErB;GACA,OAAO;EACT;EAEA,MAAM,OAAO,OAAO,KAAK,UAAU,EAAE,MAAM,GAAG,4BAA4B;EAC1E,KAAK,MAAM,OA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,WAAW,IAAI,KAAA,IAAY,KAAK,IAAI,GAAG,IAAI;CACjE;AACF;;AAGA,MAAa,mBAAmB,WAAwD;CACtF,0BAA0B,OAAO;CACjC,iCAAiC,OAAO;CACxC,2BAA2B,OAAO;CAClC,yBAAyB,OAAO;CAChC,8BAA8B,OAAO;AACvC;AAEA,MAAM,oBAAoB,WAAyD;CACjF,IAAI,OAAO,WAAW,GACpB;CAEF,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,OAAO,MAAM,OAAO,QAAQ,MAAM;EACxC,IAAI,OAAO,SAAS,UAClB,KAAK,IAAI,IAAI;CAEjB;CACA,OAAO,KAAK,SAAS,IAAI,KAAA,IAAY,MAAM,KAAK,IAAI,EAAE,KAAK,GAAG;AAChE"}
|
|
1
|
+
{"version":3,"file":"tracing.js","names":["#emit"],"sources":["../../src/services/tracing.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Tracer from \"effect/Tracer\";\n\nimport type { UsagePayload } from \"../types/events\";\nimport {\n EDATraceContext,\n type EDAEventTrace,\n type EDATraceAttributeValue,\n type EDATraceMetadata,\n makeEDAEventTrace,\n makeEDATraceContext,\n makeRootEDAEventTrace,\n} from \"../types/tracing\";\n\nexport {\n EDATraceContext,\n EDARunTrace,\n EDATraceLink,\n EDATraceMetadata,\n EDAEventTrace,\n makeEDAEventTrace,\n makeEDARunTrace,\n makeEDATraceContext,\n makeEDATraceMetadataFromParent,\n makeRootEDAEventTrace,\n makeRootEDATraceMetadata,\n} from \"../types/tracing\";\n\nexport { buildEDATraceparent, parseEDATraceparent } from \"../types/tracing\";\n\n/** Attribute value types accepted by Effect span annotations after compaction. */\nexport type EdaSpanAttributeValue = EDATraceAttributeValue | undefined;\n\n/** EDA span attribute map; undefined values are intentionally dropped before annotation. */\nexport type EdaSpanAttributes = Record<string, EdaSpanAttributeValue>;\n\nexport interface EDATracingOptions {\n readonly disableTracing?: boolean;\n readonly disableSpanPropagation?: boolean;\n readonly spanAttributes?: EdaSpanAttributes;\n readonly spanPrefix?: string;\n}\n\nexport interface EDAExportedSpanLink {\n readonly attributes: Record<string, string | number | boolean>;\n readonly sampled: boolean;\n readonly spanId: string;\n readonly traceId: string;\n}\n\nexport interface EDAExportedSpan {\n readonly attributes: Record<string, string | number | boolean>;\n readonly endedAtMs: number;\n readonly endedAtUnixNano: string;\n readonly kind: Tracer.SpanKind;\n readonly links: ReadonlyArray<EDAExportedSpanLink>;\n readonly name: string;\n readonly outcome: \"ok\" | \"error\" | \"timeout\" | \"canceled\";\n readonly parentSpanId?: string;\n readonly sampled: boolean;\n readonly spanId: string;\n readonly startedAtMs: number;\n readonly startedAtUnixNano: string;\n readonly statusCode: \"OK\" | \"ERROR\";\n readonly statusMessage?: string;\n readonly traceId: string;\n}\n\n/** Maximum primitive attributes copied from one native Effect span or link. */\nconst MAX_EXPORTED_SPAN_ATTRIBUTES = 256;\n\ninterface EventLike {\n readonly event?: { readonly type?: unknown; readonly durability?: unknown };\n readonly type?: unknown;\n}\n\ninterface PositionedEventLike {\n readonly position?: { readonly seq?: unknown; readonly subSeq?: unknown };\n readonly event?: { readonly type?: unknown; readonly durability?: unknown };\n}\n\n/** Compact undefined tracing attributes before handing them to Effect spans. */\nexport const compactSpanAttributes = (\n attributes: EdaSpanAttributes,\n): Record<string, string | number | boolean> => {\n const compacted: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n compacted[key] = value;\n }\n }\n return compacted;\n};\n\nconst compactUnknownAttributes = (\n attributes: Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>,\n): Record<string, string | number | boolean> => {\n const compacted: Record<string, string | number | boolean> = {};\n try {\n if (attributes instanceof Map) {\n let count = 0;\n for (const [key, value] of attributes) {\n if (count >= MAX_EXPORTED_SPAN_ATTRIBUTES) {\n break;\n }\n count += 1;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n compacted[key] = value;\n }\n }\n return compacted;\n }\n\n const keys = Object.keys(attributes).slice(0, MAX_EXPORTED_SPAN_ATTRIBUTES);\n for (const key of keys) {\n let value: unknown;\n try {\n value = Reflect.get(attributes, key);\n } catch {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n compacted[key] = value;\n }\n }\n } catch {\n // Tracing diagnostics must not replace the operation whose span is ending.\n }\n return compacted;\n};\n\nexport const toEdaExternalSpan = (context: EDATraceContext): Tracer.ExternalSpan =>\n Tracer.externalSpan({\n traceId: context.traceId,\n spanId: context.spanId,\n sampled: context.sampled,\n });\n\nexport const edaTraceContextFromSpan = (span: Tracer.AnySpan): EDATraceContext =>\n makeEDATraceContext({\n traceId: span.traceId,\n spanId: span.spanId,\n sampled: span.sampled,\n tracestate: null,\n });\n\nexport const currentEDATraceContext: Effect.Effect<EDATraceContext, unknown> =\n Effect.currentSpan.pipe(Effect.map(edaTraceContextFromSpan));\n\nexport const currentOrRootEDAEventTrace: Effect.Effect<EDAEventTrace> = Effect.currentSpan.pipe(\n Effect.map((span) => makeEDAEventTrace(edaTraceContextFromSpan(span))),\n Effect.catch(() => Effect.sync(makeRootEDAEventTrace)),\n);\n\nexport const withEdaTraceMetadata =\n (metadata: EDATraceMetadata) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n effect.pipe(Effect.annotateSpans(metadata.attributes));\n\n/** Add EDA attributes to the currently active span. */\nexport const annotateEdaSpan = (attributes: EdaSpanAttributes): Effect.Effect<void> =>\n Effect.annotateCurrentSpan(compactSpanAttributes(attributes));\n\nconst nanosToMillis = (nanos: bigint): number => Number(nanos / 1_000_000n);\n\nconst outcomeFromExit = (exit: Exit.Exit<unknown, unknown>): EDAExportedSpan[\"outcome\"] => {\n if (Exit.isSuccess(exit)) {\n return \"ok\";\n }\n return Cause.hasInterruptsOnly(exit.cause) ? \"canceled\" : \"error\";\n};\n\nconst statusMessageFromExit = (exit: Exit.Exit<unknown, unknown>): string | undefined => {\n if (Exit.isSuccess(exit)) {\n return undefined;\n }\n const error = Cause.squash(exit.cause);\n return error instanceof Error ? error.message : String(error);\n};\n\nclass ExportingNativeSpan extends Tracer.NativeSpan {\n readonly #emit: (span: EDAExportedSpan) => void;\n\n constructor(\n options: ConstructorParameters<typeof Tracer.NativeSpan>[0],\n emit: (span: EDAExportedSpan) => void,\n ) {\n super(options);\n this.#emit = emit;\n }\n\n override end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {\n super.end(endTime, exit);\n // Keep the two startup summaries even within one clock tick: their checkpoint\n // and reuse counts explain why initialization was fast. Other zero-duration\n // spans add noise without describing execution.\n if (\n endTime <= this.startTime &&\n this.name !== \"agent.session.hydrate\" &&\n this.name !== \"agent.sinks.initialize\"\n ) {\n return;\n }\n const parent = Option.getOrUndefined(this.parent);\n this.#emit({\n attributes: compactUnknownAttributes(this.attributes),\n endedAtMs: nanosToMillis(endTime),\n endedAtUnixNano: endTime.toString(),\n kind: this.kind,\n links: this.links.map((link) => ({\n attributes: compactUnknownAttributes(link.attributes),\n traceId: link.span.traceId,\n spanId: link.span.spanId,\n sampled: link.span.sampled,\n })),\n name: this.name,\n outcome: outcomeFromExit(exit),\n ...(parent === undefined ? {} : { parentSpanId: parent.spanId }),\n sampled: this.sampled,\n spanId: this.spanId,\n startedAtMs: nanosToMillis(this.startTime),\n startedAtUnixNano: this.startTime.toString(),\n statusCode: Exit.isSuccess(exit) ? \"OK\" : \"ERROR\",\n ...(statusMessageFromExit(exit) === undefined\n ? {}\n : { statusMessage: statusMessageFromExit(exit) }),\n traceId: this.traceId,\n });\n }\n}\n\n/** Create an Effect tracer that exports only spans with observable duration. */\nexport const makeEdaExportingTracer = (emit: (span: EDAExportedSpan) => void): Tracer.Tracer =>\n Tracer.make({\n span: (options) => new ExportingNativeSpan(options, emit),\n });\n\n/** Summarize a durable/logical event collection for span attributes. */\nexport const eventBatchAttributes = (events: ReadonlyArray<EventLike>): EdaSpanAttributes => ({\n \"eda.event.count\": events.length,\n \"eda.event.types\": eventTypeSummary(events),\n});\n\n/** Summarize a committed positioned event collection for span attributes. */\nexport const committedBatchAttributes = (\n events: ReadonlyArray<PositionedEventLike>,\n): EdaSpanAttributes => {\n const seqs = events\n .map((entry) => entry.position?.seq)\n .filter((seq): seq is number => typeof seq === \"number\");\n return {\n ...eventBatchAttributes(events),\n \"eda.seq.min\": seqs.length === 0 ? undefined : Math.min(...seqs),\n \"eda.seq.max\": seqs.length === 0 ? undefined : Math.max(...seqs),\n };\n};\n\n/** Stable, low-cardinality usage attributes for model lifecycle spans. */\nexport const usageAttributes = (usage: UsagePayload | undefined): EdaSpanAttributes => ({\n \"eda.usage.input_tokens\": usage?.inputTokens,\n \"eda.usage.cached_input_tokens\": usage?.cachedInputTokens,\n \"eda.usage.output_tokens\": usage?.outputTokens,\n \"eda.usage.text_tokens\": usage?.textTokens,\n \"eda.usage.reasoning_tokens\": usage?.reasoningTokens,\n});\n\nconst eventTypeSummary = (events: ReadonlyArray<EventLike>): string | undefined => {\n if (events.length === 0) {\n return undefined;\n }\n const seen = new Set<string>();\n for (const event of events) {\n const type = event.event?.type ?? event.type;\n if (typeof type === \"string\") {\n seen.add(type);\n }\n }\n return seen.size === 0 ? undefined : Array.from(seen).join(\",\");\n};\n"],"mappings":";;;;;;;;AAwEA,MAAM,+BAA+B;;AAarC,MAAa,yBACX,eAC8C;CAC9C,MAAM,YAAuD,CAAC;CAC9D,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,GAClD,IAAI,UAAU,KAAA,GACZ,UAAU,OAAO;CAGrB,OAAO;AACT;AAEA,MAAM,4BACJ,eAC8C;CAC9C,MAAM,YAAuD,CAAC;CAC9D,IAAI;EACF,IAAI,sBAAsB,KAAK;GAC7B,IAAI,QAAQ;GACZ,KAAK,MAAM,CAAC,KAAK,UAAU,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Aa,4BACX,WACsB;CACtB,MAAM,OAAO,OACV,KAAK,UAAU,MAAM,UAAU,GAAG,CAAC,CACnC,QAAQ,QAAuB,OAAO,QAAQ,QAAQ;CACzD,OAAO;EACL,GAAG,qBAAqB,MAAM;EAC9B,eAAe,KAAK,WAAW,IAAI,KAAA,IAAY,KAAK,IAAI,GAAG,IAAI;EAC/D,eAAe,KAAK,WAAW,IAAI,KAAA,IAAY,KAAK,IAAI,GAAG,IAAI;CACjE;AACF;;AAGA,MAAa,mBAAmB,WAAwD;CACtF,0BAA0B,OAAO;CACjC,iCAAiC,OAAO;CACxC,2BAA2B,OAAO;CAClC,yBAAyB,OAAO;CAChC,8BAA8B,OAAO;AACvC;AAEA,MAAM,oBAAoB,WAAyD;CACjF,IAAI,OAAO,WAAW,GACpB;CAEF,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,OAAO,MAAM,OAAO,QAAQ,MAAM;EACxC,IAAI,OAAO,SAAS,UAClB,KAAK,IAAI,IAAI;CAEjB;CACA,OAAO,KAAK,SAAS,IAAI,KAAA,IAAY,MAAM,KAAK,IAAI,CAAC,CAAC,KAAK,GAAG;AAChE"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { f as PositionedEvent } from "./envelope-
|
|
1
|
+
import { f as PositionedEvent } from "./envelope-Che6KatU.js";
|
|
2
|
+
import "./events-sxIzJY26.js";
|
|
2
3
|
import * as Context from "effect/Context";
|
|
3
4
|
import * as Effect from "effect/Effect";
|
|
4
5
|
import * as Layer from "effect/Layer";
|
|
5
|
-
|
|
6
6
|
//#region src/services/session-event-observer.d.ts
|
|
7
7
|
/**
|
|
8
8
|
* Outbound integration point notified synchronously after EDA publishes an event.
|
|
@@ -21,4 +21,4 @@ declare class SessionEventObserver extends SessionEventObserver_base {
|
|
|
21
21
|
}
|
|
22
22
|
//#endregion
|
|
23
23
|
export { SessionEventObserverShape as n, SessionEventObserver as t };
|
|
24
|
-
//# sourceMappingURL=session-event-observer-
|
|
24
|
+
//# sourceMappingURL=session-event-observer-BDwja1jX.d.ts.map
|