effect-durable-agent 0.1.0-alpha.1 → 0.1.0-alpha.4

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.
Files changed (136) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/README.md +131 -128
  3. package/SECURITY.md +3 -4
  4. package/dist/{command-queues-CQ9cwRP7.d.ts → command-queues-CV7O-51r.d.ts} +7 -6
  5. package/dist/{compaction-YayFKo_1.d.ts → compaction-zbvLREI8.d.ts} +8 -6
  6. package/dist/context-projection-n6Rdup0N.d.ts +140 -0
  7. package/dist/{core-Hv3cFydL.d.ts → core-CYT6DBaS.d.ts} +2 -2
  8. package/dist/domain/command-queues.d.ts +1 -1
  9. package/dist/domain/context-projection.d.ts +2 -0
  10. package/dist/domain/context-projection.js +32 -0
  11. package/dist/domain/context-projection.js.map +1 -0
  12. package/dist/domain/message-transcript.d.ts +1 -1
  13. package/dist/domain/reduced-state-schema.d.ts +2 -0
  14. package/dist/domain/reduced-state-schema.js +2 -1
  15. package/dist/domain/reduced-state-schema.js.map +1 -1
  16. package/dist/domain/reduced-state.d.ts +1 -1
  17. package/dist/domain/reduced-state.js +1 -1
  18. package/dist/{durable-DlScwmCy.d.ts → durable-B7M6TD_0.d.ts} +341 -2
  19. package/dist/{durable-C3Rz7kg3.js → durable-DsV9PxZC.js} +13 -2
  20. package/dist/durable-DsV9PxZC.js.map +1 -0
  21. package/dist/{keep-alive-DYDsH6qN.d.ts → event-factory-CLJcyymV.d.ts} +5 -29
  22. package/dist/{keep-alive-p8dIcSVy.js → event-factory-tcpLgdMN.js} +3 -10
  23. package/dist/event-factory-tcpLgdMN.js.map +1 -0
  24. package/dist/host/websocket-protocol.d.ts +229 -0
  25. package/dist/host/websocket-protocol.js +99 -0
  26. package/dist/host/websocket-protocol.js.map +1 -0
  27. package/dist/host/websocket-wire.d.ts +2 -2
  28. package/dist/host/websocket-wire.js +37 -20
  29. package/dist/host/websocket-wire.js.map +1 -1
  30. package/dist/{id-generator-C2Q15uZM.d.ts → id-generator-Ckl8_XWW.d.ts} +2 -2
  31. package/dist/index.d.ts +4 -4
  32. package/dist/index.js +2 -2
  33. package/dist/keep-alive-Chl5SJxy.d.ts +29 -0
  34. package/dist/{message-transcript-BCHdHAe2.d.ts → message-transcript-DiOPBY3l.d.ts} +3 -3
  35. package/dist/{prompt-projector-9_02lk5-.d.ts → prompt-projector-C1IbkHr0.d.ts} +15 -16
  36. package/dist/{reduced-state-C4nVVzz9.js → reduced-state-TMi7ISla.js} +20 -4
  37. package/dist/reduced-state-TMi7ISla.js.map +1 -0
  38. package/dist/{reducer-registry-C0svUa63.d.ts → reducer-registry-CjSJBPKo.d.ts} +2 -2
  39. package/dist/{runtime-C56FQxiL.d.ts → runtime-DOgmAKsO.d.ts} +7 -6
  40. package/dist/services/compaction.d.ts +1 -1
  41. package/dist/services/compaction.js +4 -3
  42. package/dist/services/compaction.js.map +1 -1
  43. package/dist/services/id-generator.d.ts +1 -1
  44. package/dist/services/keep-alive.d.ts +2 -0
  45. package/dist/services/keep-alive.js +13 -0
  46. package/dist/services/keep-alive.js.map +1 -0
  47. package/dist/services/prompt-projector.d.ts +2 -2
  48. package/dist/services/prompt-projector.js +20 -10
  49. package/dist/services/prompt-projector.js.map +1 -1
  50. package/dist/services/reducer-registry.d.ts +1 -1
  51. package/dist/services/runtime-layer.d.ts +58 -0
  52. package/dist/services/runtime-layer.js +42 -0
  53. package/dist/services/runtime-layer.js.map +1 -0
  54. package/dist/services/runtime.d.ts +1 -1
  55. package/dist/services/runtime.js +4 -3
  56. package/dist/services/runtime.js.map +1 -1
  57. package/dist/services/session-query.d.ts +1 -1
  58. package/dist/services/session-query.js +76 -1
  59. package/dist/services/session-query.js.map +1 -0
  60. package/dist/services/session-state.d.ts +2 -0
  61. package/dist/services/session-state.js +2 -0
  62. package/dist/services/session-store.d.ts +2 -2
  63. package/dist/services/session-store.js +181 -2
  64. package/dist/services/session-store.js.map +1 -0
  65. package/dist/services/sink-checkpoint-store.d.ts +2 -0
  66. package/dist/services/sink-checkpoint-store.js +49 -0
  67. package/dist/services/sink-checkpoint-store.js.map +1 -0
  68. package/dist/services/sink-registry.d.ts +1 -1
  69. package/dist/services/sink-registry.js +1 -1
  70. package/dist/services/tool-registry.d.ts +1 -1
  71. package/dist/services/websocket-subscriber.d.ts +54 -0
  72. package/dist/services/websocket-subscriber.js +190 -0
  73. package/dist/services/websocket-subscriber.js.map +1 -0
  74. package/dist/session-query-C-C4m1eq.d.ts +38 -0
  75. package/dist/{session-query-DlRo5Ufc.d.ts → session-state-CjOSvWbe.d.ts} +132 -40
  76. package/dist/{session-query-DOc1KanA.js → session-state-SStf0KUo.js} +43 -146
  77. package/dist/session-state-SStf0KUo.js.map +1 -0
  78. package/dist/{session-store-D2Ore1QC.d.ts → session-store-DZZUffUy.d.ts} +5 -94
  79. package/dist/sink-checkpoint-store-BZmQFTRE.d.ts +40 -0
  80. package/dist/{sink-registry-CIU0LD3m.d.ts → sink-registry-Cf79ICdW.d.ts} +11 -40
  81. package/dist/{sink-registry-CFC6xjsN.js → sink-registry-D13eUO_c.js} +9 -47
  82. package/dist/sink-registry-D13eUO_c.js.map +1 -0
  83. package/dist/testkit/layers.d.ts +14 -11
  84. package/dist/testkit/layers.js +8 -5
  85. package/dist/testkit/layers.js.map +1 -1
  86. package/dist/{tool-registry-CcnkAAQK.d.ts → tool-registry-B7Wona6N.d.ts} +3 -3
  87. package/dist/types/core.d.ts +1 -1
  88. package/dist/types/core.js +1 -1
  89. package/dist/types/core.js.map +1 -1
  90. package/dist/types/events/durable.d.ts +2 -2
  91. package/dist/types/events/durable.js +2 -2
  92. package/dist/types/events.d.ts +2 -2
  93. package/dist/types/events.js +2 -2
  94. package/dist/websocket-wire-QD2SquQE.d.ts +2244 -0
  95. package/docs/assets/architecture.svg +170 -60
  96. package/docs/assets/event-sequence.svg +68 -78
  97. package/docs/assets/hero.svg +33 -0
  98. package/docs/message-steering.md +1 -1
  99. package/docs/releasing.md +96 -39
  100. package/docs/spec.md +15 -12
  101. package/docs/websocket-protocol.md +35 -9
  102. package/package.json +55 -35
  103. package/dist/durable-C3Rz7kg3.js.map +0 -1
  104. package/dist/durable-object-runtime-B7jwBY2R.js +0 -1494
  105. package/dist/durable-object-runtime-B7jwBY2R.js.map +0 -1
  106. package/dist/durable-object-runtime-pWv0ohlz.d.ts +0 -257
  107. package/dist/durable-object-storage-Czy7IPrh.d.ts +0 -41
  108. package/dist/host/durable-object-runtime.d.ts +0 -2
  109. package/dist/host/durable-object-runtime.js +0 -2
  110. package/dist/host/durable-object-storage.d.ts +0 -2
  111. package/dist/host/durable-object-storage.js +0 -0
  112. package/dist/host/durable-object.d.ts +0 -83
  113. package/dist/host/durable-object.js +0 -191
  114. package/dist/host/durable-object.js.map +0 -1
  115. package/dist/keep-alive-p8dIcSVy.js.map +0 -1
  116. package/dist/reduced-state-C4nVVzz9.js.map +0 -1
  117. package/dist/session-query-DOc1KanA.js.map +0 -1
  118. package/dist/session-store-pYxQW9qh.js +0 -214
  119. package/dist/session-store-pYxQW9qh.js.map +0 -1
  120. package/dist/sink-registry-CFC6xjsN.js.map +0 -1
  121. package/dist/websocket-wire-DvOu_6BJ.d.ts +0 -16773
  122. package/examples/001-no-tools/README.md +0 -65
  123. package/examples/001-no-tools/worker.ts +0 -79
  124. package/examples/002-slack-bridge/README.md +0 -134
  125. package/examples/002-slack-bridge/events.ts +0 -115
  126. package/examples/002-slack-bridge/reducer.ts +0 -216
  127. package/examples/002-slack-bridge/scenario.test.ts +0 -223
  128. package/examples/002-slack-bridge/sinks.ts +0 -109
  129. package/examples/002-slack-bridge/worker.ts +0 -140
  130. package/examples/003-sandbox-lifecycle/README.md +0 -78
  131. package/examples/003-sandbox-lifecycle/events.ts +0 -203
  132. package/examples/003-sandbox-lifecycle/reducer.ts +0 -305
  133. package/examples/003-sandbox-lifecycle/scenario.test.ts +0 -202
  134. package/examples/_shared/event-id.ts +0 -12
  135. package/examples/_shared/http.ts +0 -27
  136. package/examples/_shared/openai.ts +0 -33
