Open History to see the last commit
1import {
2 CommandId,
3 type OrchestrationV2Run,
4 OrchestrationV2DomainEvent,
5 type OrchestrationV2ProviderThread,
6 type OrchestrationV2Subagent,
7 type OrchestrationV2TurnItem,
8 OrchestrationV2StoredEvent,
9 ProviderThreadId,
10 RunAttemptId,
11 RunId,
12 RuntimeRequestId,
13 NodeId,
14 type ProjectId,
15 ThreadId,
16} from "@t3tools/contracts";
17import * as ProviderCommitBatch from "./ProviderCommitBatch.ts";
18import * as Context from "effect/Context";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as PubSub from "effect/PubSub";
24import * as Semaphore from "effect/Semaphore";
25import * as Schema from "effect/Schema";
26import * as Stream from "effect/Stream";
27import * as SqlClient from "effect/sql/SqlClient";
28import * as SqlError from "effect/sql/SqlError";
29
30import { replayAndBufferProjectedLiveEvents } from "./LiveStreamBudget.ts";
31import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts";
32import { projectStoredEventForWire } from "./WireProjection.ts";
33import { makeRunOutcomeRecorder, type RunOutcome } from "./RunMetrics.ts";
34
35import * as CommandReceiptStore from "./CommandReceiptStore.ts";
36import * as EffectOutbox from "./EffectOutbox.ts";
37import * as EventStore from "./EventStore.ts";
38import * as ProjectionStore from "./ProjectionStore.ts";
39import * as ProjectStore from "./ProjectStore.ts";
40import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";
41
42export class EventSinkWriteError extends Schema.TaggedError<EventSinkWriteError>()(
43 "EventSinkWriteError",
44 {
45 eventCount: Schema.Number,
46 commandId: Schema.optional(CommandId),
47 cause: Schema.optional(Schema.Defect()),
48 },
49) {
50 override get message(): string {
51 return `Failed to write ${this.eventCount} orchestration V2 event(s).`;
52 }
53}
54
55export class EventSinkStreamError extends Schema.TaggedError<EventSinkStreamError>()(
56 "EventSinkStreamError",
57 {
58 threadId: Schema.optional(ThreadId),
59 afterSequence: Schema.optional(Schema.Number),
60 cause: Schema.optional(Schema.Defect()),
61 },
62) {
63 override get message(): string {
64 return this.threadId === undefined
65 ? "Failed to stream orchestration V2 events."
66 : `Failed to stream orchestration V2 events for thread ${this.threadId}.`;
67 }
68}
69
70export const EventSinkV2Error = Schema.Union([EventSinkWriteError, EventSinkStreamError]);
71export type EventSinkV2Error = typeof EventSinkV2Error.Type;
72
73interface ProviderBatchPublication {
74 readonly publish: Array<Effect.Effect<void>>;
75 eventCount: number;
76}
77const CurrentProviderBatch = Context.Reference<ProviderBatchPublication | undefined>(
78 "t3/orchestration-v2/EventSink/CurrentProviderBatch",
79 { defaultValue: () => undefined },
80);
81
82export interface EventSinkV2Shape {
83 /** Items that are not provider snapshots, such as a consumer's own control items, never batch. */
84 readonly consumeProviderEvents: <A extends { readonly type: string }, E, R, E2, R2>(
85 source: Stream.Stream<A, E, R>,
86 process: (event: A) => Effect.Effect<void, E2, R2>,
87 after: Effect.Effect<boolean, E2, R2>,
88 canBatch: Effect.Effect<boolean, never, R2>,
89 ) => Effect.Effect<
90 void,
91 E | E2 | ProviderCommitBatch.CommitBatchError | Schema.SchemaError,
92 R | R2
93 >;
94
95 /** Normalize and persist an ordered group against one transaction; publish after its commit. */
96 readonly withProviderBatch: <A, E, R>(
97 effect: Effect.Effect<A, E, R>,
98 ) => Effect.Effect<A, E | EventSinkV2Error, R>;
99
100 readonly write: (input: {
101 /** Return no events if another thread owns this native session at commit time. */
102 readonly unlessNativeThreadOwned?: Pick<
103 OrchestrationV2ProviderThread,
104 "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
105 >;
106 readonly guardPendingUserInputCancellations?: boolean;
107 readonly commandId?: CommandId;
108 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
109 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
110 readonly writeWithEffects: (input: {
111 /**
112 * Rebuilds each run.updated from the stored row with only its delegatedCompletion replaced.
113 * The batch must not also change that run's lifecycle.
114 */
115 readonly updateDelegatedCompletionOnly?: boolean;
116 readonly unlessNativeThreadOwned?: Pick<
117 OrchestrationV2ProviderThread,
118 "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
119 >;
120 readonly guardPendingUserInputCancellations?: boolean;
121 readonly commandId?: CommandId;
122 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
123 readonly effects: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
124 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
125 readonly writeIfRunCurrent: (input: {
126 readonly guardPendingUserInputCancellations?: boolean;
127 readonly commandId?: CommandId;
128 readonly threadId: ThreadId;
129 readonly runId: RunId;
130 readonly activeAttemptId: RunAttemptId;
131 readonly expectedStatus: OrchestrationV2Run["status"];
132 /** Also refuse while this run interrupt request is stored without its result. */
133 readonly unlessInterruptRequested?: {
134 readonly requestId: OrchestrationV2TurnItem["id"];
135 readonly resultId: OrchestrationV2TurnItem["id"];
136 };
137 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
138 readonly effects?: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
139 }) => Effect.Effect<
140 {
141 readonly committed: boolean;
142 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
143 },
144 EventSinkV2Error
145 >;
146 /** Commits only if the expected attempt and ordinal still own the provider thread, protecting newer attempts. */
147 readonly writeIfProviderThreadOwner: (input: {
148 readonly guardPendingUserInputCancellations?: boolean;
149 readonly commandId?: CommandId;
150 readonly providerThreadId: ProviderThreadId;
151 readonly runId: RunId;
152 readonly activeAttemptId: RunAttemptId;
153 readonly expectedLastRunOrdinal: number;
154 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
155 }) => Effect.Effect<
156 {
157 readonly committed: boolean;
158 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
159 },
160 EventSinkV2Error
161 >;
162 /** Commits only if the full provider row equals expected; some writers do not advance updatedAt. */
163 readonly writeIfProviderThreadUnchanged: (input: {
164 readonly expected: OrchestrationV2ProviderThread;
165 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
166 }) => Effect.Effect<
167 {
168 readonly committed: boolean;
169 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
170 },
171 EventSinkV2Error
172 >;
173 /** Commits only if the stored turn item still equals expected. */
174 readonly writeIfTurnItemUnchanged: (input: {
175 readonly expected: OrchestrationV2TurnItem;
176 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
177 }) => Effect.Effect<
178 {
179 readonly committed: boolean;
180 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
181 },
182 EventSinkV2Error
183 >;
184 /** Commits only if the stored subagent still equals expected. */
185 readonly writeIfSubagentUnchanged: (input: {
186 readonly expected: OrchestrationV2Subagent;
187 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
188 }) => Effect.Effect<
189 {
190 readonly committed: boolean;
191 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
192 },
193 EventSinkV2Error
194 >;
195 readonly commitCommand: (input: {
196 readonly commandId: CommandId;
197 readonly threadId: ThreadId;
198 readonly commandType: string;
199 readonly acceptedAt: DateTime.Utc;
200 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
201 readonly effects: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
202 readonly cancelUnsettledEffects?: {
203 readonly effectTypes: ReadonlyArray<EffectOutbox.OrchestrationEffectRequestV2["type"]>;
204 readonly reason: string;
205 };
206 /** Like writeWithEffects' updateDelegatedCompletionOnly, for this run's run.updated only. */
207 readonly updateDelegatedCompletionOnlyRunId?: RunId;
208 }) => Effect.Effect<
209 {
210 readonly receipt: CommandReceiptStore.CommandReceiptV2;
211 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
212 readonly committed: boolean;
213 readonly cancelledEffectCount: number;
214 },
215 EventSinkV2Error
216 >;
217 readonly commitRejectedCommand: (input: {
218 readonly commandId: CommandId;
219 readonly threadId: ThreadId;
220 readonly commandType: string;
221 readonly rejectedAt: DateTime.Utc;
222 readonly error: string;
223 }) => Effect.Effect<CommandReceiptStore.CommandReceiptV2, EventSinkV2Error>;
224 readonly commitProjectCommand: (input: {
225 readonly commandId: CommandId;
226 readonly projectId: ProjectId;
227 readonly commandType: string;
228 readonly acceptedAt: DateTime.Utc;
229 readonly event: UnsequencedProjectEvent;
230 }) => Effect.Effect<
231 { readonly receipt: CommandReceiptStore.ProjectCommandReceiptV2; readonly committed: boolean },
232 EventSinkV2Error
233 >;
234 readonly commitRejectedProjectCommand: (input: {
235 readonly commandId: CommandId;
236 readonly projectId: ProjectId;
237 readonly commandType: string;
238 readonly rejectedAt: DateTime.Utc;
239 readonly error: string;
240 }) => Effect.Effect<CommandReceiptStore.ProjectCommandReceiptV2, EventSinkV2Error>;
241 readonly stream: (input?: {
242 readonly threadId?: ThreadId;
243 readonly afterSequence?: number;
244 readonly eventType?: OrchestrationV2DomainEvent["type"];
245 /** Bound RPC subscribers; internal workers must not drop their subscription under load. */
246 readonly bounded?: boolean;
247 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
248 readonly latestSequence: (input?: {
249 readonly threadId?: ThreadId;
250 }) => Effect.Effect<number, EventSinkV2Error>;
251 readonly readByCommandId: (input: {
252 readonly commandId: CommandId;
253 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
254}
255
256export class EventSinkV2 extends Context.Service<EventSinkV2, EventSinkV2Shape>()(
257 "t3/orchestration-v2/EventSink/EventSinkV2",
258) {}
259
260const layerBase: Layer.Layer<
261 EventSinkV2,
262 never,
263 | CommandReceiptStore.CommandReceiptStoreV2
264 | EffectOutbox.EffectOutboxV2
265 | EventStore.EventStoreV2
266 | ProjectionStore.ProjectionStoreV2
267 | ProjectStore.ProjectStoreV2
268 | SqlClient.SqlClient
269 | TurnItemPositionStore.TurnItemPositionStoreV2
270> = Layer.effect(
271 EventSinkV2,
272 Effect.gen(function* () {
273 const sql = yield* SqlClient.SqlClient;
274 const commandReceipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
275 const effectOutbox = yield* EffectOutbox.EffectOutboxV2;
276 const eventStore = yield* EventStore.EventStoreV2;
277 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
278 const projectStore = yield* ProjectStore.ProjectStoreV2;
279 const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
280 const liveEvents = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
281 const liveEventsByType = new Map<
282 OrchestrationV2DomainEvent["type"],
283 PubSub.PubSub<OrchestrationV2StoredEvent>
284 >();
285 const publishLiveEvents =
286 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
287 Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2StoredEvent>) {
288 yield* PubSub.publishAll(liveEvents, events);
289 for (const [type, pubsub] of liveEventsByType) {
290 yield* PubSub.publishAll(
291 pubsub,
292 events.filter((stored) => stored.event.type === type),
293 );
294 }
295 });
296 const runOutcomes = makeRunOutcomeRecorder((threadId) =>
297 // One payload row; unlike the shell, it still resolves a deleted child thread.
298 projectionStore
299 .getThread(threadId)
300 .pipe(Effect.map((thread) => thread.lineage.relationshipToParent === "subagent")),
301 );
302 // Recorded before publication, so an interrupted publish cannot lose a committed outcome.
303 const publishStoredEvents = (
304 events: ReadonlyArray<OrchestrationV2StoredEvent>,
305 outcomes: ReadonlyArray<RunOutcome>,
306 ) =>
307 runOutcomes
308 .record(outcomes)
309 .pipe(
310 Effect.andThen(eventStore.publishCommitted(events)),
311 Effect.andThen(publishLiveEvents(events)),
312 );
313
314 // Serialize commit and publish; reordered publication makes clients drop earlier sequences.
315 const publishLane = yield* Semaphore.make(1);
316 const commitThenPublishNow = <A, E, R>(
317 transaction: Effect.Effect<A, E, R>,
318 publish: (committed: A) => Effect.Effect<void>,
319 ) =>
320 Effect.uninterruptibleMask((restore) => {
321 let holdsLane = false;
322 const takeLane = publishLane.take(1).pipe(
323 Effect.andThen(
324 Effect.sync(() => {
325 holdsLane = true;
326 }),
327 ),
328 Effect.uninterruptible,
329 );
330 // Cancellation may roll back the transaction's work. Once it commits,
331 // every subscriber must hear about it before this writer can exit.
332 // Otherwise a failed child run can leave its parent's task running.
333 return sql
334 .withTransaction(Effect.tap(restore(transaction), () => takeLane))
335 .pipe(
336 Effect.tap(publish),
337 Effect.ensuring(
338 Effect.suspend(() => (holdsLane ? publishLane.release(1) : Effect.void)),
339 ),
340 );
341 });
342
343 // A user can answer after terminal normalization reads the pending request.
344 // Recheck inside the write transaction so stale cleanup cannot erase answers.
345 const guardUserInputCancellations =
346 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
347 Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2DomainEvent>) {
348 const staleRequests = new Set<RuntimeRequestId>();
349 const staleNodes = new Set<NodeId>();
350 for (const event of events) {
351 if (
352 event.type !== "runtime-request.updated" ||
353 event.payload.kind !== "user_input" ||
354 event.payload.status !== "cancelled"
355 )
356 continue;
357 const current = yield* projectionStore.getRuntimeRequest(
358 event.threadId,
359 event.payload.id,
360 );
361 if (
362 current?.status !== "pending" ||
363 current.kind !== "user_input" ||
364 current.providerTurnId !== event.payload.providerTurnId ||
365 current.responseCapability.type === "message"
366 ) {
367 staleRequests.add(event.payload.id);
368 staleNodes.add(event.payload.nodeId);
369 }
370 }
371 return events.filter((event) => {
372 switch (event.type) {
373 case "runtime-request.updated":
374 return event.payload.status !== "cancelled" || !staleRequests.has(event.payload.id);
375 case "node.updated":
376 return event.payload.status !== "cancelled" || !staleNodes.has(event.payload.id);
377 case "turn-item.updated":
378 return (
379 event.payload.type !== "user_input_request" ||
380 event.payload.status !== "cancelled" ||
381 !staleRequests.has(event.payload.requestId)
382 );
383 default:
384 return true;
385 }
386 });
387 });
388
389 const normalizeEvents = (events: ReadonlyArray<OrchestrationV2DomainEvent>) => {
390 const runOrdinals = new Map(
391 events.flatMap((event) =>
392 event.type === "run.created" || event.type === "run.updated"
393 ? [[event.payload.id, event.payload.ordinal] as const]
394 : [],
395 ),
396 );
397 return Effect.forEach(
398 events,
399 (event): Effect.Effect<OrchestrationV2DomainEvent, unknown> =>
400 event.type === "turn-item.updated"
401 ? turnItemPositions
402 .normalize(
403 event.payload,
404 event.payload.runId === null ? undefined : runOrdinals.get(event.payload.runId),
405 )
406 .pipe(Effect.map((payload) => ({ ...event, payload })))
407 : Effect.succeed(event),
408 { concurrency: 1 },
409 );
410 };
411
412 const applyStoredEvents =
413 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
414 Effect.fnUntraced(function* (storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>) {
415 yield* Effect.forEach(storedEvents, (stored) => projectionStore.apply(stored.event), {
416 concurrency: 1,
417 });
418 const sequence = storedEvents.at(-1)?.sequence;
419 if (sequence !== undefined) {
420 const now = DateTime.formatIso(yield* DateTime.now);
421 yield* sql`
422 INSERT INTO orchestration_v2_projection_metadata (
423 projection_name,
424 schema_version,
425 last_sequence,
426 updated_at
427 )
428 VALUES (
429 'thread-projections',
430 ${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
431 ${sequence},
432 ${now}
433 )
434 ON CONFLICT(projection_name)
435 DO UPDATE SET
436 schema_version = excluded.schema_version,
437 last_sequence = excluded.last_sequence,
438 updated_at = excluded.updated_at
439 `;
440 }
441 // Read lineage here, on the connection this transaction holds; see makeRunOutcomeRecorder.
442 return yield* runOutcomes.prepare(storedEvents);
443 });
444
445 // The enclosing write or commit span already traces this per-event projection merge.
446 const updateDelegatedCompletionOnly = Effect.fnUntraced(function* (
447 events: ReadonlyArray<OrchestrationV2DomainEvent>,
448 includesRun: (runId: RunId) => boolean,
449 ) {
450 return yield* Effect.forEach(events, (event) =>
451 Effect.gen(function* () {
452 if (event.type !== "run.updated" || !includesRun(event.payload.id)) return event;
453 const { runs } = yield* projectionStore.getThreadRecords(event.threadId, ["runs"], {
454 runIds: [event.payload.id],
455 });
456 const current = runs[0];
457 return current === undefined
458 ? event
459 : {
460 ...event,
461 payload: { ...current, delegatedCompletion: event.payload.delegatedCompletion },
462 };
463 }),
464 );
465 });
466
467 const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* (
468 input: Parameters<EventSinkV2Shape["writeWithEffects"]>[0],
469 ) {
470 yield* Effect.annotateCurrentSpan({
471 "orchestration_v2.command_id": input.commandId ?? null,
472 "orchestration_v2.event_count": input.events.length,
473 "orchestration_v2.thread_id": input.events[0]?.threadId ?? null,
474 });
475
476 const batch = yield* CurrentProviderBatch;
477 if (batch !== undefined) batch.eventCount += input.events.length;
478 const { committed } = yield* commitThenPublish(
479 Effect.gen(function* () {
480 // Check ownership in the same transaction that claims the native session.
481 const imported = input.unlessNativeThreadOwned;
482 if (imported?.nativeThreadRef != null) {
483 const owners = yield* sql`
484 SELECT provider_thread_id
485 FROM orchestration_v2_projection_provider_threads
486 WHERE driver = ${imported.driver}
487 AND provider_instance_id = ${imported.providerInstanceId}
488 AND thread_id IS NOT ${imported.appThreadId}
489 AND json_extract(payload_json, '$.nativeThreadRef.nativeId') = ${imported.nativeThreadRef.nativeId}
490 LIMIT 1
491 `;
492 if (owners.length > 0) return { committed: [], outcomes: [] };
493 }
494 // Checkpoint capture can finish after a cohort writer reads its parent run.
495 // Merge in this transaction so the event log and projection keep that completion.
496 const events = input.updateDelegatedCompletionOnly
497 ? yield* updateDelegatedCompletionOnly(input.events, () => true)
498 : input.events;
499 const normalized = yield* normalizeEvents(
500 input.guardPendingUserInputCancellations === true
501 ? yield* guardUserInputCancellations(events)
502 : events,
503 );
504 const committed = yield* eventStore.append({
505 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
506 events: normalized,
507 });
508 const outcomes = yield* applyStoredEvents(committed);
509 yield* effectOutbox.enqueue(input.effects);
510 return { committed, outcomes };
511 }).pipe(Effect.withTracerEnabled(false)),
512 ({ committed, outcomes }) =>
513 Effect.gen(function* () {
514 if (input.effects.length > 0) {
515 yield* effectOutbox.notifyAvailable(input.effects.length);
516 }
517 yield* publishStoredEvents(committed, outcomes);
518 }),
519 );
520 return committed;
521 });
522
523 const writeIfRunCurrentEffect = Effect.fn("orchestrationV2.EventSink.writeIfRunCurrent")(
524 function* (input: Parameters<EventSinkV2Shape["writeIfRunCurrent"]>[0]) {
525 yield* Effect.annotateCurrentSpan({
526 "orchestration_v2.command_id": input.commandId ?? null,
527 "orchestration_v2.event_count": input.events.length,
528 "orchestration_v2.run_id": input.runId,
529 "orchestration_v2.thread_id": input.threadId,
530 });
531
532 return yield* commitThenPublish(
533 Effect.gen(function* () {
534 const rows = yield* sql<{
535 readonly status: string;
536 readonly active_attempt_id: string | null;
537 }>`
538 SELECT
539 status,
540 json_extract(payload_json, '$.activeAttemptId') AS active_attempt_id
541 FROM orchestration_v2_projection_runs
542 WHERE run_id = ${input.runId}
543 AND thread_id = ${input.threadId}
544 LIMIT 1
545 `;
546 const current = rows[0];
547 if (
548 current === undefined ||
549 current.status !== input.expectedStatus ||
550 current.active_attempt_id !== input.activeAttemptId
551 ) {
552 return {
553 committed: false as const,
554 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
555 };
556 }
557 if (input.unlessInterruptRequested !== undefined) {
558 const { requestId, resultId } = input.unlessInterruptRequested;
559 const pending = yield* sql<{ readonly pending: number }>`
560 SELECT EXISTS (
561 SELECT 1 FROM orchestration_v2_projection_turn_items
562 WHERE thread_id = ${input.threadId} AND turn_item_id = ${requestId}
563 ) AND NOT EXISTS (
564 SELECT 1 FROM orchestration_v2_projection_turn_items
565 WHERE thread_id = ${input.threadId} AND turn_item_id = ${resultId}
566 ) AS pending
567 `;
568 if (pending[0]?.pending === 1) {
569 return {
570 committed: false as const,
571 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
572 };
573 }
574 }
575
576 const normalized = yield* normalizeEvents(
577 input.guardPendingUserInputCancellations === true
578 ? yield* guardUserInputCancellations(input.events)
579 : input.events,
580 );
581 const storedEvents = yield* eventStore.append({
582 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
583 events: normalized,
584 });
585 const outcomes = yield* applyStoredEvents(storedEvents);
586 yield* effectOutbox.enqueue(input.effects ?? []);
587 return { committed: true as const, storedEvents, outcomes };
588 }),
589 (result) =>
590 Effect.gen(function* () {
591 if (!result.committed) return;
592 if (input.effects !== undefined && input.effects.length > 0) {
593 yield* effectOutbox.notifyAvailable(input.effects.length);
594 }
595 yield* publishStoredEvents(result.storedEvents, result.outcomes);
596 }),
597 );
598 },
599 );
600
601 const writeIfProviderThreadOwnerEffect = Effect.fn(
602 "orchestrationV2.EventSink.writeIfProviderThreadOwner",
603 )(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadOwner"]>[0]) {
604 yield* Effect.annotateCurrentSpan({
605 "orchestration_v2.command_id": input.commandId ?? null,
606 "orchestration_v2.event_count": input.events.length,
607 "orchestration_v2.provider_thread_id": input.providerThreadId,
608 "orchestration_v2.run_id": input.runId,
609 "orchestration_v2.active_attempt_id": input.activeAttemptId,
610 "orchestration_v2.expected_last_run_ordinal": input.expectedLastRunOrdinal,
611 });
612
613 return yield* commitThenPublish(
614 Effect.gen(function* () {
615 const rows = yield* sql<{
616 readonly active_attempt_id: string | null;
617 readonly last_run_ordinal: number | null;
618 }>`
619 SELECT
620 json_extract(r.payload_json, '$.activeAttemptId') AS active_attempt_id,
621 p.last_run_ordinal
622 FROM orchestration_v2_projection_provider_threads p
623 JOIN orchestration_v2_projection_runs r
624 ON r.run_id = ${input.runId}
625 AND r.thread_id = p.thread_id
626 WHERE p.provider_thread_id = ${input.providerThreadId}
627 LIMIT 1
628 `;
629 const current = rows[0];
630 if (
631 current === undefined ||
632 current.active_attempt_id !== input.activeAttemptId ||
633 current.last_run_ordinal !== input.expectedLastRunOrdinal
634 ) {
635 return {
636 committed: false as const,
637 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
638 };
639 }
640
641 const normalized = yield* normalizeEvents(
642 input.guardPendingUserInputCancellations === true
643 ? yield* guardUserInputCancellations(input.events)
644 : input.events,
645 );
646 const storedEvents = yield* eventStore.append({
647 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
648 events: normalized,
649 });
650 const outcomes = yield* applyStoredEvents(storedEvents);
651 return { committed: true as const, storedEvents, outcomes };
652 }),
653 (result) =>
654 result.committed
655 ? publishStoredEvents(result.storedEvents, result.outcomes)
656 : Effect.void,
657 );
658 });
659
660 // Appends the events only if the stored payload still matches, in one transaction.
661 const writeIfStoredPayloadMatches = <E>(
662 readStoredPayload: Effect.Effect<ReadonlyArray<{ readonly payload_json: string }>, E>,
663 expectedJson: string,
664 events: ReadonlyArray<OrchestrationV2DomainEvent>,
665 ) =>
666 commitThenPublish(
667 Effect.gen(function* () {
668 const rows = yield* readStoredPayload;
669 if (rows[0]?.payload_json !== expectedJson) {
670 return {
671 committed: false as const,
672 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
673 };
674 }
675
676 const normalized = yield* normalizeEvents(events);
677 const storedEvents = yield* eventStore.append({ events: normalized });
678 const outcomes = yield* applyStoredEvents(storedEvents);
679 return { committed: true as const, storedEvents, outcomes };
680 }),
681 (result) =>
682 result.committed
683 ? publishStoredEvents(result.storedEvents, result.outcomes)
684 : Effect.void,
685 );
686
687 const writeIfProviderThreadUnchangedEffect = Effect.fn(
688 "orchestrationV2.EventSink.writeIfProviderThreadUnchanged",
689 )(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadUnchanged"]>[0]) {
690 yield* Effect.annotateCurrentSpan({
691 "orchestration_v2.event_count": input.events.length,
692 "orchestration_v2.provider_thread_id": input.expected.id,
693 });
694 const expectedJson = yield* ProjectionStore.encodeProviderThreadPayload(input.expected);
695 return yield* writeIfStoredPayloadMatches(
696 sql<{ readonly payload_json: string }>`
697 SELECT payload_json
698 FROM orchestration_v2_projection_provider_threads
699 WHERE provider_thread_id = ${input.expected.id}
700 LIMIT 1
701 `,
702 expectedJson,
703 input.events,
704 );
705 });
706
707 const writeIfTurnItemUnchangedEffect = Effect.fn(
708 "orchestrationV2.EventSink.writeIfTurnItemUnchanged",
709 )(function* (input: Parameters<EventSinkV2Shape["writeIfTurnItemUnchanged"]>[0]) {
710 yield* Effect.annotateCurrentSpan({
711 "orchestration_v2.event_count": input.events.length,
712 "orchestration_v2.turn_item_id": input.expected.id,
713 });
714 const expectedJson = yield* ProjectionStore.encodeTurnItemPayload(input.expected);
715 return yield* writeIfStoredPayloadMatches(
716 sql<{ readonly payload_json: string }>`
717 SELECT payload_json
718 FROM orchestration_v2_projection_turn_items
719 WHERE turn_item_id = ${input.expected.id}
720 LIMIT 1
721 `,
722 expectedJson,
723 input.events,
724 );
725 });
726
727 const writeIfSubagentUnchangedEffect = Effect.fn(
728 "orchestrationV2.EventSink.writeIfSubagentUnchanged",
729 )(function* (input: Parameters<EventSinkV2Shape["writeIfSubagentUnchanged"]>[0]) {
730 yield* Effect.annotateCurrentSpan({
731 "orchestration_v2.event_count": input.events.length,
732 "orchestration_v2.subagent_id": input.expected.id,
733 });
734 const expectedJson = yield* ProjectionStore.encodeSubagentPayload(input.expected);
735 return yield* writeIfStoredPayloadMatches(
736 sql<{ readonly payload_json: string }>`
737 SELECT payload_json
738 FROM orchestration_v2_projection_subagents
739 WHERE subagent_id = ${input.expected.id}
740 LIMIT 1
741 `,
742 expectedJson,
743 input.events,
744 );
745 });
746
747 const existingCommandResult =
748 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
749 Effect.fnUntraced(function* (commandId: CommandId) {
750 const existing = yield* commandReceipts.getByCommandId(commandId);
751 if (Option.isNone(existing)) {
752 return yield* Effect.die(
753 new Error(`Command receipt ${commandId} disappeared during its transaction.`),
754 );
755 }
756 const storedEvents = yield* eventStore.readByCommandId({ commandId }).pipe(
757 Stream.runCollect,
758 Effect.map((events): ReadonlyArray<OrchestrationV2StoredEvent> => Array.from(events)),
759 );
760 return { receipt: existing.value, storedEvents };
761 });
762
763 const commitCommandEffect = Effect.fn("orchestrationV2.EventSink.commitCommand")(function* (
764 input: Parameters<EventSinkV2Shape["commitCommand"]>[0],
765 ) {
766 const result = yield* commitThenPublish(
767 Effect.gen(function* () {
768 const reserved = yield* commandReceipts.insertIfAbsent({
769 commandId: input.commandId,
770 threadId: input.threadId,
771 commandType: input.commandType,
772 acceptedAt: input.acceptedAt,
773 resultSequence: 0,
774 status: "accepted",
775 error: null,
776 });
777 if (!reserved) {
778 const existing = yield* existingCommandResult(input.commandId);
779 return { ...existing, committed: false as const, cancelledEffectIds: [] };
780 }
781
782 const runId = input.updateDelegatedCompletionOnlyRunId;
783 const normalized = yield* normalizeEvents(
784 runId === undefined
785 ? input.events
786 : yield* updateDelegatedCompletionOnly(input.events, (id) => id === runId),
787 );
788 const storedEvents = yield* eventStore.append({
789 commandId: input.commandId,
790 events: normalized,
791 });
792 // A Stop that changes nothing can still queue the stop of its delegated tasks.
793 const sequence =
794 storedEvents.at(-1)?.sequence ??
795 (input.effects.length === 0
796 ? undefined
797 : yield* eventStore.latestSequence({ threadId: input.threadId }));
798 if (sequence === undefined) {
799 return yield* Effect.die(
800 new Error(`Command ${input.commandId} produced no orchestration events.`),
801 );
802 }
803 const outcomes = yield* applyStoredEvents(storedEvents);
804 yield* effectOutbox.enqueue(input.effects);
805 const receipt: CommandReceiptStore.CommandReceiptV2 = {
806 commandId: input.commandId,
807 threadId: input.threadId,
808 commandType: input.commandType,
809 acceptedAt: input.acceptedAt,
810 resultSequence: sequence,
811 status: "accepted",
812 error: null,
813 };
814 yield* commandReceipts.upsert(receipt);
815 const cancelledEffectIds =
816 input.cancelUnsettledEffects === undefined
817 ? []
818 : yield* effectOutbox.cancelUnsettled({
819 threadId: input.threadId,
820 ...input.cancelUnsettledEffects,
821 });
822 return { receipt, storedEvents, outcomes, committed: true as const, cancelledEffectIds };
823 }),
824 (result) =>
825 Effect.gen(function* () {
826 yield* effectOutbox.signalCancellations(result.cancelledEffectIds);
827 if (result.committed && input.effects.length > 0) {
828 yield* effectOutbox.notifyAvailable(input.effects.length);
829 }
830 if (result.committed) yield* publishStoredEvents(result.storedEvents, result.outcomes);
831 }),
832 );
833 return {
834 receipt: result.receipt,
835 storedEvents: result.storedEvents,
836 committed: result.committed,
837 cancelledEffectCount: result.cancelledEffectIds.length,
838 };
839 });
840
841 const commitRejectedCommandEffect = Effect.fn(
842 "orchestrationV2.EventSink.commitRejectedCommand",
843 )(function* (input: Parameters<EventSinkV2Shape["commitRejectedCommand"]>[0]) {
844 return yield* sql.withTransaction(
845 Effect.gen(function* () {
846 const sequence = yield* eventStore.latestSequence({ threadId: input.threadId });
847 const receipt: CommandReceiptStore.CommandReceiptV2 = {
848 commandId: input.commandId,
849 threadId: input.threadId,
850 commandType: input.commandType,
851 acceptedAt: input.rejectedAt,
852 resultSequence: sequence,
853 status: "rejected",
854 error: input.error,
855 };
856 const inserted = yield* commandReceipts.insertIfAbsent(receipt);
857 if (inserted) {
858 return receipt;
859 }
860 const existing = yield* commandReceipts.getByCommandId(input.commandId);
861 return Option.getOrElse(existing, () => receipt);
862 }),
863 );
864 });
865
866 const existingProjectReceipt = (commandId: CommandId) =>
867 commandReceipts.getProjectByCommandId(commandId).pipe(
868 Effect.flatMap(
869 Option.match({
870 onNone: () =>
871 Effect.fail(`Command ${commandId} was already used by a thread command.` as const),
872 onSome: Effect.succeed,
873 }),
874 ),
875 );
876
877 const commitProjectCommandEffect = Effect.fn("orchestrationV2.EventSink.commitProjectCommand")(
878 function* (input: Parameters<EventSinkV2Shape["commitProjectCommand"]>[0]) {
879 const result = yield* commitThenPublish(
880 Effect.gen(function* () {
881 const reserved: CommandReceiptStore.ProjectCommandReceiptV2 = {
882 commandId: input.commandId,
883 projectId: input.projectId,
884 commandType: input.commandType,
885 acceptedAt: input.acceptedAt,
886 resultSequence: 0,
887 status: "accepted",
888 error: null,
889 };
890 if (!(yield* commandReceipts.insertIfAbsent(reserved))) {
891 return { receipt: yield* existingProjectReceipt(input.commandId), event: undefined };
892 }
893 const event = yield* eventStore.appendProjectEvent(input.event);
894 yield* projectStore.apply(event);
895 const receipt = { ...reserved, resultSequence: event.sequence };
896 yield* commandReceipts.upsert(receipt);
897 return { receipt, event };
898 }),
899 (result) =>
900 result.event === undefined ? Effect.void : eventStore.publishCommitted([result.event]),
901 );
902 return { receipt: result.receipt, committed: result.event !== undefined };
903 },
904 );
905
906 const commitRejectedProjectCommandEffect = Effect.fn(
907 "orchestrationV2.EventSink.commitRejectedProjectCommand",
908 )(function* (input: Parameters<EventSinkV2Shape["commitRejectedProjectCommand"]>[0]) {
909 return yield* sql.withTransaction(
910 Effect.gen(function* () {
911 const receipt: CommandReceiptStore.ProjectCommandReceiptV2 = {
912 commandId: input.commandId,
913 projectId: input.projectId,
914 commandType: input.commandType,
915 acceptedAt: input.rejectedAt,
916 resultSequence: yield* eventStore.latestApplicationSequence,
917 status: "rejected",
918 error: input.error,
919 };
920 return (yield* commandReceipts.insertIfAbsent(receipt))
921 ? receipt
922 : yield* existingProjectReceipt(input.commandId);
923 }),
924 );
925 });
926
927 const catchUp = (input: {
928 readonly afterSequence: number;
929 readonly throughSequence: number;
930 readonly threadId?: ThreadId;
931 readonly eventType?: OrchestrationV2DomainEvent["type"];
932 }): Stream.Stream<OrchestrationV2StoredEvent, unknown> => {
933 const pageSize = 256;
934 const loop = (afterSequence: number): Stream.Stream<OrchestrationV2StoredEvent, unknown> =>
935 Stream.unwrap(
936 eventStore
937 .read({
938 afterSequence,
939 throughSequence: input.throughSequence,
940 ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
941 ...(input.eventType === undefined ? {} : { eventType: input.eventType }),
942 limit: pageSize,
943 })
944 .pipe(
945 Stream.runCollect,
946 Effect.map((chunk) => Array.from(chunk)),
947 Effect.map((events) => {
948 if (events.length === 0) {
949 return Stream.empty;
950 }
951 const current = Stream.fromIterable(events);
952 const last = events.at(-1)?.sequence ?? input.throughSequence;
953 return events.length < pageSize || last >= input.throughSequence
954 ? current
955 : Stream.concat(current, loop(last));
956 }),
957 ),
958 );
959 return loop(input.afterSequence);
960 };
961
962 const stream = (input?: Parameters<EventSinkV2Shape["stream"]>[0]) => {
963 const afterSequence = input?.afterSequence ?? 0;
964 const matches = (stored: OrchestrationV2StoredEvent) =>
965 (input?.threadId === undefined || stored.event.threadId === input.threadId) &&
966 (input?.eventType === undefined || stored.event.type === input.eventType);
967 const replay = (throughSequence: number) =>
968 catchUp({
969 afterSequence,
970 throughSequence,
971 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
972 ...(input?.eventType === undefined ? {} : { eventType: input.eventType }),
973 }).pipe(Stream.filter(matches));
974 return Stream.unwrap(
975 Effect.gen(function* () {
976 let pubsub = liveEvents;
977 if (input?.eventType !== undefined) {
978 const existing = liveEventsByType.get(input.eventType);
979 if (existing !== undefined) {
980 pubsub = existing;
981 } else {
982 const created = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
983 pubsub = liveEventsByType.get(input.eventType) ?? created;
984 liveEventsByType.set(input.eventType, pubsub);
985 }
986 }
987 if (input?.bounded === true) {
988 return replayAndBufferProjectedLiveEvents({
989 subscribe: PubSub.subscribe(pubsub),
990 latestSequence: eventStore.latestSequence(),
991 afterSequence,
992 filter: matches,
993 replay,
994 project: projectStoredEventForWire,
995 });
996 }
997 const subscription = yield* PubSub.subscribe(pubsub);
998 const highWater = yield* eventStore.latestSequence();
999 const live = Stream.fromSubscription(subscription).pipe(
1000 Stream.filter((stored) => stored.sequence > Math.max(highWater, afterSequence)),
1001 Stream.filter(matches),
1002 );
1003 return Stream.concat(replay(highWater), live);
1004 }),
1005 );
1006 };
1007
1008 const commitThenPublish = <A, E, R>(
1009 transaction: Effect.Effect<A, E, R>,
1010 publish: (committed: A) => Effect.Effect<void>,
1011 ) =>
1012 Effect.flatMap(CurrentProviderBatch, (batch) =>
1013 batch === undefined
1014 ? Effect.flatMap(Effect.serviceOption(sql.transactionService), (existing) =>
1015 Option.isSome(existing)
1016 ? commitThenPublishNow(transaction, publish)
1017 : coordinator.barrier(commitThenPublishNow(transaction, publish)),
1018 )
1019 : transaction.pipe(
1020 Effect.tap((committed) =>
1021 Effect.sync(() => {
1022 batch.publish.push(publish(committed));
1023 }),
1024 ),
1025 ),
1026 );
1027
1028 const withProviderBatch: EventSinkV2Shape["withProviderBatch"] = Effect.fn(
1029 "orchestrationV2.EventSink.providerBatch",
1030 )(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
1031 if ((yield* CurrentProviderBatch) !== undefined) return yield* effect;
1032 const batch: ProviderBatchPublication = { publish: [], eventCount: 0 };
1033 let started = false;
1034 const result = yield* commitThenPublishNow(
1035 Effect.sync(() => {
1036 started = true;
1037 }).pipe(Effect.andThen(Effect.provideService(effect, CurrentProviderBatch, batch))),
1038 () => Effect.forEach(batch.publish, (publish) => publish, { discard: true }),
1039 ).pipe(
1040 // Normalization mutates run-local state, so only retry before its transaction body starts.
1041 Effect.retry({
1042 while: (cause) =>
1043 !started && SqlError.isSqlError(cause) && cause.reason._tag === "LockTimeoutError",
1044 times: 2,
1045 }),
1046 Effect.mapError((cause) =>
1047 SqlError.isSqlError(cause)
1048 ? new EventSinkWriteError({ eventCount: batch.eventCount, cause })
1049 : cause,
1050 ),
1051 );
1052 yield* Effect.annotateCurrentSpan({
1053 "orchestration_v2.event_count": batch.eventCount,
1054 "orchestration_v2.batch_writes": batch.publish.length,
1055 });
1056 return result;
1057 });
1058
1059 const coordinator = yield* ProviderCommitBatch.make(
1060 (work) =>
1061 withProviderBatch(work).pipe(
1062 Effect.mapError((cause) =>
1063 ProviderCommitBatch.isCommitBatchError(cause)
1064 ? cause
1065 : new ProviderCommitBatch.CommitBatchError({ cause }),
1066 ),
1067 ),
1068 yield* ProviderCommitBatch.enabled,
1069 // Each snapshot owns a savepoint and its deferred publications within the shared commit.
1070 Effect.fnUntraced(function* (
1071 work: Effect.Effect<void, ProviderCommitBatch.CommitBatchError>,
1072 ) {
1073 const batch = yield* CurrentProviderBatch;
1074 const publicationCount = batch?.publish.length ?? 0;
1075 const eventCount = batch?.eventCount ?? 0;
1076 return yield* sql.withTransaction(work).pipe(
1077 Effect.onError(() =>
1078 Effect.sync(() => {
1079 if (batch !== undefined) {
1080 batch.publish.length = publicationCount;
1081 batch.eventCount = eventCount;
1082 }
1083 }),
1084 ),
1085 Effect.mapError((cause) =>
1086 ProviderCommitBatch.isCommitBatchError(cause)
1087 ? cause
1088 : new ProviderCommitBatch.CommitBatchError({ cause }),
1089 ),
1090 );
1091 }),
1092 );
1093
1094 return EventSinkV2.of({
1095 consumeProviderEvents: coordinator.consume,
1096 withProviderBatch,
1097 write: (input) =>
1098 writeEffect({ ...input, effects: [] }).pipe(
1099 Effect.mapError(
1100 (cause) =>
1101 new EventSinkWriteError({
1102 eventCount: input.events.length,
1103 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
1104 cause,
1105 }),
1106 ),
1107 ),
1108 writeWithEffects: (input) =>
1109 writeEffect(input).pipe(
1110 Effect.mapError(
1111 (cause) =>
1112 new EventSinkWriteError({
1113 eventCount: input.events.length,
1114 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
1115 cause,
1116 }),
1117 ),
1118 ),
1119 writeIfRunCurrent: (input) =>
1120 writeIfRunCurrentEffect(input).pipe(
1121 Effect.mapError(
1122 (cause) =>
1123 new EventSinkWriteError({
1124 eventCount: input.events.length,
1125 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
1126 cause,
1127 }),
1128 ),
1129 ),
1130 writeIfProviderThreadOwner: (input) =>
1131 writeIfProviderThreadOwnerEffect(input).pipe(
1132 Effect.mapError(
1133 (cause) =>
1134 new EventSinkWriteError({
1135 eventCount: input.events.length,
1136 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
1137 cause,
1138 }),
1139 ),
1140 ),
1141 writeIfProviderThreadUnchanged: (input) =>
1142 writeIfProviderThreadUnchangedEffect(input).pipe(
1143 Effect.mapError(
1144 (cause) => new EventSinkWriteError({ eventCount: input.events.length, cause }),
1145 ),
1146 ),
1147 writeIfTurnItemUnchanged: (input) =>
1148 writeIfTurnItemUnchangedEffect(input).pipe(
1149 Effect.mapError(
1150 (cause) => new EventSinkWriteError({ eventCount: input.events.length, cause }),
1151 ),
1152 ),
1153 writeIfSubagentUnchanged: (input) =>
1154 writeIfSubagentUnchangedEffect(input).pipe(
1155 Effect.mapError(
1156 (cause) => new EventSinkWriteError({ eventCount: input.events.length, cause }),
1157 ),
1158 ),
1159 commitCommand: (input) =>
1160 commitCommandEffect(input).pipe(
1161 Effect.mapError(
1162 (cause) =>
1163 new EventSinkWriteError({
1164 commandId: input.commandId,
1165 eventCount: input.events.length,
1166 cause,
1167 }),
1168 ),
1169 ),
1170 commitRejectedCommand: (input) =>
1171 commitRejectedCommandEffect(input).pipe(
1172 Effect.mapError(
1173 (cause) =>
1174 new EventSinkWriteError({
1175 commandId: input.commandId,
1176 eventCount: 0,
1177 cause,
1178 }),
1179 ),
1180 ),
1181 commitProjectCommand: (input) =>
1182 commitProjectCommandEffect(input).pipe(
1183 Effect.mapError(
1184 (cause) =>
1185 new EventSinkWriteError({ commandId: input.commandId, eventCount: 1, cause }),
1186 ),
1187 ),
1188 commitRejectedProjectCommand: (input) =>
1189 commitRejectedProjectCommandEffect(input).pipe(
1190 Effect.mapError(
1191 (cause) =>
1192 new EventSinkWriteError({ commandId: input.commandId, eventCount: 0, cause }),
1193 ),
1194 ),
1195 stream: (input) =>
1196 stream(input).pipe(
1197 Stream.mapError(
1198 (cause) =>
1199 new EventSinkStreamError({
1200 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
1201 ...(input?.afterSequence === undefined
1202 ? {}
1203 : { afterSequence: input.afterSequence }),
1204 cause,
1205 }),
1206 ),
1207 ),
1208 latestSequence: (input) =>
1209 eventStore.latestSequence(input).pipe(
1210 Effect.mapError(
1211 (cause) =>
1212 new EventSinkStreamError({
1213 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
1214 cause,
1215 }),
1216 ),
1217 ),
1218 readByCommandId: (input) =>
1219 eventStore.readByCommandId(input).pipe(
1220 Stream.mapError(
1221 (cause) =>
1222 new EventSinkStreamError({
1223 cause,
1224 }),
1225 ),
1226 ),
1227 } satisfies EventSinkV2Shape);
1228 }),
1229);
1230
1231/** Share the worker's outbox instance: enqueue wakeups are in-memory. */
1232export const layerFromStores = layerBase;
1233
1234export const layer: Layer.Layer<
1235 EventSinkV2,
1236 never,
1237 EventStore.EventStoreV2 | ProjectionStore.ProjectionStoreV2 | SqlClient.SqlClient
1238> = layerBase.pipe(
1239 Layer.provide(
1240 Layer.mergeAll(
1241 CommandReceiptStore.layer,
1242 EffectOutbox.layer,
1243 ProjectStore.layer,
1244 TurnItemPositionStore.layer,
1245 ),
1246 ),
1247);