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