diff --git a/apps/server/src/orchestration/Layer.ts b/apps/server/src/orchestration/Layer.ts index 1edacd925c..6cd70f9511 100644 --- a/apps/server/src/orchestration/Layer.ts +++ b/apps/server/src/orchestration/Layer.ts @@ -4,7 +4,7 @@ import type { OrchestrationReadModel, } from "@t3tools/contracts"; import { OrchestrationCommandSchema } from "@t3tools/contracts"; -import { Deferred, Effect, Layer, PubSub, Queue, Schema } from "effect"; +import { Deferred, Effect, Layer, Queue, Schema } from "effect"; import { createLogger } from "../logger.ts"; import { OrchestrationEventRepository } from "../persistence/Services/OrchestrationEvents.ts"; @@ -20,6 +20,7 @@ import { OrchestrationEngineService, type OrchestrationEngineShape } from "./Ser interface CommandEnvelope { command: OrchestrationCommand; result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>; + transient?: boolean | undefined; } function mapCommandToEvent(command: OrchestrationCommand): Omit { @@ -169,8 +170,6 @@ const makeOrchestrationEngine = Effect.gen(function* () { let readModel = createEmptyReadModel(new Date().toISOString()); const commandQueue = yield* Queue.unbounded(); - const readModelPubSub = yield* PubSub.unbounded(); - const eventPubSub = yield* PubSub.unbounded(); const readModelListeners = new Set<(snapshot: OrchestrationReadModel) => void>(); const domainEventListeners = new Set<(event: OrchestrationEvent) => void>(); @@ -194,19 +193,28 @@ const makeOrchestrationEngine = Effect.gen(function* () { const processEnvelope = (envelope: CommandEnvelope): Effect.Effect => Effect.gen(function* () { const eventBase = mapCommandToEvent(envelope.command); - const savedEvent = yield* eventStore.append(eventBase); + + let savedEvent: OrchestrationEvent; + if (envelope.transient) { + savedEvent = { ...eventBase, sequence: readModel.sequence }; + } else { + savedEvent = yield* eventStore.append(eventBase); + } readModel = yield* reduceEvent(readModel, savedEvent); - const snapshot = readModel; - yield* Effect.all([ - PubSub.publish(eventPubSub, savedEvent), - PubSub.publish(readModelPubSub, snapshot), - ]); - - yield* notifyDomainEventListeners(savedEvent); - yield* notifyReadModelListeners(snapshot); - yield* Deferred.succeed(envelope.result, { sequence: savedEvent.sequence }); + + const snapshot = readModel; + yield* notifyDomainEventListeners(savedEvent).pipe( + Effect.catch((error) => + Effect.sync(() => logger.warn("domain event listener failed", { error: String(error) })), + ), + ); + yield* notifyReadModelListeners(snapshot).pipe( + Effect.catch((error) => + Effect.sync(() => logger.warn("read model listener failed", { error: String(error) })), + ), + ); }).pipe(Effect.catch((error) => Deferred.fail(envelope.result, error).pipe(Effect.asVoid))); const bootstrapReadModel: Effect.Effect = Effect.gen( @@ -232,10 +240,10 @@ const makeOrchestrationEngine = Effect.gen(function* () { const replayEvents: OrchestrationEngineShape["replayEvents"] = (fromSequenceExclusive) => eventStore.readFromSequence(fromSequenceExclusive); - const dispatch: OrchestrationEngineShape["dispatch"] = (command) => + const dispatch: OrchestrationEngineShape["dispatch"] = (command, options) => Effect.gen(function* () { const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>(); - yield* Queue.offer(commandQueue, { command, result }); + yield* Queue.offer(commandQueue, { command, result, transient: options?.transient }); return yield* Deferred.await(result); }); diff --git a/apps/server/src/orchestration/Service.ts b/apps/server/src/orchestration/Service.ts index 1dadacce97..db5fdb436e 100644 --- a/apps/server/src/orchestration/Service.ts +++ b/apps/server/src/orchestration/Service.ts @@ -51,10 +51,12 @@ export interface OrchestrationEngineShape { * Dispatch a validated orchestration command. * * @param command - Valid orchestration command. + * @param options - Optional dispatch options. Set `transient` to skip persistence. * @returns Effect containing the sequence of the persisted event. */ readonly dispatch: ( command: OrchestrationCommand, + options?: { transient?: boolean | undefined } | undefined, ) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError>; /** diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts index d9fde1cb73..70c0bcf022 100644 --- a/apps/server/src/wsServer.ts +++ b/apps/server/src/wsServer.ts @@ -250,20 +250,29 @@ export function createServer(options: ServerOptions) { if (event.textDelta && event.textDelta.length > 0) { const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`; await runtime.runPromise( - liveOrchestrationEngine.dispatch({ - type: "message.send", - commandId: crypto.randomUUID(), - threadId: thread.id, - messageId: assistantMessageId, - role: "assistant", - text: event.textDelta, - streaming: true, - createdAt: now, - }), + liveOrchestrationEngine.dispatch( + { + type: "message.send", + commandId: crypto.randomUUID(), + threadId: thread.id, + messageId: assistantMessageId, + role: "assistant", + text: event.textDelta, + streaming: true, + createdAt: now, + }, + { transient: true }, + ), ); } if (event.method === "turn/completed") { const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`; + const latestSnapshot = await runtime.runPromise(liveOrchestrationEngine.getSnapshot()); + const latestThread = latestSnapshot.threads.find( + (entry) => entry.session?.sessionId === event.sessionId, + ); + const existingMessage = latestThread?.messages.find((m) => m.id === assistantMessageId); + const accumulatedText = existingMessage?.text ?? ""; await runtime.runPromise( liveOrchestrationEngine.dispatch({ type: "message.send", @@ -271,7 +280,7 @@ export function createServer(options: ServerOptions) { threadId: thread.id, messageId: assistantMessageId, role: "assistant", - text: "", + text: accumulatedText, streaming: false, createdAt: now, }),