effect-durable-agent 0.1.0-alpha.3 → 0.1.0-alpha.5
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/README.md +43 -41
- package/dist/{command-queues-CQ9cwRP7.d.ts → command-queues-Dwdf41mq.d.ts} +7 -6
- package/dist/{compaction-1LSZR944.d.ts → compaction-DpHOf-g7.d.ts} +8 -6
- package/dist/context-projection-B4DWOZgi.d.ts +140 -0
- package/dist/{core-Hv3cFydL.d.ts → core-CYT6DBaS.d.ts} +2 -2
- package/dist/domain/command-queues.d.ts +1 -1
- package/dist/domain/context-projection.d.ts +2 -0
- package/dist/domain/context-projection.js +32 -0
- package/dist/domain/context-projection.js.map +1 -0
- package/dist/domain/message-transcript.d.ts +1 -1
- package/dist/domain/reduced-state-schema.d.ts +2 -0
- package/dist/domain/reduced-state-schema.js +2 -1
- package/dist/domain/reduced-state-schema.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +1 -1
- package/dist/domain/reduced-state.js +1 -1
- package/dist/{durable-DlScwmCy.d.ts → durable-B7M6TD_0.d.ts} +341 -2
- package/dist/{durable-C3Rz7kg3.js → durable-DsV9PxZC.js} +13 -2
- package/dist/durable-DsV9PxZC.js.map +1 -0
- package/dist/{keep-alive-DYDsH6qN.d.ts → event-factory-CLJcyymV.d.ts} +5 -29
- package/dist/{keep-alive-p8dIcSVy.js → event-factory-tcpLgdMN.js} +3 -10
- package/dist/event-factory-tcpLgdMN.js.map +1 -0
- package/dist/host/websocket-protocol.d.ts +252 -0
- package/dist/host/websocket-protocol.js +111 -0
- package/dist/host/websocket-protocol.js.map +1 -0
- package/dist/host/websocket-wire.d.ts +2 -2
- package/dist/host/websocket-wire.js +21 -4
- package/dist/host/websocket-wire.js.map +1 -1
- package/dist/{id-generator-C2Q15uZM.d.ts → id-generator-Ckl8_XWW.d.ts} +2 -2
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/keep-alive-Chl5SJxy.d.ts +29 -0
- package/dist/{message-transcript-BCHdHAe2.d.ts → message-transcript-CFn_D3MH.d.ts} +3 -3
- package/dist/{prompt-projector-DimXJPOJ.d.ts → prompt-projector-C2meuNrV.d.ts} +5 -5
- package/dist/{reduced-state-C4nVVzz9.js → reduced-state-TMi7ISla.js} +20 -4
- package/dist/reduced-state-TMi7ISla.js.map +1 -0
- package/dist/{reducer-registry-C0svUa63.d.ts → reducer-registry-K9FqZq5-.d.ts} +2 -2
- package/dist/{runtime-DcdPOEuE.d.ts → runtime-5NEJngu3.d.ts} +12 -6
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/compaction.js +4 -3
- package/dist/services/compaction.js.map +1 -1
- package/dist/services/id-generator.d.ts +1 -1
- package/dist/services/keep-alive.d.ts +2 -0
- package/dist/services/keep-alive.js +13 -0
- package/dist/services/keep-alive.js.map +1 -0
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/reducer-registry.d.ts +1 -1
- package/dist/services/runtime-layer.d.ts +58 -0
- package/dist/services/runtime-layer.js +42 -0
- package/dist/services/runtime-layer.js.map +1 -0
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +9 -4
- package/dist/services/runtime.js.map +1 -1
- package/dist/services/session-query.d.ts +2 -2
- package/dist/services/session-query.js +93 -1
- package/dist/services/session-query.js.map +1 -0
- package/dist/services/session-state.d.ts +2 -0
- package/dist/services/session-state.js +2 -0
- package/dist/services/session-store.d.ts +2 -2
- package/dist/services/session-store.js +181 -2
- package/dist/services/session-store.js.map +1 -0
- package/dist/services/sink-checkpoint-store.d.ts +2 -0
- package/dist/services/sink-checkpoint-store.js +49 -0
- package/dist/services/sink-checkpoint-store.js.map +1 -0
- package/dist/services/sink-registry.d.ts +1 -1
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/span-names.d.ts +1 -1
- package/dist/services/span-names.js +1 -0
- package/dist/services/span-names.js.map +1 -1
- package/dist/services/tool-registry.d.ts +1 -1
- package/dist/services/websocket-delivery.d.ts +90 -0
- package/dist/services/websocket-delivery.js +221 -0
- package/dist/services/websocket-delivery.js.map +1 -0
- package/dist/session-query-5oyZRaQL.d.ts +45 -0
- package/dist/{session-query-hxfujxUH.d.ts → session-state-CI1xeT6f.d.ts} +134 -42
- package/dist/{session-query-Cbf-e0rG.js → session-state-D7dqko7r.js} +19 -78
- package/dist/session-state-D7dqko7r.js.map +1 -0
- package/dist/{session-store-D2Ore1QC.d.ts → session-store-BLg6UvZa.d.ts} +5 -94
- package/dist/sink-checkpoint-store-B9WNvDtY.d.ts +40 -0
- package/dist/{sink-registry-CFC6xjsN.js → sink-registry-BbmoI9uv.js} +25 -70
- package/dist/sink-registry-BbmoI9uv.js.map +1 -0
- package/dist/{sink-registry-BziFpxoE.d.ts → sink-registry-CO3YPS1p.d.ts} +31 -48
- package/dist/testkit/layers.d.ts +14 -11
- package/dist/testkit/layers.js +9 -6
- package/dist/testkit/layers.js.map +1 -1
- package/dist/{tool-registry-CcnkAAQK.d.ts → tool-registry-B8H1P6Pu.d.ts} +3 -3
- package/dist/types/core.d.ts +1 -1
- package/dist/types/core.js +1 -1
- package/dist/types/core.js.map +1 -1
- package/dist/types/events/durable.d.ts +2 -2
- package/dist/types/events/durable.js +2 -2
- package/dist/types/events.d.ts +2 -2
- package/dist/types/events.js +2 -2
- package/dist/{websocket-wire-D3tLrhe2.d.ts → websocket-wire-DPxwY4G5.d.ts} +112 -11
- package/package.json +48 -40
- package/testing/offline-trace/README.md +2 -1
- package/CHANGELOG.md +0 -25
- package/CONTRIBUTING.md +0 -26
- package/SECURITY.md +0 -7
- package/dist/durable-C3Rz7kg3.js.map +0 -1
- package/dist/durable-object-runtime-CiMKxGs6.d.ts +0 -257
- package/dist/durable-object-runtime-wKiqaAt2.js +0 -1494
- package/dist/durable-object-runtime-wKiqaAt2.js.map +0 -1
- package/dist/durable-object-storage-Czy7IPrh.d.ts +0 -41
- package/dist/host/durable-object-runtime.d.ts +0 -2
- package/dist/host/durable-object-runtime.js +0 -2
- package/dist/host/durable-object-storage.d.ts +0 -2
- package/dist/host/durable-object-storage.js +0 -0
- package/dist/host/durable-object.d.ts +0 -83
- package/dist/host/durable-object.js +0 -191
- package/dist/host/durable-object.js.map +0 -1
- package/dist/keep-alive-p8dIcSVy.js.map +0 -1
- package/dist/reduced-state-C4nVVzz9.js.map +0 -1
- package/dist/session-query-Cbf-e0rG.js.map +0 -1
- package/dist/session-store-pYxQW9qh.js +0 -214
- package/dist/session-store-pYxQW9qh.js.map +0 -1
- package/dist/sink-registry-CFC6xjsN.js.map +0 -1
- package/docs/assets/architecture.svg +0 -216
- package/docs/assets/event-sequence.svg +0 -133
- package/docs/assets/gcp-trace.png +0 -0
- package/docs/assets/hero.svg +0 -33
- package/docs/message-steering.md +0 -831
- package/docs/releasing.md +0 -96
- package/docs/spec.md +0 -777
- package/docs/subagents.md +0 -725
- package/docs/testing.md +0 -64
- package/docs/ui-projection.md +0 -742
- package/docs/websocket-protocol.md +0 -639
- package/examples/001-no-tools/README.md +0 -65
- package/examples/001-no-tools/worker.ts +0 -79
- package/examples/002-slack-bridge/README.md +0 -134
- package/examples/002-slack-bridge/events.ts +0 -115
- package/examples/002-slack-bridge/reducer.ts +0 -216
- package/examples/002-slack-bridge/scenario.test.ts +0 -223
- package/examples/002-slack-bridge/sinks.ts +0 -109
- package/examples/002-slack-bridge/worker.ts +0 -140
- package/examples/003-sandbox-lifecycle/README.md +0 -78
- package/examples/003-sandbox-lifecycle/events.ts +0 -203
- package/examples/003-sandbox-lifecycle/reducer.ts +0 -305
- package/examples/003-sandbox-lifecycle/scenario.test.ts +0 -202
- package/examples/_shared/event-id.ts +0 -12
- package/examples/_shared/http.ts +0 -27
- package/examples/_shared/openai.ts +0 -33
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { SequenceNumber } from "../types/core.js";
|
|
2
|
+
import { EDAWebSocketErrorFrame, EDAWebSocketEventsFrame, EDAWebSocketHelloFrame, EDAWebSocketLaggedFrame, EDA_WEB_SOCKET_PROTOCOL_VERSION, EDA_WS_CLOSE_LAGGED, EDA_WS_CLOSE_PROTOCOL_ERROR, FrameId, laggedCloseReason } from "../host/websocket-protocol.js";
|
|
3
|
+
import * as Schema from "effect/Schema";
|
|
4
|
+
//#region src/services/websocket-delivery.ts
|
|
5
|
+
/** Slow subscriber reasons that intentionally close only the lagging socket. */
|
|
6
|
+
const SubscriberLagReason = Schema.Literals(["buffer-overflow", "ack-timeout"]);
|
|
7
|
+
/** Build the delivery state for a new connection or a post-eviction restore. */
|
|
8
|
+
const makeWebSocketDeliveryState = (input) => ({
|
|
9
|
+
subscriberId: input.subscriberId,
|
|
10
|
+
policy: input.policy,
|
|
11
|
+
coldRestored: input.coldRestored ?? false,
|
|
12
|
+
lastAckedSeq: input.resumeSeq,
|
|
13
|
+
lastAckedFrameId: 0,
|
|
14
|
+
lastSentFrameId: 0,
|
|
15
|
+
nextFrameId: 1,
|
|
16
|
+
sentDurableThroughSeq: input.resumeSeq,
|
|
17
|
+
inFlight: [],
|
|
18
|
+
pendingEphemeral: []
|
|
19
|
+
});
|
|
20
|
+
/** First frame for a freshly accepted connection. Cold restores never re-send hello. */
|
|
21
|
+
const deliveryHelloFrame = (state) => EDAWebSocketHelloFrame.make({
|
|
22
|
+
_tag: "hello",
|
|
23
|
+
protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,
|
|
24
|
+
subscriberId: state.subscriberId,
|
|
25
|
+
resumeSeq: state.lastAckedSeq,
|
|
26
|
+
flowControl: state.policy
|
|
27
|
+
});
|
|
28
|
+
/**
|
|
29
|
+
* Deliver committed durable events read from the store.
|
|
30
|
+
*
|
|
31
|
+
* The store is the only buffer for durable events: frames are emitted while
|
|
32
|
+
* the ACK window has room and the remainder is requested again via
|
|
33
|
+
* `wantsCatchUpAfterSeq` once ACKs reopen the window.
|
|
34
|
+
*/
|
|
35
|
+
const onDurableEvents = (state, events, head, nowMs) => {
|
|
36
|
+
const stale = staleAckResult(state, nowMs);
|
|
37
|
+
if (stale !== void 0) return stale;
|
|
38
|
+
let next = state;
|
|
39
|
+
const frames = [];
|
|
40
|
+
let batch = [];
|
|
41
|
+
const flushBatch = () => {
|
|
42
|
+
if (batch.length === 0) return;
|
|
43
|
+
const sent = sendEventsFrame(next, batch, nowMs);
|
|
44
|
+
if (sent.close !== void 0) return {
|
|
45
|
+
...sent,
|
|
46
|
+
frames: [...frames, ...sent.frames]
|
|
47
|
+
};
|
|
48
|
+
next = sent.state;
|
|
49
|
+
frames.push(...sent.frames);
|
|
50
|
+
batch = [];
|
|
51
|
+
};
|
|
52
|
+
for (const event of events) {
|
|
53
|
+
if (event.event.durability === "durable" && event.position.seq <= next.sentDurableThroughSeq) continue;
|
|
54
|
+
if (batch.length === 0 && windowCapacity(next) <= 0) break;
|
|
55
|
+
batch.push(event);
|
|
56
|
+
if (batch.length >= next.policy.maxFrameEvents) {
|
|
57
|
+
const closed = flushBatch();
|
|
58
|
+
if (closed !== void 0) return closed;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const closed = flushBatch();
|
|
62
|
+
if (closed !== void 0) return closed;
|
|
63
|
+
return {
|
|
64
|
+
state: next,
|
|
65
|
+
frames,
|
|
66
|
+
...windowCapacity(next) > 0 && next.sentDurableThroughSeq < head ? { wantsCatchUpAfterSeq: next.sentDurableThroughSeq } : {}
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Deliver one live ephemeral event.
|
|
71
|
+
*
|
|
72
|
+
* Ephemeral events have no durable backing, so a bounded in-memory buffer
|
|
73
|
+
* holds them while the ACK window is full; overflow lag-closes only this
|
|
74
|
+
* subscriber, mirroring the previous streaming behavior.
|
|
75
|
+
*/
|
|
76
|
+
const onEphemeralEvent = (state, event, nowMs) => {
|
|
77
|
+
const stale = staleAckResult(state, nowMs);
|
|
78
|
+
if (stale !== void 0) return stale;
|
|
79
|
+
if (windowCapacity(state) > 0 && state.pendingEphemeral.length === 0) return sendEventsFrame(state, [event], nowMs);
|
|
80
|
+
const pendingEphemeral = [...state.pendingEphemeral, event];
|
|
81
|
+
if (pendingEphemeral.length > state.policy.subscriberBufferCapacityEvents) return laggedResult(state, "buffer-overflow");
|
|
82
|
+
return {
|
|
83
|
+
state: {
|
|
84
|
+
...state,
|
|
85
|
+
pendingEphemeral
|
|
86
|
+
},
|
|
87
|
+
frames: []
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
/** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */
|
|
91
|
+
const onClientAck = (state, ack, nowMs) => {
|
|
92
|
+
const validated = state.coldRestored ? applyColdAck(state, ack) : applyWarmAck(state, ack);
|
|
93
|
+
if (validated._tag === "close") return validated.result;
|
|
94
|
+
if (validated._tag === "ignore") return {
|
|
95
|
+
state,
|
|
96
|
+
frames: []
|
|
97
|
+
};
|
|
98
|
+
let next = validated.state;
|
|
99
|
+
const frames = [];
|
|
100
|
+
while (next.pendingEphemeral.length > 0 && windowCapacity(next) > 0) {
|
|
101
|
+
const [head, ...rest] = next.pendingEphemeral;
|
|
102
|
+
const sent = sendEventsFrame({
|
|
103
|
+
...next,
|
|
104
|
+
pendingEphemeral: rest
|
|
105
|
+
}, [head], nowMs);
|
|
106
|
+
if (sent.close !== void 0) return {
|
|
107
|
+
...sent,
|
|
108
|
+
frames: [...frames, ...sent.frames],
|
|
109
|
+
persistSeq: validated.persistSeq
|
|
110
|
+
};
|
|
111
|
+
next = sent.state;
|
|
112
|
+
frames.push(...sent.frames);
|
|
113
|
+
}
|
|
114
|
+
const stale = staleAckResult(next, nowMs);
|
|
115
|
+
if (stale !== void 0) return {
|
|
116
|
+
...stale,
|
|
117
|
+
frames: [...frames, ...stale.frames],
|
|
118
|
+
persistSeq: validated.persistSeq
|
|
119
|
+
};
|
|
120
|
+
return {
|
|
121
|
+
state: next,
|
|
122
|
+
frames,
|
|
123
|
+
persistSeq: validated.persistSeq,
|
|
124
|
+
...windowCapacity(next) > 0 && next.pendingEphemeral.length === 0 ? { wantsCatchUpAfterSeq: next.sentDurableThroughSeq } : {}
|
|
125
|
+
};
|
|
126
|
+
};
|
|
127
|
+
const applyWarmAck = (state, ack) => {
|
|
128
|
+
if (ack.frameId <= state.lastAckedFrameId) return ack.durableThroughSeq > state.lastAckedSeq ? protocolClose(state, "Duplicate ACK attempted to advance durable seq") : { _tag: "ignore" };
|
|
129
|
+
if (ack.frameId > state.lastSentFrameId) return protocolClose(state, "ACK referenced an unsent frame");
|
|
130
|
+
if (ack.durableThroughSeq < state.lastAckedSeq) return protocolClose(state, "ACK durable seq moved backwards");
|
|
131
|
+
const acknowledged = state.inFlight.filter((frame) => frame.frameId <= ack.frameId);
|
|
132
|
+
if (acknowledged.length === 0) return protocolClose(state, "ACK referenced no in-flight frames");
|
|
133
|
+
const allowedDurableSeq = SequenceNumber.make(acknowledged.reduce((max, frame) => Math.max(max, frame.durableThroughSeq), state.lastAckedSeq));
|
|
134
|
+
if (ack.durableThroughSeq > allowedDurableSeq) return protocolClose(state, "ACK durable seq exceeded sent frame boundary");
|
|
135
|
+
return {
|
|
136
|
+
_tag: "apply",
|
|
137
|
+
persistSeq: ack.durableThroughSeq,
|
|
138
|
+
state: {
|
|
139
|
+
...state,
|
|
140
|
+
inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),
|
|
141
|
+
lastAckedFrameId: ack.frameId,
|
|
142
|
+
lastAckedSeq: ack.durableThroughSeq
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
};
|
|
146
|
+
const applyColdAck = (state, ack) => {
|
|
147
|
+
if (ack.durableThroughSeq < state.lastAckedSeq) return { _tag: "ignore" };
|
|
148
|
+
const lastAckedSeq = SequenceNumber.make(Math.max(state.lastAckedSeq, ack.durableThroughSeq));
|
|
149
|
+
return {
|
|
150
|
+
_tag: "apply",
|
|
151
|
+
persistSeq: lastAckedSeq,
|
|
152
|
+
state: {
|
|
153
|
+
...state,
|
|
154
|
+
inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),
|
|
155
|
+
lastAckedFrameId: Math.max(state.lastAckedFrameId, ack.frameId),
|
|
156
|
+
lastAckedSeq,
|
|
157
|
+
sentDurableThroughSeq: SequenceNumber.make(Math.max(state.sentDurableThroughSeq, lastAckedSeq))
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
const windowCapacity = (state) => state.policy.maxInFlightFrames - state.inFlight.length;
|
|
162
|
+
const sendEventsFrame = (state, events, nowMs) => {
|
|
163
|
+
const frameId = FrameId.make(state.nextFrameId);
|
|
164
|
+
const durableThroughSeq = SequenceNumber.make(events.reduce((max, event) => event.event.durability === "durable" ? Math.max(max, event.position.seq) : max, state.sentDurableThroughSeq));
|
|
165
|
+
const frame = EDAWebSocketEventsFrame.make({
|
|
166
|
+
_tag: "events",
|
|
167
|
+
frameId,
|
|
168
|
+
events,
|
|
169
|
+
durableThroughSeq
|
|
170
|
+
});
|
|
171
|
+
const encodedBytes = new TextEncoder().encode(JSON.stringify(frame)).byteLength;
|
|
172
|
+
if (encodedBytes > state.policy.maxFrameBytes) return protocolClose(state, `Encoded WebSocket frame exceeded maxFrameBytes (${encodedBytes} > ${state.policy.maxFrameBytes})`).result;
|
|
173
|
+
return {
|
|
174
|
+
state: {
|
|
175
|
+
...state,
|
|
176
|
+
inFlight: [...state.inFlight, {
|
|
177
|
+
frameId,
|
|
178
|
+
durableThroughSeq,
|
|
179
|
+
sentAtMs: nowMs
|
|
180
|
+
}],
|
|
181
|
+
lastSentFrameId: frameId,
|
|
182
|
+
nextFrameId: frameId + 1,
|
|
183
|
+
sentDurableThroughSeq: durableThroughSeq
|
|
184
|
+
},
|
|
185
|
+
frames: [frame]
|
|
186
|
+
};
|
|
187
|
+
};
|
|
188
|
+
/** Lazily enforce the ACK deadline: no resident timer, checked on each transition. */
|
|
189
|
+
const staleAckResult = (state, nowMs) => {
|
|
190
|
+
return state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs) ? laggedResult(state, "ack-timeout") : void 0;
|
|
191
|
+
};
|
|
192
|
+
const laggedResult = (state, reason) => ({
|
|
193
|
+
state,
|
|
194
|
+
frames: [EDAWebSocketLaggedFrame.make({
|
|
195
|
+
_tag: "lagged",
|
|
196
|
+
resumeSeq: state.lastAckedSeq,
|
|
197
|
+
reason
|
|
198
|
+
})],
|
|
199
|
+
close: {
|
|
200
|
+
code: EDA_WS_CLOSE_LAGGED,
|
|
201
|
+
reason: laggedCloseReason(state.lastAckedSeq)
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
const protocolClose = (state, message) => ({
|
|
205
|
+
_tag: "close",
|
|
206
|
+
result: {
|
|
207
|
+
state,
|
|
208
|
+
frames: [EDAWebSocketErrorFrame.make({
|
|
209
|
+
_tag: "error",
|
|
210
|
+
message: message.slice(0, 120)
|
|
211
|
+
})],
|
|
212
|
+
close: {
|
|
213
|
+
code: EDA_WS_CLOSE_PROTOCOL_ERROR,
|
|
214
|
+
reason: "protocol"
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
//#endregion
|
|
219
|
+
export { SubscriberLagReason, deliveryHelloFrame, makeWebSocketDeliveryState, onClientAck, onDurableEvents, onEphemeralEvent };
|
|
220
|
+
|
|
221
|
+
//# sourceMappingURL=websocket-delivery.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"websocket-delivery.js","names":[],"sources":["../../src/services/websocket-delivery.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\nimport {\n EDA_WEB_SOCKET_PROTOCOL_VERSION,\n EDA_WS_CLOSE_LAGGED,\n EDA_WS_CLOSE_PROTOCOL_ERROR,\n EDAWebSocketEventsFrame,\n EDAWebSocketErrorFrame,\n EDAWebSocketHelloFrame,\n EDAWebSocketLaggedFrame,\n FrameId,\n SubscriberId,\n laggedCloseReason,\n type EDAWebSocketAckFrame,\n type EDAWebSocketFlowControl,\n type EDAWebSocketServerFrame,\n} from \"../host/websocket-protocol\";\n\n/** Slow subscriber reasons that intentionally close only the lagging socket. */\nexport const SubscriberLagReason = Schema.Literals([\"buffer-overflow\", \"ack-timeout\"]);\nexport type SubscriberLagReason = typeof SubscriberLagReason.Type;\n\n/** One sent-but-unacknowledged events frame. */\nexport interface InFlightFrame {\n readonly frameId: FrameId;\n readonly durableThroughSeq: SequenceNumber;\n readonly sentAtMs: number;\n}\n\n/**\n * In-memory delivery state for one accepted event WebSocket.\n *\n * This state is deliberately disposable: hibernation-capable hosts persist\n * only the acknowledged durable cursor in the socket attachment and rebuild\n * a cold state after isolate eviction. Nothing here owns a fiber, a timer,\n * or a stream; all progress is driven by explicit host calls.\n */\nexport interface EDAWebSocketDeliveryState {\n readonly subscriberId: SubscriberId;\n readonly policy: EDAWebSocketFlowControl;\n /**\n * True when this state was rebuilt from a persisted attachment after the\n * in-memory frame bookkeeping was lost. Frame-id validation is relaxed for\n * the remainder of the connection because pre-eviction frame ids are\n * unknowable; durable cursors stay strictly monotonic either way.\n */\n readonly coldRestored: boolean;\n readonly lastAckedSeq: SequenceNumber;\n readonly lastAckedFrameId: number;\n readonly lastSentFrameId: number;\n readonly nextFrameId: number;\n readonly sentDurableThroughSeq: SequenceNumber;\n readonly inFlight: ReadonlyArray<InFlightFrame>;\n readonly pendingEphemeral: ReadonlyArray<PositionedEvent>;\n}\n\n/** Close instruction for the host WebSocket boundary. */\nexport interface DeliveryClose {\n readonly code: number;\n readonly reason: string;\n}\n\n/** Result of one pure delivery transition. */\nexport interface EDAWebSocketDeliveryResult {\n readonly state: EDAWebSocketDeliveryState;\n /** Frames to send in order, including any final lagged/error frame before `close`. */\n readonly frames: ReadonlyArray<EDAWebSocketServerFrame>;\n /** When set, persist this acknowledged durable cursor to the socket attachment. */\n readonly persistSeq?: SequenceNumber;\n /** When set, send `frames` then close the socket and drop its state. */\n readonly close?: DeliveryClose;\n /** When set, the host should read a durable slice after this seq and call `onDurableEvents`. */\n readonly wantsCatchUpAfterSeq?: SequenceNumber;\n}\n\n/** Inputs for one fresh or cold-restored delivery state. */\nexport interface MakeDeliveryStateInput {\n readonly subscriberId: SubscriberId;\n readonly resumeSeq: SequenceNumber;\n readonly policy: EDAWebSocketFlowControl;\n readonly coldRestored?: boolean;\n}\n\n/** Build the delivery state for a new connection or a post-eviction restore. */\nexport const makeWebSocketDeliveryState = (\n input: MakeDeliveryStateInput,\n): EDAWebSocketDeliveryState => ({\n subscriberId: input.subscriberId,\n policy: input.policy,\n coldRestored: input.coldRestored ?? false,\n lastAckedSeq: input.resumeSeq,\n lastAckedFrameId: 0,\n lastSentFrameId: 0,\n nextFrameId: 1,\n sentDurableThroughSeq: input.resumeSeq,\n inFlight: [],\n pendingEphemeral: [],\n});\n\n/** First frame for a freshly accepted connection. Cold restores never re-send hello. */\nexport const deliveryHelloFrame = (state: EDAWebSocketDeliveryState): EDAWebSocketHelloFrame =>\n EDAWebSocketHelloFrame.make({\n _tag: \"hello\",\n protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,\n subscriberId: state.subscriberId,\n resumeSeq: state.lastAckedSeq,\n flowControl: state.policy,\n });\n\n/**\n * Deliver committed durable events read from the store.\n *\n * The store is the only buffer for durable events: frames are emitted while\n * the ACK window has room and the remainder is requested again via\n * `wantsCatchUpAfterSeq` once ACKs reopen the window.\n */\nexport const onDurableEvents = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n head: SequenceNumber,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) {\n return stale;\n }\n\n let next = state;\n const frames: EDAWebSocketServerFrame[] = [];\n let batch: PositionedEvent[] = [];\n\n const flushBatch = (): EDAWebSocketDeliveryResult | undefined => {\n if (batch.length === 0) {\n return undefined;\n }\n const sent = sendEventsFrame(next, batch, nowMs);\n if (sent.close !== undefined) {\n return { ...sent, frames: [...frames, ...sent.frames] };\n }\n next = sent.state;\n frames.push(...sent.frames);\n batch = [];\n return undefined;\n };\n\n for (const event of events) {\n if (event.event.durability === \"durable\" && event.position.seq <= next.sentDurableThroughSeq) {\n continue;\n }\n if (batch.length === 0 && windowCapacity(next) <= 0) {\n break;\n }\n batch.push(event);\n if (batch.length >= next.policy.maxFrameEvents) {\n const closed = flushBatch();\n if (closed !== undefined) {\n return closed;\n }\n }\n }\n const closed = flushBatch();\n if (closed !== undefined) {\n return closed;\n }\n\n return {\n state: next,\n frames,\n ...(windowCapacity(next) > 0 && next.sentDurableThroughSeq < head\n ? { wantsCatchUpAfterSeq: next.sentDurableThroughSeq }\n : {}),\n };\n};\n\n/**\n * Deliver one live ephemeral event.\n *\n * Ephemeral events have no durable backing, so a bounded in-memory buffer\n * holds them while the ACK window is full; overflow lag-closes only this\n * subscriber, mirroring the previous streaming behavior.\n */\nexport const onEphemeralEvent = (\n state: EDAWebSocketDeliveryState,\n event: PositionedEvent,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) {\n return stale;\n }\n\n if (windowCapacity(state) > 0 && state.pendingEphemeral.length === 0) {\n return sendEventsFrame(state, [event], nowMs);\n }\n\n const pendingEphemeral = [...state.pendingEphemeral, event];\n if (pendingEphemeral.length > state.policy.subscriberBufferCapacityEvents) {\n return laggedResult(state, \"buffer-overflow\");\n }\n return { state: { ...state, pendingEphemeral }, frames: [] };\n};\n\n/** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */\nexport const onClientAck = (\n state: EDAWebSocketDeliveryState,\n ack: EDAWebSocketAckFrame,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const validated = state.coldRestored ? applyColdAck(state, ack) : applyWarmAck(state, ack);\n if (validated._tag === \"close\") {\n return validated.result;\n }\n if (validated._tag === \"ignore\") {\n return { state, frames: [] };\n }\n\n let next = validated.state;\n const frames: EDAWebSocketServerFrame[] = [];\n while (next.pendingEphemeral.length > 0 && windowCapacity(next) > 0) {\n const [head, ...rest] = next.pendingEphemeral;\n const sent = sendEventsFrame({ ...next, pendingEphemeral: rest }, [head!], nowMs);\n if (sent.close !== undefined) {\n return {\n ...sent,\n frames: [...frames, ...sent.frames],\n persistSeq: validated.persistSeq,\n };\n }\n next = sent.state;\n frames.push(...sent.frames);\n }\n\n const stale = staleAckResult(next, nowMs);\n if (stale !== undefined) {\n return { ...stale, frames: [...frames, ...stale.frames], persistSeq: validated.persistSeq };\n }\n\n return {\n state: next,\n frames,\n persistSeq: validated.persistSeq,\n ...(windowCapacity(next) > 0 && next.pendingEphemeral.length === 0\n ? { wantsCatchUpAfterSeq: next.sentDurableThroughSeq }\n : {}),\n };\n};\n\ntype AckValidation =\n | { readonly _tag: \"ignore\" }\n | { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult }\n | {\n readonly _tag: \"apply\";\n readonly state: EDAWebSocketDeliveryState;\n readonly persistSeq: SequenceNumber;\n };\n\nconst applyWarmAck = (\n state: EDAWebSocketDeliveryState,\n ack: EDAWebSocketAckFrame,\n): AckValidation => {\n if (ack.frameId <= state.lastAckedFrameId) {\n return ack.durableThroughSeq > state.lastAckedSeq\n ? protocolClose(state, \"Duplicate ACK attempted to advance durable seq\")\n : { _tag: \"ignore\" };\n }\n if (ack.frameId > state.lastSentFrameId) {\n return protocolClose(state, \"ACK referenced an unsent frame\");\n }\n if (ack.durableThroughSeq < state.lastAckedSeq) {\n return protocolClose(state, \"ACK durable seq moved backwards\");\n }\n const acknowledged = state.inFlight.filter((frame) => frame.frameId <= ack.frameId);\n if (acknowledged.length === 0) {\n return protocolClose(state, \"ACK referenced no in-flight frames\");\n }\n const allowedDurableSeq = SequenceNumber.make(\n acknowledged.reduce<number>(\n (max, frame) => Math.max(max, frame.durableThroughSeq),\n state.lastAckedSeq,\n ),\n );\n if (ack.durableThroughSeq > allowedDurableSeq) {\n return protocolClose(state, \"ACK durable seq exceeded sent frame boundary\");\n }\n return {\n _tag: \"apply\",\n persistSeq: ack.durableThroughSeq,\n state: {\n ...state,\n inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),\n lastAckedFrameId: ack.frameId,\n lastAckedSeq: ack.durableThroughSeq,\n },\n };\n};\n\nconst applyColdAck = (\n state: EDAWebSocketDeliveryState,\n ack: EDAWebSocketAckFrame,\n): AckValidation => {\n // Pre-eviction frame ids are unknowable, so only durable-cursor monotonicity\n // is enforced; stale re-ACKs are ignored instead of protocol-closed.\n if (ack.durableThroughSeq < state.lastAckedSeq) {\n return { _tag: \"ignore\" };\n }\n const lastAckedSeq = SequenceNumber.make(Math.max(state.lastAckedSeq, ack.durableThroughSeq));\n return {\n _tag: \"apply\",\n persistSeq: lastAckedSeq,\n state: {\n ...state,\n inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),\n lastAckedFrameId: Math.max(state.lastAckedFrameId, ack.frameId),\n lastAckedSeq,\n // A late ACK can prove delivery beyond what this cold state has sent;\n // never re-send durable events the client has already acknowledged.\n sentDurableThroughSeq: SequenceNumber.make(\n Math.max(state.sentDurableThroughSeq, lastAckedSeq),\n ),\n },\n };\n};\n\nconst windowCapacity = (state: EDAWebSocketDeliveryState): number =>\n state.policy.maxInFlightFrames - state.inFlight.length;\n\nconst sendEventsFrame = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const frameId = FrameId.make(state.nextFrameId);\n const durableThroughSeq = SequenceNumber.make(\n events.reduce<number>(\n (max, event) =>\n event.event.durability === \"durable\" ? Math.max(max, event.position.seq) : max,\n state.sentDurableThroughSeq,\n ),\n );\n const frame = EDAWebSocketEventsFrame.make({\n _tag: \"events\",\n frameId,\n events: events as [PositionedEvent, ...PositionedEvent[]],\n durableThroughSeq,\n });\n const encodedBytes = new TextEncoder().encode(JSON.stringify(frame)).byteLength;\n if (encodedBytes > state.policy.maxFrameBytes) {\n const close = protocolClose(\n state,\n `Encoded WebSocket frame exceeded maxFrameBytes (${encodedBytes} > ${state.policy.maxFrameBytes})`,\n );\n return close.result;\n }\n return {\n state: {\n ...state,\n inFlight: [...state.inFlight, { frameId, durableThroughSeq, sentAtMs: nowMs }],\n lastSentFrameId: frameId,\n nextFrameId: frameId + 1,\n sentDurableThroughSeq: durableThroughSeq,\n },\n frames: [frame],\n };\n};\n\n/** Lazily enforce the ACK deadline: no resident timer, checked on each transition. */\nconst staleAckResult = (\n state: EDAWebSocketDeliveryState,\n nowMs: number,\n): EDAWebSocketDeliveryResult | undefined => {\n const overdue = state.inFlight.some(\n (frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs,\n );\n return overdue ? laggedResult(state, \"ack-timeout\") : undefined;\n};\n\nconst laggedResult = (\n state: EDAWebSocketDeliveryState,\n reason: SubscriberLagReason,\n): EDAWebSocketDeliveryResult => ({\n state,\n frames: [\n EDAWebSocketLaggedFrame.make({\n _tag: \"lagged\",\n resumeSeq: state.lastAckedSeq,\n reason,\n }),\n ],\n close: { code: EDA_WS_CLOSE_LAGGED, reason: laggedCloseReason(state.lastAckedSeq) },\n});\n\nconst protocolClose = (\n state: EDAWebSocketDeliveryState,\n message: string,\n): { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult } => ({\n _tag: \"close\",\n result: {\n state,\n frames: [EDAWebSocketErrorFrame.make({ _tag: \"error\", message: message.slice(0, 120) })],\n close: { code: EDA_WS_CLOSE_PROTOCOL_ERROR, reason: \"protocol\" },\n },\n});\n"],"mappings":";;;;;AAqBA,MAAa,sBAAsB,OAAO,SAAS,CAAC,mBAAmB,aAAa,CAAC;;AAiErF,MAAa,8BACX,WAC+B;CAC/B,cAAc,MAAM;CACpB,QAAQ,MAAM;CACd,cAAc,MAAM,gBAAgB;CACpC,cAAc,MAAM;CACpB,kBAAkB;CAClB,iBAAiB;CACjB,aAAa;CACb,uBAAuB,MAAM;CAC7B,UAAU,CAAC;CACX,kBAAkB,CAAC;AACrB;;AAGA,MAAa,sBAAsB,UACjC,uBAAuB,K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;CACjE;AACF"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { m as SequenceNumber } from "./core-CYT6DBaS.js";
|
|
2
|
+
import { L as PositionedEvent } from "./events-Bb9-Cu-7.js";
|
|
3
|
+
import { a as EDASessionStore, o as EDASessionStoreError } from "./session-store-BLg6UvZa.js";
|
|
4
|
+
import { S as ReducedState } from "./command-queues-Dwdf41mq.js";
|
|
5
|
+
import { t as DurableTranscriptMessage } from "./message-transcript-CFn_D3MH.js";
|
|
6
|
+
import { u as LiveEventBus } from "./sink-registry-CO3YPS1p.js";
|
|
7
|
+
import { i as EDAReducerStateSnapshot } from "./reducer-registry-K9FqZq5-.js";
|
|
8
|
+
import { h as SessionState } from "./session-state-CI1xeT6f.js";
|
|
9
|
+
import * as Context from "effect/Context";
|
|
10
|
+
import * as Effect from "effect/Effect";
|
|
11
|
+
import * as Layer from "effect/Layer";
|
|
12
|
+
import * as Stream from "effect/Stream";
|
|
13
|
+
import * as Scope from "effect/Scope";
|
|
14
|
+
|
|
15
|
+
//#region src/services/session-query.d.ts
|
|
16
|
+
/** Authoritative live snapshot for one EDA session plus its derived durable transcript. */
|
|
17
|
+
interface EDASessionSnapshot {
|
|
18
|
+
readonly state: ReducedState;
|
|
19
|
+
readonly reducerStates: EDAReducerStateSnapshot;
|
|
20
|
+
readonly messages: ReadonlyArray<DurableTranscriptMessage>;
|
|
21
|
+
}
|
|
22
|
+
/** Read-only query facade over authoritative live state and reconnect-safe event streams. */
|
|
23
|
+
interface EDASessionQueryShape {
|
|
24
|
+
/** Read the authoritative live state and derive its durable transcript. */
|
|
25
|
+
readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;
|
|
26
|
+
/** Read durable user/assistant messages in committed sequence order from the live snapshot. */
|
|
27
|
+
readonly messages: () => Effect.Effect<ReadonlyArray<DurableTranscriptMessage>, EDASessionStoreError>;
|
|
28
|
+
/** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */
|
|
29
|
+
readonly eventsAfter: (afterSeq: SequenceNumber) => Effect.Effect<Stream.Stream<PositionedEvent, EDASessionStoreError>, EDASessionStoreError, Scope.Scope>;
|
|
30
|
+
/** Read one bounded committed durable slice after `afterSeq` plus the committed head. */
|
|
31
|
+
readonly eventsSlice: (afterSeq: SequenceNumber, limit: number) => Effect.Effect<EDASessionEventsSlice, EDASessionStoreError>;
|
|
32
|
+
}
|
|
33
|
+
/** Bounded committed durable replay slice for pull-based delivery. */
|
|
34
|
+
interface EDASessionEventsSlice {
|
|
35
|
+
readonly events: ReadonlyArray<PositionedEvent>;
|
|
36
|
+
readonly head: SequenceNumber;
|
|
37
|
+
}
|
|
38
|
+
declare const EDASessionQuery_base: Context.ServiceClass<EDASessionQuery, "@effect-durable-agent/EDASessionQuery", EDASessionQueryShape>;
|
|
39
|
+
/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */
|
|
40
|
+
declare class EDASessionQuery extends EDASessionQuery_base {
|
|
41
|
+
static readonly Live: Layer.Layer<EDASessionQuery, never, SessionState | EDASessionStore | LiveEventBus>;
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { EDASessionSnapshot as i, EDASessionQuery as n, EDASessionQueryShape as r, EDASessionEventsSlice as t };
|
|
45
|
+
//# sourceMappingURL=session-query-5oyZRaQL.d.ts.map
|
|
@@ -1,25 +1,22 @@
|
|
|
1
|
-
import { m as SequenceNumber } from "./core-Hv3cFydL.js";
|
|
2
1
|
import { r as EDACommand } from "./commands-Ce1ec6kH.js";
|
|
3
2
|
import { D as DurableEventEnvelope, F as ModelSelectionPayload, I as NonNegativeInt, L as PositionedEvent, O as EphemeralEventEnvelope } from "./events-Bb9-Cu-7.js";
|
|
4
|
-
import {
|
|
5
|
-
import { a as EDASessionStore, o as EDASessionStoreError, t as CommittedDurableEvent } from "./session-store-
|
|
6
|
-
import { S as ReducedState } from "./command-queues-
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import { t as
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import { r as EDAPromptProjector } from "./prompt-projector-
|
|
14
|
-
import { r as EDAToolRegistry } from "./tool-registry-
|
|
3
|
+
import { kt as ToolCallCreatedEvent } from "./durable-B7M6TD_0.js";
|
|
4
|
+
import { a as EDASessionStore, o as EDASessionStoreError, t as CommittedDurableEvent } from "./session-store-BLg6UvZa.js";
|
|
5
|
+
import { S as ReducedState } from "./command-queues-Dwdf41mq.js";
|
|
6
|
+
import { s as EDASinkRegistry, u as LiveEventBus } from "./sink-registry-CO3YPS1p.js";
|
|
7
|
+
import { t as IdGenerator } from "./id-generator-Ckl8_XWW.js";
|
|
8
|
+
import { r as SessionContext, t as EventFactory } from "./event-factory-CLJcyymV.js";
|
|
9
|
+
import { t as EDAKeepAlive } from "./keep-alive-Chl5SJxy.js";
|
|
10
|
+
import { d as CompactionRunner } from "./compaction-DpHOf-g7.js";
|
|
11
|
+
import { i as EDAReducerStateSnapshot, n as EDAReducerRegistry } from "./reducer-registry-K9FqZq5-.js";
|
|
12
|
+
import { r as EDAPromptProjector } from "./prompt-projector-C2meuNrV.js";
|
|
13
|
+
import { r as EDAToolRegistry } from "./tool-registry-B8H1P6Pu.js";
|
|
15
14
|
import * as Context from "effect/Context";
|
|
16
15
|
import * as Effect from "effect/Effect";
|
|
17
16
|
import * as Layer from "effect/Layer";
|
|
18
17
|
import * as Schema from "effect/Schema";
|
|
19
|
-
import * as Stream from "effect/Stream";
|
|
20
18
|
import * as Prompt from "effect/unstable/ai/Prompt";
|
|
21
19
|
import * as Cause from "effect/Cause";
|
|
22
|
-
import * as Scope from "effect/Scope";
|
|
23
20
|
import * as LanguageModel from "effect/unstable/ai/LanguageModel";
|
|
24
21
|
import * as Response from "effect/unstable/ai/Response";
|
|
25
22
|
|
|
@@ -146,7 +143,7 @@ interface ToolExecutorShape {
|
|
|
146
143
|
declare const ToolExecutor_base: Context.ServiceClass<ToolExecutor, "@effect-durable-agent/ToolExecutor", ToolExecutorShape>;
|
|
147
144
|
/** Executes sealed framework-owned tool calls and commits tool lifecycle boundaries. */
|
|
148
145
|
declare class ToolExecutor extends ToolExecutor_base {
|
|
149
|
-
static readonly Live: Layer.Layer<ToolExecutor, never,
|
|
146
|
+
static readonly Live: Layer.Layer<ToolExecutor, never, EDAToolRegistry | IdGenerator | EventFactory | SessionContext>;
|
|
150
147
|
}
|
|
151
148
|
//#endregion
|
|
152
149
|
//#region src/services/inference-runner.d.ts
|
|
@@ -294,7 +291,7 @@ interface InferenceRunnerShape {
|
|
|
294
291
|
declare const InferenceRunner_base: Context.ServiceClass<InferenceRunner, "@effect-durable-agent/InferenceRunner", InferenceRunnerShape>;
|
|
295
292
|
/** Owns provider inference streams and routes them into durable/live inference emissions. */
|
|
296
293
|
declare class InferenceRunner extends InferenceRunner_base {
|
|
297
|
-
static readonly Live: Layer.Layer<InferenceRunner, never, LanguageModel.LanguageModel |
|
|
294
|
+
static readonly Live: Layer.Layer<InferenceRunner, never, EDAToolRegistry | LanguageModel.LanguageModel | IdGenerator | EventFactory>;
|
|
298
295
|
}
|
|
299
296
|
//#endregion
|
|
300
297
|
//#region src/services/turn-runner.d.ts
|
|
@@ -547,7 +544,7 @@ interface TurnRunnerShape {
|
|
|
547
544
|
declare const TurnRunner_base: Context.ServiceClass<TurnRunner, "@effect-durable-agent/TurnRunner", TurnRunnerShape>;
|
|
548
545
|
/** Owns one turn: turn boundaries, inferences, tool handoff, and terminal turn events. */
|
|
549
546
|
declare class TurnRunner extends TurnRunner_base {
|
|
550
|
-
static readonly Live: Layer.Layer<TurnRunner, never,
|
|
547
|
+
static readonly Live: Layer.Layer<TurnRunner, never, IdGenerator | EventFactory | InferenceRunner | ToolExecutor>;
|
|
551
548
|
}
|
|
552
549
|
//#endregion
|
|
553
550
|
//#region src/services/session-state.d.ts
|
|
@@ -567,6 +564,120 @@ declare const SessionRunInput: Schema.Struct<{
|
|
|
567
564
|
readonly systemPrompt: Schema.optionalKey<Schema.NonEmptyString>;
|
|
568
565
|
}>;
|
|
569
566
|
type SessionRunInput = typeof SessionRunInput.Type;
|
|
567
|
+
/** Command outcome when the command's run completed and the command was completed. */
|
|
568
|
+
declare const SessionCommandCompleted: Schema.TaggedStruct<"SessionCommandCompleted", {
|
|
569
|
+
readonly committed: Schema.Struct<{
|
|
570
|
+
readonly position: Schema.Struct<{
|
|
571
|
+
readonly seq: Schema.brand<Schema.Int, "SequenceNumber">;
|
|
572
|
+
readonly subSeq: Schema.brand<Schema.Literal<0>, "SubSequenceNumber">;
|
|
573
|
+
}>;
|
|
574
|
+
readonly event: Schema.Struct<{
|
|
575
|
+
readonly durability: Schema.Literal<"durable">;
|
|
576
|
+
readonly namespace: Schema.NonEmptyString;
|
|
577
|
+
readonly type: Schema.NonEmptyString;
|
|
578
|
+
readonly schemaVersion: Schema.Int;
|
|
579
|
+
readonly eventId: Schema.brand<Schema.String, "EventId">;
|
|
580
|
+
readonly sessionId: Schema.brand<Schema.String, "SessionId">;
|
|
581
|
+
readonly correlationId: Schema.optionalKey<Schema.brand<Schema.String, "CorrelationId">>;
|
|
582
|
+
readonly createdAtMs: Schema.brand<Schema.Int, "UnixEpochMillis">;
|
|
583
|
+
readonly trace: Schema.withConstructorDefault<Schema.Struct<{
|
|
584
|
+
readonly span: Schema.Struct<{
|
|
585
|
+
readonly traceId: Schema.brand<Schema.String, "EDATraceId">;
|
|
586
|
+
readonly spanId: Schema.brand<Schema.String, "EDASpanId">;
|
|
587
|
+
readonly sampled: Schema.Boolean;
|
|
588
|
+
readonly tracestate: Schema.NullOr<Schema.String>;
|
|
589
|
+
}>;
|
|
590
|
+
readonly links: Schema.$Array<Schema.Struct<{
|
|
591
|
+
readonly context: Schema.Struct<{
|
|
592
|
+
readonly traceId: Schema.brand<Schema.String, "EDATraceId">;
|
|
593
|
+
readonly spanId: Schema.brand<Schema.String, "EDASpanId">;
|
|
594
|
+
readonly sampled: Schema.Boolean;
|
|
595
|
+
readonly tracestate: Schema.NullOr<Schema.String>;
|
|
596
|
+
}>;
|
|
597
|
+
readonly attributes: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Number, Schema.Boolean]>>;
|
|
598
|
+
}>>;
|
|
599
|
+
}>>;
|
|
600
|
+
readonly payload: Schema.Unknown;
|
|
601
|
+
}>;
|
|
602
|
+
}>;
|
|
603
|
+
}>;
|
|
604
|
+
type SessionCommandCompleted = typeof SessionCommandCompleted.Type;
|
|
605
|
+
/** Command outcome when the command's run failed and the command was failed. */
|
|
606
|
+
declare const SessionCommandFailed: Schema.TaggedStruct<"SessionCommandFailed", {
|
|
607
|
+
readonly committed: Schema.Struct<{
|
|
608
|
+
readonly position: Schema.Struct<{
|
|
609
|
+
readonly seq: Schema.brand<Schema.Int, "SequenceNumber">;
|
|
610
|
+
readonly subSeq: Schema.brand<Schema.Literal<0>, "SubSequenceNumber">;
|
|
611
|
+
}>;
|
|
612
|
+
readonly event: Schema.Struct<{
|
|
613
|
+
readonly durability: Schema.Literal<"durable">;
|
|
614
|
+
readonly namespace: Schema.NonEmptyString;
|
|
615
|
+
readonly type: Schema.NonEmptyString;
|
|
616
|
+
readonly schemaVersion: Schema.Int;
|
|
617
|
+
readonly eventId: Schema.brand<Schema.String, "EventId">;
|
|
618
|
+
readonly sessionId: Schema.brand<Schema.String, "SessionId">;
|
|
619
|
+
readonly correlationId: Schema.optionalKey<Schema.brand<Schema.String, "CorrelationId">>;
|
|
620
|
+
readonly createdAtMs: Schema.brand<Schema.Int, "UnixEpochMillis">;
|
|
621
|
+
readonly trace: Schema.withConstructorDefault<Schema.Struct<{
|
|
622
|
+
readonly span: Schema.Struct<{
|
|
623
|
+
readonly traceId: Schema.brand<Schema.String, "EDATraceId">;
|
|
624
|
+
readonly spanId: Schema.brand<Schema.String, "EDASpanId">;
|
|
625
|
+
readonly sampled: Schema.Boolean;
|
|
626
|
+
readonly tracestate: Schema.NullOr<Schema.String>;
|
|
627
|
+
}>;
|
|
628
|
+
readonly links: Schema.$Array<Schema.Struct<{
|
|
629
|
+
readonly context: Schema.Struct<{
|
|
630
|
+
readonly traceId: Schema.brand<Schema.String, "EDATraceId">;
|
|
631
|
+
readonly spanId: Schema.brand<Schema.String, "EDASpanId">;
|
|
632
|
+
readonly sampled: Schema.Boolean;
|
|
633
|
+
readonly tracestate: Schema.NullOr<Schema.String>;
|
|
634
|
+
}>;
|
|
635
|
+
readonly attributes: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Number, Schema.Boolean]>>;
|
|
636
|
+
}>>;
|
|
637
|
+
}>>;
|
|
638
|
+
readonly payload: Schema.Unknown;
|
|
639
|
+
}>;
|
|
640
|
+
}>;
|
|
641
|
+
}>;
|
|
642
|
+
type SessionCommandFailed = typeof SessionCommandFailed.Type;
|
|
643
|
+
/** Command outcome when command work was cancelled by stop, interrupt, or recovery. */
|
|
644
|
+
declare const SessionCommandCancelled: Schema.TaggedStruct<"SessionCommandCancelled", {
|
|
645
|
+
readonly committed: Schema.Struct<{
|
|
646
|
+
readonly position: Schema.Struct<{
|
|
647
|
+
readonly seq: Schema.brand<Schema.Int, "SequenceNumber">;
|
|
648
|
+
readonly subSeq: Schema.brand<Schema.Literal<0>, "SubSequenceNumber">;
|
|
649
|
+
}>;
|
|
650
|
+
readonly event: Schema.Struct<{
|
|
651
|
+
readonly durability: Schema.Literal<"durable">;
|
|
652
|
+
readonly namespace: Schema.NonEmptyString;
|
|
653
|
+
readonly type: Schema.NonEmptyString;
|
|
654
|
+
readonly schemaVersion: Schema.Int;
|
|
655
|
+
readonly eventId: Schema.brand<Schema.String, "EventId">;
|
|
656
|
+
readonly sessionId: Schema.brand<Schema.String, "SessionId">;
|
|
657
|
+
readonly correlationId: Schema.optionalKey<Schema.brand<Schema.String, "CorrelationId">>;
|
|
658
|
+
readonly createdAtMs: Schema.brand<Schema.Int, "UnixEpochMillis">;
|
|
659
|
+
readonly trace: Schema.withConstructorDefault<Schema.Struct<{
|
|
660
|
+
readonly span: Schema.Struct<{
|
|
661
|
+
readonly traceId: Schema.brand<Schema.String, "EDATraceId">;
|
|
662
|
+
readonly spanId: Schema.brand<Schema.String, "EDASpanId">;
|
|
663
|
+
readonly sampled: Schema.Boolean;
|
|
664
|
+
readonly tracestate: Schema.NullOr<Schema.String>;
|
|
665
|
+
}>;
|
|
666
|
+
readonly links: Schema.$Array<Schema.Struct<{
|
|
667
|
+
readonly context: Schema.Struct<{
|
|
668
|
+
readonly traceId: Schema.brand<Schema.String, "EDATraceId">;
|
|
669
|
+
readonly spanId: Schema.brand<Schema.String, "EDASpanId">;
|
|
670
|
+
readonly sampled: Schema.Boolean;
|
|
671
|
+
readonly tracestate: Schema.NullOr<Schema.String>;
|
|
672
|
+
}>;
|
|
673
|
+
readonly attributes: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Number, Schema.Boolean]>>;
|
|
674
|
+
}>>;
|
|
675
|
+
}>>;
|
|
676
|
+
readonly payload: Schema.Unknown;
|
|
677
|
+
}>;
|
|
678
|
+
}>;
|
|
679
|
+
}>;
|
|
680
|
+
type SessionCommandCancelled = typeof SessionCommandCancelled.Type;
|
|
570
681
|
/** Terminal command-processing variants returned from one control action. */
|
|
571
682
|
declare const SessionCommandOutcome: Schema.Union<readonly [Schema.TaggedStruct<"SessionCommandCompleted", {
|
|
572
683
|
readonly committed: Schema.Struct<{
|
|
@@ -680,6 +791,9 @@ interface SessionCommandResult {
|
|
|
680
791
|
readonly started: CommittedDurableEvent;
|
|
681
792
|
readonly outcome: SessionCommandOutcome;
|
|
682
793
|
}
|
|
794
|
+
/** Why a control drain stopped without starting more command work. */
|
|
795
|
+
declare const SessionNoRunnableReason: Schema.Literals<readonly ["active-command", "no-pending-command"]>;
|
|
796
|
+
type SessionNoRunnableReason = typeof SessionNoRunnableReason.Type;
|
|
683
797
|
/** Session control result when no admitted command is runnable. */
|
|
684
798
|
declare const SessionNoRunnableCommand: Schema.TaggedStruct<"SessionNoRunnableCommand", {
|
|
685
799
|
readonly reason: Schema.Literals<readonly ["active-command", "no-pending-command"]>;
|
|
@@ -740,30 +854,8 @@ interface SessionStateShape extends SessionEventSink {
|
|
|
740
854
|
declare const SessionState_base: Context.ServiceClass<SessionState, "@effect-durable-agent/SessionState", SessionStateShape>;
|
|
741
855
|
/** Internal authoritative live state and root control loop for one session. */
|
|
742
856
|
declare class SessionState extends SessionState_base {
|
|
743
|
-
static readonly Live: Layer.Layer<SessionState, EDASessionStoreError,
|
|
744
|
-
}
|
|
745
|
-
//#endregion
|
|
746
|
-
//#region src/services/session-query.d.ts
|
|
747
|
-
/** Authoritative live snapshot for one EDA session plus its derived durable transcript. */
|
|
748
|
-
interface EDASessionSnapshot {
|
|
749
|
-
readonly state: ReducedState;
|
|
750
|
-
readonly reducerStates: EDAReducerStateSnapshot;
|
|
751
|
-
readonly messages: ReadonlyArray<DurableTranscriptMessage>;
|
|
752
|
-
}
|
|
753
|
-
/** Read-only query facade over authoritative live state and reconnect-safe event streams. */
|
|
754
|
-
interface EDASessionQueryShape {
|
|
755
|
-
/** Read the authoritative live state and derive its durable transcript. */
|
|
756
|
-
readonly snapshot: () => Effect.Effect<EDASessionSnapshot, EDASessionStoreError>;
|
|
757
|
-
/** Read durable user/assistant messages in committed sequence order from the live snapshot. */
|
|
758
|
-
readonly messages: () => Effect.Effect<ReadonlyArray<DurableTranscriptMessage>, EDASessionStoreError>;
|
|
759
|
-
/** Backfill durable events after `afterSeq`, then follow live durable/ephemeral events. */
|
|
760
|
-
readonly eventsAfter: (afterSeq: SequenceNumber) => Effect.Effect<Stream.Stream<PositionedEvent, EDASessionStoreError>, EDASessionStoreError, Scope.Scope>;
|
|
761
|
-
}
|
|
762
|
-
declare const EDASessionQuery_base: Context.ServiceClass<EDASessionQuery, "@effect-durable-agent/EDASessionQuery", EDASessionQueryShape>;
|
|
763
|
-
/** Read-only session query facade backed by authoritative SessionState plus durable backfill. */
|
|
764
|
-
declare class EDASessionQuery extends EDASessionQuery_base {
|
|
765
|
-
static readonly Live: Layer.Layer<EDASessionQuery, never, EDASessionStore | LiveEventBus | SessionState>;
|
|
857
|
+
static readonly Live: Layer.Layer<SessionState, EDASessionStoreError, EDASessionStore | LiveEventBus | EDAKeepAlive | IdGenerator | EventFactory | TurnRunner | CompactionRunner | EDAPromptProjector | SessionContext | EDAReducerRegistry | EDASinkRegistry>;
|
|
766
858
|
}
|
|
767
859
|
//#endregion
|
|
768
|
-
export {
|
|
769
|
-
//# sourceMappingURL=session-
|
|
860
|
+
export { ToolExecutor as S, SessionStateShape as _, SessionCommandCompleted as a, InferenceRunner as b, SessionCommandResult as c, SessionForkedCommand as d, SessionNoRunnableCommand as f, SessionStateError as g, SessionState as h, SessionCommandCancelled as i, SessionDrainProcessed as l, SessionRunInput as m, SessionCommandAdmissionConflict as n, SessionCommandFailed as o, SessionNoRunnableReason as p, SessionCommandAdmissionError as r, SessionCommandOutcome as s, EDASubmittable as t, SessionDrainResult as u, SessionStateSnapshotData as v, InferenceRunnerStreamPart as x, TurnRunner as y };
|
|
861
|
+
//# sourceMappingURL=session-state-CI1xeT6f.d.ts.map
|