@@ -1,223 +0,0 @@
1
- import * as Effect from "effect/Effect";
2
- import * as Prompt from "effect/unstable/ai/Prompt";
3
- import { describe, expect, it } from "vite-plus/test";
4
-
5
- import { CommandIdempotencyKey, SubmitMessageCommand } from "../../src/types/commands";
6
- import {
7
- InferenceId,
8
- CommandId,
9
- EventId,
10
- MessageId,
11
- RunId,
12
- SequenceNumber,
13
- SessionId,
14
- TurnId,
15
- durablePosition,
16
- } from "../../src/types/core";
17
- import {
18
- AssistantMessageCommittedPayload,
19
- CommandAdmittedPayload,
20
- DurableEventEnvelope,
21
- EventType,
22
- RunStartedPayload,
23
- UnixEpochMillis,
24
- UserMessageCommittedPayload,
25
- assistantMessageCommittedEventType,
26
- commandAdmittedEventType,
27
- effectDurableAgentNamespace,
28
- runStartedEventType,
29
- schemaV1,
30
- userMessageCommittedEventType,
31
- } from "../../src/types/events";
32
- import { sequentialUuidV7 } from "../../src/services/id-generator";
33
- import { CommittedDurableEvent } from "../../src/services/session-store";
34
- import type { EDASinkContext, EDASinkDurableBatch } from "../../src/services/sink-registry";
35
- import {
36
- OutboundSlackIdempotencyKey,
37
- SlackChannelId,
38
- SlackEventId,
39
- SlackEvents,
40
- SlackMessageTs,
41
- SlackTeamId,
42
- SlackThreadTs,
43
- SlackUserId,
44
- } from "./events";
45
- import { SlackBridgeReducer, initialSlackBridgeState, reduceSlackBridgeState } from "./reducer";
46
- import { makeSlackReplySink, type SlackClient } from "./sinks";
47
-
48
- const SESSION_ID = SessionId.make("018f6bd5-2f2a-7b1e-8f1a-1f2e3d4c5b6a");
49
- const COMMAND_ID = CommandId.make(sequentialUuidV7(1));
50
- const USER_MESSAGE_ID = MessageId.make(sequentialUuidV7(2));
51
- const ASSISTANT_MESSAGE_ID = MessageId.make(sequentialUuidV7(3));
52
- const RUN_ID = RunId.make(sequentialUuidV7(4));
53
- const TURN_ID = TurnId.make(sequentialUuidV7(5));
54
- const INFERENCE_ID = InferenceId.make(sequentialUuidV7(6));
55
- const IDEMPOTENCY_KEY = CommandIdempotencyKey.make("slack:event:Ev123");
56
- const MODEL_SELECTION = { provider: "test", modelId: "test-model" };
57
-
58
- const command = new SubmitMessageCommand({
59
- commandId: COMMAND_ID,
60
- idempotencyKey: IDEMPOTENCY_KEY,
61
- disposition: "queue",
62
- content: [Prompt.textPart({ text: "Please summarize this incident." })],
63
- });
64
-
65
- describe("Slack bridge example", () => {
66
- it("derives Slack bridge state from framework events and app events", () => {
67
- const state = baseScenarioEvents()
68
- .concat([
69
- committed(
70
- 6,
71
- SlackEvents.replyDelivered({
72
- assistantMessageId: ASSISTANT_MESSAGE_ID,
73
- teamId: slackMessageReceived.teamId,
74
- channelId: slackMessageReceived.channelId,
75
- threadTs: slackMessageReceived.threadTs,
76
- slackMessageTs: SlackMessageTs.make("1729.001"),
77
- outboundIdempotencyKey: OutboundSlackIdempotencyKey.make(
78
- `${SESSION_ID}:${ASSISTANT_MESSAGE_ID}`,
79
- ),
80
- createdAtMs: UnixEpochMillis.make(1_715_000_000_000),
81
- eventId: EventId.make(sequentialUuidV7(206)),
82
- sessionId: SESSION_ID,
83
- }),
84
- ),
85
- ])
86
- .reduce(reduceSlackBridgeState, initialSlackBridgeState);
87
-
88
- expect(state.slackByCommandId.get(COMMAND_ID)?.slackEventId).toBe("Ev123");
89
- expect(state.slackByUserMessageId.get(USER_MESSAGE_ID)?.threadTs).toBe("1729.000");
90
- expect(state.slackByAssistantMessageId.get(ASSISTANT_MESSAGE_ID)?.channelId).toBe("C1");
91
- expect(state.deliveredByAssistantMessageId.get(ASSISTANT_MESSAGE_ID)?.slackMessageTs).toBe(
92
- "1729.001",
93
- );
94
- });
95
-
96
- it("keeps Slack delivery idempotent when EDA retries the same sink batch", async () => {
97
- const calls: Array<{ readonly idempotencyKey: string; readonly text: string }> = [];
98
- const flakySlackClient: SlackClient = {
99
- postThreadReply: (input) =>
100
- Effect.gen(function* () {
101
- calls.push({ idempotencyKey: input.idempotencyKey, text: input.text });
102
- if (calls.length === 1) {
103
- return yield* Effect.fail(new Error("transient Slack outage"));
104
- }
105
- return SlackMessageTs.make("1729.002");
106
- }),
107
- };
108
- const sink = makeSlackReplySink(flakySlackClient).durable!;
109
- const assistantEvent = baseScenarioEvents().at(-1)!;
110
- const reducerState = baseScenarioEvents().reduce(
111
- reduceSlackBridgeState,
112
- initialSlackBridgeState,
113
- );
114
- const batch: EDASinkDurableBatch = {
115
- allEvents: baseScenarioEvents(),
116
- events: [assistantEvent],
117
- reducerStates: new Map([[SlackBridgeReducer.name, reducerState]]),
118
- throughSeq: assistantEvent.position.seq,
119
- stateAfter: undefined as never,
120
- };
121
-
122
- const staged: Array<DurableEventEnvelope> = [];
123
- await expect(Effect.runPromise(sink.process(batch, sinkContext(staged)))).rejects.toThrow(
124
- "transient Slack outage",
125
- );
126
- expect(staged).toEqual([]);
127
-
128
- await Effect.runPromise(sink.process(batch, sinkContext(staged)));
129
-
130
- expect(calls).toHaveLength(2);
131
- expect(new Set(calls.map((call) => call.idempotencyKey)).size).toBe(1);
132
- expect(staged.map((event) => event.type)).toEqual(["SlackReplyDelivered"]);
133
- });
134
- });
135
-
136
- const baseScenarioEvents = (): ReadonlyArray<CommittedDurableEvent> => [
137
- frameworkEvent(1, commandAdmittedEventType, CommandAdmittedPayload.make({ command })),
138
- committed(
139
- 2,
140
- SlackEvents.messageReceived({
141
- ...slackMessageReceived,
142
- relatedCommandIdempotencyKey: IDEMPOTENCY_KEY,
143
- }),
144
- ),
145
- frameworkEvent(
146
- 3,
147
- userMessageCommittedEventType,
148
- UserMessageCommittedPayload.make({
149
- commandId: COMMAND_ID,
150
- messageId: USER_MESSAGE_ID,
151
- content: [Prompt.textPart({ text: "Please summarize this incident." })],
152
- }),
153
- ),
154
- frameworkEvent(
155
- 4,
156
- runStartedEventType,
157
- RunStartedPayload.make({
158
- runId: RUN_ID,
159
- commandIds: [COMMAND_ID],
160
- modelSelection: MODEL_SELECTION,
161
- }),
162
- ),
163
- frameworkEvent(
164
- 5,
165
- assistantMessageCommittedEventType,
166
- AssistantMessageCommittedPayload.make({
167
- messageId: ASSISTANT_MESSAGE_ID,
168
- runId: RUN_ID,
169
- turnId: TURN_ID,
170
- inferenceId: INFERENCE_ID,
171
- promptParts: [Prompt.textPart({ text: "Here is the summary." })],
172
- }),
173
- ),
174
- ];
175
-
176
- const slackMessageReceived = {
177
- teamId: SlackTeamId.make("T1"),
178
- channelId: SlackChannelId.make("C1"),
179
- threadTs: SlackThreadTs.make("1729.000"),
180
- slackEventId: SlackEventId.make("Ev123"),
181
- slackUserId: SlackUserId.make("U1"),
182
- text: "Please summarize this incident.",
183
- createdAtMs: UnixEpochMillis.make(1_715_000_000_000),
184
- eventId: EventId.make(sequentialUuidV7(200)),
185
- sessionId: SESSION_ID,
186
- };
187
-
188
- const sinkContext = (staged: Array<DurableEventEnvelope>): EDASinkContext => ({
189
- sessionId: SESSION_ID,
190
- checkpoint: {
191
- get: (_schema, initial) => Effect.succeed(initial),
192
- save: () => Effect.void,
193
- },
194
- events: undefined as never,
195
- makeEventId: () => Effect.succeed(EventId.make(sequentialUuidV7(900 + staged.length))),
196
- stageDurable: (event) =>
197
- Effect.sync(() => {
198
- staged.push(event);
199
- }),
200
- emitEphemeral: () => Effect.die("not used in this example"),
201
- forkScoped: () => Effect.die("not used in this example"),
202
- });
203
-
204
- const frameworkEvent = (seq: number, type: EventType, payload: unknown): CommittedDurableEvent =>
205
- committed(
206
- seq,
207
- DurableEventEnvelope.make({
208
- namespace: effectDurableAgentNamespace,
209
- type,
210
- schemaVersion: schemaV1,
211
- durability: "durable",
212
- eventId: EventId.make(sequentialUuidV7(100 + seq)),
213
- sessionId: SESSION_ID,
214
- createdAtMs: UnixEpochMillis.make(1_715_000_000_000 + seq),
215
- payload,
216
- }),
217
- );
218
-
219
- const committed = (seq: number, event: DurableEventEnvelope): CommittedDurableEvent =>
220
- CommittedDurableEvent.make({
221
- position: durablePosition(SequenceNumber.make(seq)),
222
- event,
223
- });
@@ -1,109 +0,0 @@
1
- import * as Effect from "effect/Effect";
2
- import * as Schema from "effect/Schema";
3
-
4
- import { getEDAReducerState } from "../../src/services/reducer-registry";
5
- import { EDASink } from "../../src/services/sink-registry";
6
- import {
7
- AssistantMessageCommittedPayload,
8
- UnixEpochMillis,
9
- assistantMessageCommittedEventType,
10
- } from "../../src/types/events";
11
- import {
12
- OutboundSlackIdempotencyKey,
13
- SlackChannelId,
14
- SlackEvents,
15
- SlackMessageTs,
16
- SlackTeamId,
17
- SlackThreadTs,
18
- } from "./events";
19
- import { SlackBridgeReducer } from "./reducer";
20
-
21
- /** External Slack API seam used by the durable sink. */
22
- export interface SlackClient {
23
- readonly postThreadReply: (input: {
24
- readonly teamId: SlackTeamId;
25
- readonly channelId: SlackChannelId;
26
- readonly threadTs: SlackThreadTs;
27
- readonly idempotencyKey: OutboundSlackIdempotencyKey;
28
- readonly text: string;
29
- }) => Effect.Effect<SlackMessageTs, unknown>;
30
- }
31
-
32
- /**
33
- * Durable sink: after an assistant message commits, deliver it to Slack.
34
- *
35
- * If delivery fails, the sink cursor does not advance and EDA will retry. If
36
- * delivery succeeds, the sink stages `SlackReplyDelivered` in the same session
37
- * log so future retries and all clients can see the durable delivery fact.
38
- */
39
- export const makeSlackReplySink = (client: SlackClient): EDASink =>
40
- EDASink.make({
41
- name: "example.slack.reply-delivery",
42
- durable: {
43
- interests: [assistantMessageCommittedEventType],
44
- process: (batch, ctx) =>
45
- Effect.gen(function* () {
46
- const state = getEDAReducerState(batch.reducerStates, SlackBridgeReducer);
47
-
48
- for (const entry of batch.events) {
49
- const assistant = decodeAssistantMessage(entry.event.payload);
50
- if (assistant === undefined) {
51
- continue;
52
- }
53
- if (state.deliveredByAssistantMessageId.has(assistant.messageId)) {
54
- continue;
55
- }
56
-
57
- const slack = state.slackByAssistantMessageId.get(assistant.messageId);
58
- if (slack === undefined) {
59
- continue;
60
- }
61
-
62
- const outboundKey = OutboundSlackIdempotencyKey.make(
63
- `${ctx.sessionId}:${assistant.messageId}`,
64
- );
65
- const slackMessageTs = yield* client.postThreadReply({
66
- teamId: slack.teamId,
67
- channelId: slack.channelId,
68
- threadTs: slack.threadTs,
69
- idempotencyKey: outboundKey,
70
- text: renderAssistantText(assistant),
71
- });
72
-
73
- yield* ctx.stageDurable(
74
- SlackEvents.replyDelivered({
75
- assistantMessageId: assistant.messageId,
76
- teamId: slack.teamId,
77
- channelId: slack.channelId,
78
- threadTs: slack.threadTs,
79
- slackMessageTs,
80
- outboundIdempotencyKey: outboundKey,
81
- createdAtMs: UnixEpochMillis.make(Date.now()),
82
- eventId: yield* ctx.makeEventId(),
83
- sessionId: ctx.sessionId,
84
- }),
85
- );
86
- }
87
- }),
88
- },
89
- });
90
-
91
- export const loggingSlackClient: SlackClient = {
92
- postThreadReply: (input) =>
93
- Effect.gen(function* () {
94
- yield* Effect.logInfo("Would post Slack thread reply", input);
95
- return SlackMessageTs.make(`reply-${input.idempotencyKey}`);
96
- }),
97
- };
98
-
99
- const decodeAssistantMessage = (payload: unknown): AssistantMessageCommittedPayload | undefined =>
100
- Schema.is(AssistantMessageCommittedPayload)(payload) ? payload : undefined;
101
-
102
- export const renderAssistantText = (payload: AssistantMessageCommittedPayload): string => {
103
- const text = payload.promptParts
104
- .filter((part) => part.type === "text")
105
- .map((part) => part.text)
106
- .join("\n")
107
- .trim();
108
- return text.length === 0 ? "(assistant response had no visible text)" : text;
109
- };
@@ -1,140 +0,0 @@
1
- import * as Prompt from "effect/unstable/ai/Prompt";
2
-
3
- import { CommandIdempotencyKey, SubmitMessageCommand } from "../../src/types/commands";
4
- import { SessionId } from "../../src/types/core";
5
- import { UnixEpochMillis } from "../../src/types/events";
6
- import { makeRootEDATraceMetadata } from "../../src/types/tracing";
7
- import {
8
- EDASessionDurableObject,
9
- getEDASessionDurableObjectByName,
10
- } from "../../src/host/durable-object";
11
- import { mintExampleEventId } from "../_shared/event-id";
12
- import { json, parseJsonObject, pathParam, requiredString } from "../_shared/http";
13
- import { makeExampleOpenAiOptions, type ExampleOpenAiEnv } from "../_shared/openai";
14
- import {
15
- SlackChannelId,
16
- SlackEventId,
17
- SlackEvents,
18
- SlackTeamId,
19
- SlackThreadTs,
20
- SlackUserId,
21
- } from "./events";
22
- import { SlackBridgeReducer } from "./reducer";
23
- import { loggingSlackClient, makeSlackReplySink } from "./sinks";
24
-
25
- /** Bindings used by the Slack bridge EDA example Worker. */
26
- export interface SlackBridgeEDAEnv extends ExampleOpenAiEnv {
27
- readonly SlackBridgeEDASession: DurableObjectNamespace<SlackBridgeEDASession>;
28
- }
29
-
30
- /** Concrete session object with Slack reducer + reply sink installed. */
31
- export class SlackBridgeEDASession extends EDASessionDurableObject<SlackBridgeEDAEnv> {
32
- constructor(ctx: DurableObjectState, env: SlackBridgeEDAEnv) {
33
- super(ctx, env, {
34
- ...makeExampleOpenAiOptions(env),
35
- reducers: [SlackBridgeReducer],
36
- sinks: [makeSlackReplySink(loggingSlackClient)],
37
- });
38
- }
39
- }
40
-
41
- /**
42
- * Minimal Slack-ish facade.
43
- *
44
- * The important move is submitting `[command, SlackMessageReceived]` together:
45
- * one durable admission boundary captures both the model input and its Slack
46
- * identity/idempotency metadata.
47
- */
48
- export default {
49
- async fetch(request, env): Promise<Response> {
50
- const url = new URL(request.url);
51
-
52
- const rawSlackSessionId = pathParam(url.pathname, /^\/sessions\/([^/]+)\/slack\/events\/?$/);
53
- if (request.method === "POST" && rawSlackSessionId !== null) {
54
- const body = await parseJsonObject(request);
55
- const parsed = parseSlackEvent(body);
56
- if ("error" in parsed) {
57
- return json({ error: parsed.error }, 400);
58
- }
59
-
60
- const sessionId = SessionId.make(rawSlackSessionId);
61
- const session = getEDASessionDurableObjectByName(env.SlackBridgeEDASession, sessionId);
62
- const idempotencyKey = CommandIdempotencyKey.make(`slack:event:${parsed.slackEventId}`);
63
- const trace = makeRootEDATraceMetadata();
64
-
65
- const committed = await session.submitBatch({
66
- sessionId,
67
- trace,
68
- items: [
69
- new SubmitMessageCommand({
70
- idempotencyKey,
71
- disposition: "queue",
72
- content: [Prompt.textPart({ text: parsed.text })],
73
- }),
74
- SlackEvents.messageReceived({
75
- relatedCommandIdempotencyKey: idempotencyKey,
76
- teamId: SlackTeamId.make(parsed.teamId),
77
- channelId: SlackChannelId.make(parsed.channelId),
78
- threadTs: SlackThreadTs.make(parsed.threadTs),
79
- slackEventId: SlackEventId.make(parsed.slackEventId),
80
- slackUserId: SlackUserId.make(parsed.slackUserId),
81
- text: parsed.text,
82
- createdAtMs: UnixEpochMillis.make(Date.now()),
83
- eventId: await mintExampleEventId(),
84
- sessionId,
85
- }),
86
- ],
87
- });
88
-
89
- return json({ committed, messages: await session.messages({ sessionId, trace }) }, 202);
90
- }
91
-
92
- const rawMessagesSessionId = pathParam(url.pathname, /^\/sessions\/([^/]+)\/messages\/?$/);
93
- if (request.method === "GET" && rawMessagesSessionId !== null) {
94
- const sessionId = SessionId.make(rawMessagesSessionId);
95
- const session = getEDASessionDurableObjectByName(env.SlackBridgeEDASession, sessionId);
96
- return json(await session.messages({ sessionId, trace: makeRootEDATraceMetadata() }));
97
- }
98
-
99
- return json(
100
- {
101
- error: "Use POST /sessions/:sessionId/slack/events or GET /sessions/:sessionId/messages",
102
- },
103
- 404,
104
- );
105
- },
106
- } satisfies ExportedHandler<SlackBridgeEDAEnv>;
107
-
108
- interface ParsedSlackEvent {
109
- readonly teamId: string;
110
- readonly channelId: string;
111
- readonly threadTs: string;
112
- readonly slackEventId: string;
113
- readonly slackUserId: string;
114
- readonly text: string;
115
- }
116
-
117
- const parseSlackEvent = (
118
- body: Record<string, unknown>,
119
- ): ParsedSlackEvent | { readonly error: string } => {
120
- const teamId = requiredString(body, "teamId");
121
- const channelId = requiredString(body, "channelId");
122
- const threadTs = requiredString(body, "threadTs");
123
- const slackEventId = requiredString(body, "slackEventId");
124
- const slackUserId = requiredString(body, "slackUserId");
125
- const text = requiredString(body, "text");
126
- if (
127
- teamId === undefined ||
128
- channelId === undefined ||
129
- threadTs === undefined ||
130
- slackEventId === undefined ||
131
- slackUserId === undefined ||
132
- text === undefined
133
- ) {
134
- return {
135
- error:
136
- "Expected JSON body with teamId, channelId, threadTs, slackEventId, slackUserId, and text",
137
- };
138
- }
139
- return { teamId, channelId, threadTs, slackEventId, slackUserId, text };
140
- };
@@ -1,78 +0,0 @@
1
- # 003 — Sandbox Lifecycle
2
-
3
- This example shows the design space where EDA becomes much more than chat persistence.
4
-
5
- A coding agent session often owns product state tightly coupled to the agent run:
6
-
7
- - a sandbox starts;
8
- - commands run inside it;
9
- - a preview URL appears;
10
- - a human approval is requested;
11
- - the tool finishes;
12
- - the sandbox is stopped later.
13
-
14
- In EDA, those are not side-channel callbacks. They are durable app events in the same ordered session history as the framework tool and message lifecycle.
15
-
16
- ## The sequence
17
-
18
- ```text
19
- seq event projection effect
20
- --- ------------------------------------------------ -------------------------------
21
- 1 effect-durable-agent/ToolCallCreated tool card appears
22
- 2 example.sandbox/SandboxStarting sandbox status: starting
23
- 3 example.sandbox/SandboxStarted sandbox status: running
24
- 4 example.sandbox/CommandStarted command row starts
25
- 5 example.sandbox/CommandCompleted command row gets wallClockTimeMs
26
- 6 example.sandbox/PreviewReady preview card gets URL
27
- 7 example.sandbox/ApprovalRequested approval card waits
28
- 8 example.sandbox/ApprovalGranted approval card resolves
29
- 9 effect-durable-agent/ToolCallCompleted tool card completes
30
- 10 example.sandbox/SandboxStopped sandbox status: stopped
31
- ```
32
-
33
- ## What to notice
34
-
35
- ### 1. Framework state and app state reduce together
36
-
37
- `reducer.ts` folds both EDA framework events and sandbox app events:
38
-
39
- ```text
40
- ToolCallCreated
41
- SandboxStarting
42
- SandboxStarted
43
- CommandStarted
44
- CommandCompleted
45
- PreviewReady
46
- ApprovalRequested
47
- ApprovalGranted
48
- ToolCallCompleted
49
- SandboxStopped
50
- ```
51
-
52
- That one reducer derives the UI model: active sandbox, running command, last command timing, preview URL, approval state, tool card status, and stop reason.
53
-
54
- ### 2. SSR handoff is just reducer math
55
-
56
- `scenario.test.ts` demonstrates the handoff directly:
57
-
58
- ```text
59
- server renders state through seq N
60
- client receives state_N
61
- client requests events where seq > N
62
- client reduces the suffix
63
- client converges to the same state as a full replay
64
- ```
65
-
66
- No separate sandbox sync protocol is needed. The sandbox lifecycle is already part of the same event sequence as the agent lifecycle.
67
-
68
- ### 3. Recovery has a real source of truth
69
-
70
- If the process restarts, EDA can replay the durable session log and recover the committed facts. The reducer knows whether the sandbox started, which command finished, whether approval was granted, and where the tool lifecycle ended.
71
-
72
- ## Files
73
-
74
- - `events.ts` — sandbox/preview/approval durable event schemas.
75
- - `reducer.ts` — pure UI/app projection over framework + app events.
76
- - `scenario.test.ts` — executable reducer and SSR handoff scenarios.
77
-
78
- This example intentionally has no Worker facade. It is about the state-machine model itself, without HTTP or provider plumbing getting in the way.