Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderCommandReactor.ts

692 lines24.4 KB

1import {
2 type ChatAttachment,
3 CommandId,
4 EventId,
5 type OrchestrationEvent,
6 type ProviderModelOptions,
7 type ProviderKind,
8 type OrchestrationSession,
9 ThreadId,
10 type ProviderSession,
11 type RuntimeMode,
12 type TurnId,
13} from "@t3tools/contracts";
14import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Schema, Stream } from "effect";
15​
16import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
17import { GitCore } from "../../git/Services/GitCore.ts";
18import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
19import { TextGeneration } from "../../git/Services/TextGeneration.ts";
20import { ProviderService } from "../../provider/Services/ProviderService.ts";
21import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
22import {
23 ProviderCommandReactor,
24 type ProviderCommandReactorShape,
25} from "../Services/ProviderCommandReactor.ts";
26​
27type ProviderIntentEvent = Extract<
28 OrchestrationEvent,
29 {
30 type:
31 | "thread.runtime-mode-set"
32 | "thread.turn-start-requested"
33 | "thread.turn-interrupt-requested"
34 | "thread.approval-response-requested"
35 | "thread.user-input-response-requested"
36 | "thread.session-stop-requested";
37 }
38>;
39​
40function toNonEmptyProviderInput(value: string | undefined): string | undefined {
41 const normalized = value?.trim();
42 return normalized && normalized.length > 0 ? normalized : undefined;
44​
45function mapProviderSessionStatusToOrchestrationStatus(
46 status: "connecting" | "ready" | "running" | "error" | "closed",
47): OrchestrationSession["status"] {
48 switch (status) {
49 case "connecting":
50 return "starting";
51 case "running":
52 return "running";
53 case "error":
54 return "error";
55 case "closed":
56 return "stopped";
57 case "ready":
58 default:
59 return "ready";
60 }
62​
63const turnStartKeyForEvent = (event: ProviderIntentEvent): string =>
64 event.commandId !== null ? `command:${event.commandId}` : `event:${event.eventId}`;
65​
66const serverCommandId = (tag: string): CommandId =>
67 CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
68​
69const HANDLED_TURN_START_KEY_MAX = 10_000;
70const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
71const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
72const WORKTREE_BRANCH_PREFIX = "t3code";
73const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
74​
75function toErrorMessage(error: unknown): string {
76 if (error instanceof Error && error.message.trim().length > 0) {
77 return error.message;
78 }
79 try {
80 return JSON.stringify(error);
81 } catch {
82 return String(error);
83 }
85​
86function isUnknownPendingApprovalRequestError(error: unknown): boolean {
87 if (Schema.is(ProviderAdapterRequestError)(error)) {
88 const detail = error.detail.toLowerCase();
89 return (
90 detail.includes("unknown pending approval request") ||
91 detail.includes("unknown pending permission request")
92 );
93 }
94 const message = toErrorMessage(error).toLowerCase();
95 return (
96 message.includes("unknown pending approval request") ||
97 message.includes("unknown pending permission request")
98 );
100​
101function isTemporaryWorktreeBranch(branch: string): boolean {
102 return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
104​
105function buildGeneratedWorktreeBranchName(raw: string): string {
106 const normalized = raw
107 .trim()
108 .toLowerCase()
109 .replace(/^refs\/heads\//, "")
110 .replace(/['"`]/g, "");
111​
112 const withoutPrefix = normalized.startsWith(`${WORKTREE_BRANCH_PREFIX}/`)
113 ? normalized.slice(`${WORKTREE_BRANCH_PREFIX}/`.length)
114 : normalized;
115​
116 const branchFragment = withoutPrefix
117 .replace(/[^a-z0-9/_-]+/g, "-")
118 .replace(/\/+/g, "/")
119 .replace(/-+/g, "-")
120 .replace(/^[./_-]+|[./_-]+$/g, "")
121 .slice(0, 64)
122 .replace(/[./_-]+$/g, "");
123​
124 const safeFragment = branchFragment.length > 0 ? branchFragment : "update";
125 return `${WORKTREE_BRANCH_PREFIX}/${safeFragment}`;
127​
128const make = Effect.gen(function* () {
129 const orchestrationEngine = yield* OrchestrationEngineService;
130 const providerService = yield* ProviderService;
131 const git = yield* GitCore;
132 const textGeneration = yield* TextGeneration;
133 const handledTurnStartKeys = yield* Cache.make<string, true>({
134 capacity: HANDLED_TURN_START_KEY_MAX,
135 timeToLive: HANDLED_TURN_START_KEY_TTL,
136 lookup: () => Effect.succeed(true),
137 });
138​
139 const hasHandledTurnStartRecently = (key: string) =>
140 Cache.getOption(handledTurnStartKeys, key).pipe(
141 Effect.flatMap((cached) =>
142 Cache.set(handledTurnStartKeys, key, true).pipe(Effect.as(Option.isSome(cached))),
143 ),
144 );
145​
146 const appendProviderFailureActivity = (input: {
147 readonly threadId: ThreadId;
148 readonly kind:
149 | "provider.turn.start.failed"
150 | "provider.turn.interrupt.failed"
151 | "provider.approval.respond.failed"
152 | "provider.user-input.respond.failed"
153 | "provider.session.stop.failed";
154 readonly summary: string;
155 readonly detail: string;
156 readonly turnId: TurnId | null;
157 readonly createdAt: string;
158 readonly requestId?: string;
159 }) =>
160 orchestrationEngine.dispatch({
161 type: "thread.activity.append",
162 commandId: serverCommandId("provider-failure-activity"),
163 threadId: input.threadId,
164 activity: {
165 id: EventId.makeUnsafe(crypto.randomUUID()),
166 tone: "error",
167 kind: input.kind,
168 summary: input.summary,
169 payload: {
170 detail: input.detail,
171 ...(input.requestId ? { requestId: input.requestId } : {}),
172 },
173 turnId: input.turnId,
174 createdAt: input.createdAt,
175 },
176 createdAt: input.createdAt,
177 });
178​
179 const setThreadSession = (input: {
180 readonly threadId: ThreadId;
181 readonly session: OrchestrationSession;
182 readonly createdAt: string;
183 }) =>
184 orchestrationEngine.dispatch({
185 type: "thread.session.set",
186 commandId: serverCommandId("provider-session-set"),
187 threadId: input.threadId,
188 session: input.session,
189 createdAt: input.createdAt,
190 });
191​
192 const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
193 const readModel = yield* orchestrationEngine.getReadModel();
194 return readModel.threads.find((entry) => entry.id === threadId);
195 });
196​
197 const ensureSessionForThread = Effect.fnUntraced(function* (
198 threadId: ThreadId,
199 createdAt: string,
200 options?: {
201 readonly provider?: ProviderKind;
202 readonly model?: string;
203 readonly modelOptions?: ProviderModelOptions;
204 },
205 ) {
206 const readModel = yield* orchestrationEngine.getReadModel();
207 const thread = readModel.threads.find((entry) => entry.id === threadId);
208 if (!thread) {
209 return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
210 }
211​
212 const desiredRuntimeMode = thread.runtimeMode;
213 const currentProvider: ProviderKind | undefined =
214 thread.session?.providerName === "codex" ||
215 thread.session?.providerName === "claudeCode" ||
216 thread.session?.providerName === "cursor"
217 ? thread.session.providerName
218 : undefined;
219 const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
220 const desiredModel = options?.model ?? thread.model;
221 const effectiveCwd = resolveThreadWorkspaceCwd({
222 thread,
223 projects: readModel.projects,
224 });
225​
226 const resolveActiveSession = (threadId: ThreadId) =>
227 providerService.listSessions().pipe(
228 Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)),
229 );
230​
231 const startProviderSession = (input?: {
232 readonly resumeCursor?: unknown;
233 readonly provider?: ProviderKind;
234 }) =>
235 providerService.startSession(threadId, {
236 threadId,
237 ...(input?.provider ?? preferredProvider
238 ? { provider: input?.provider ?? preferredProvider }
239 : {}),
240 ...(effectiveCwd ? { cwd: effectiveCwd } : {}),
241 ...(desiredModel ? { model: desiredModel } : {}),
242 ...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
243 ...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
244 runtimeMode: desiredRuntimeMode,
245 });
246​
247 const bindSessionToThread = (session: ProviderSession) =>
248 setThreadSession({
249 threadId,
250 session: {
251 threadId,
252 status: mapProviderSessionStatusToOrchestrationStatus(session.status),
253 providerName: session.provider,
254 runtimeMode: desiredRuntimeMode,
255 // Provider turn ids are not orchestration turn ids.
256 activeTurnId: null,
257 lastError: session.lastError ?? null,
258 updatedAt: session.updatedAt,
259 },
260 createdAt,
261 });
262​
263 const existingSessionThreadId =
264 thread.session && thread.session.status !== "stopped" ? thread.id : null;
265 if (existingSessionThreadId) {
266 const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
267 const providerChanged = options?.provider !== undefined && options.provider !== currentProvider;
268 const activeSession = yield* resolveActiveSession(existingSessionThreadId);
269 const sessionModelSwitch =
270 currentProvider === undefined
271 ? "in-session"
272 : (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
273 const modelChanged =
274 options?.model !== undefined && options.model !== activeSession?.model;
275 const shouldRestartForModelChange =
276 modelChanged && sessionModelSwitch === "restart-session";
277​
278 if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
279 return existingSessionThreadId;
280 }
281​
282 const resumeCursor =
283 providerChanged || shouldRestartForModelChange
284 ? undefined
285 : (activeSession?.resumeCursor ?? undefined);
286 yield* Effect.logInfo("provider command reactor restarting provider session", {
287 threadId,
288 existingSessionThreadId,
289 currentProvider,
290 desiredProvider: options?.provider ?? currentProvider,
291 currentRuntimeMode: thread.session?.runtimeMode,
292 desiredRuntimeMode: thread.runtimeMode,
293 runtimeModeChanged,
294 providerChanged,
295 modelChanged,
296 shouldRestartForModelChange,
297 hasResumeCursor: resumeCursor !== undefined,
298 });
299 const restartedSession = yield* startProviderSession({
300 ...(resumeCursor !== undefined ? { resumeCursor } : {}),
301 ...(options?.provider !== undefined ? { provider: options.provider } : {}),
302 });
303 yield* Effect.logInfo("provider command reactor restarted provider session", {
304 threadId,
305 previousSessionId: existingSessionThreadId,
306 restartedSessionThreadId: restartedSession.threadId,
307 provider: restartedSession.provider,
308 runtimeMode: restartedSession.runtimeMode,
309 });
310 yield* bindSessionToThread(restartedSession);
311 return restartedSession.threadId;
312 }
313​
314 const startedSession = yield* startProviderSession(
315 options?.provider !== undefined ? { provider: options.provider } : undefined,
316 );
317 yield* bindSessionToThread(startedSession);
318 return startedSession.threadId;
319 });
320​
321 const sendTurnForThread = Effect.fnUntraced(function* (input: {
322 readonly threadId: ThreadId;
323 readonly messageText: string;
324 readonly attachments?: ReadonlyArray<ChatAttachment>;
325 readonly provider?: ProviderKind;
326 readonly model?: string;
327 readonly modelOptions?: ProviderModelOptions;
328 readonly interactionMode?: "default" | "plan";
329 readonly createdAt: string;
330 }) {
331 const thread = yield* resolveThread(input.threadId);
332 if (!thread) {
333 return;
334 }
335 yield* ensureSessionForThread(input.threadId, input.createdAt, {
336 ...(input.provider !== undefined ? { provider: input.provider } : {}),
337 ...(input.model !== undefined ? { model: input.model } : {}),
338 ...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
339 });
340 const normalizedInput = toNonEmptyProviderInput(input.messageText);
341 const normalizedAttachments = input.attachments ?? [];
342 const activeSession = yield* providerService.listSessions().pipe(
343 Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),
344 );
345 const sessionModelSwitch =
346 activeSession === undefined
347 ? "in-session"
348 : (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
349 const modelForTurn =
350 sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
351​
352 yield* providerService.sendTurn({
353 threadId: input.threadId,
354 ...(normalizedInput ? { input: normalizedInput } : {}),
355 ...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
356 ...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
357 ...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
358 ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
359 });
360 });
361​
362 const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fnUntraced(function* (input: {
363 readonly threadId: ThreadId;
364 readonly branch: string | null;
365 readonly worktreePath: string | null;
366 readonly messageId: string;
367 readonly messageText: string;
368 readonly attachments?: ReadonlyArray<ChatAttachment>;
369 }) {
370 if (!input.branch || !input.worktreePath) {
371 return;
372 }
373 if (!isTemporaryWorktreeBranch(input.branch)) {
374 return;
375 }
376​
377 const thread = yield* resolveThread(input.threadId);
378 if (!thread) {
379 return;
380 }
381​
382 const userMessages = thread.messages.filter((message) => message.role === "user");
383 if (userMessages.length !== 1 || userMessages[0]?.id !== input.messageId) {
384 return;
385 }
386​
387 const oldBranch = input.branch;
388 const cwd = input.worktreePath;
389 const attachments = input.attachments ?? [];
390 yield* textGeneration
391 .generateBranchName({
392 cwd,
393 message: input.messageText,
394 ...(attachments.length > 0 ? { attachments } : {}),
395 })
396 .pipe(
397 Effect.catch((error) =>
398 Effect.logWarning(
399 "provider command reactor failed to generate worktree branch name; skipping rename",
400 { threadId: input.threadId, cwd, oldBranch, reason: error.message },
401 ),
402 ),
403 Effect.flatMap((generated) => {
404 if (!generated) return Effect.void;
405​
406 const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
407 if (targetBranch === oldBranch) return Effect.void;
408​
409 return Effect.flatMap(
410 git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
411 (renamed) =>
412 orchestrationEngine.dispatch({
413 type: "thread.meta.update",
414 commandId: serverCommandId("worktree-branch-rename"),
415 threadId: input.threadId,
416 branch: renamed.branch,
417 worktreePath: cwd,
418 }),
419 );
420 }),
421 Effect.catchCause((cause) =>
422 Effect.logWarning(
423 "provider command reactor failed to generate or rename worktree branch",
424 { threadId: input.threadId, cwd, oldBranch, cause: Cause.pretty(cause) },
425 ),
426 ),
427 );
428 });
429​
430 const processTurnStartRequested = Effect.fnUntraced(function* (
431 event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
432 ) {
433 const key = turnStartKeyForEvent(event);
434 if (yield* hasHandledTurnStartRecently(key)) {
435 return;
436 }
437​
438 const thread = yield* resolveThread(event.payload.threadId);
439 if (!thread) {
440 return;
441 }
442​
443 const message = thread.messages.find((entry) => entry.id === event.payload.messageId);
444 if (!message || message.role !== "user") {
445 yield* appendProviderFailureActivity({
446 threadId: event.payload.threadId,
447 kind: "provider.turn.start.failed",
448 summary: "Provider turn start failed",
449 detail: `User message '${event.payload.messageId}' was not found for turn start request.`,
450 turnId: null,
451 createdAt: event.payload.createdAt,
452 });
453 return;
454 }
455​
456 yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
457 threadId: event.payload.threadId,
458 branch: thread.branch,
459 worktreePath: thread.worktreePath,
460 messageId: message.id,
461 messageText: message.text,
462 ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
463 }).pipe(Effect.forkScoped);
464​
465 yield* sendTurnForThread({
466 threadId: event.payload.threadId,
467 messageText: message.text,
468 ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
469 ...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
470 ...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
471 ...(event.payload.modelOptions !== undefined ? { modelOptions: event.payload.modelOptions } : {}),
472 interactionMode: event.payload.interactionMode,
473 createdAt: event.payload.createdAt,
474 });
475 });
476​
477 const processTurnInterruptRequested = Effect.fnUntraced(function* (
478 event: Extract<ProviderIntentEvent, { type: "thread.turn-interrupt-requested" }>,
479 ) {
480 const thread = yield* resolveThread(event.payload.threadId);
481 if (!thread) {
482 return;
483 }
484 const hasSession = thread.session && thread.session.status !== "stopped";
485 if (!hasSession) {
486 return yield* appendProviderFailureActivity({
487 threadId: event.payload.threadId,
488 kind: "provider.turn.interrupt.failed",
489 summary: "Provider turn interrupt failed",
490 detail: "No active provider session is bound to this thread.",
491 turnId: event.payload.turnId ?? null,
492 createdAt: event.payload.createdAt,
493 });
494 }
495​
496 // Orchestration turn ids are not provider turn ids, so interrupt by session.
497 yield* providerService.interruptTurn({ threadId: event.payload.threadId });
498 });
499​
500 const processApprovalResponseRequested = Effect.fnUntraced(function* (
501 event: Extract<ProviderIntentEvent, { type: "thread.approval-response-requested" }>,
502 ) {
503 const thread = yield* resolveThread(event.payload.threadId);
504 if (!thread) {
505 return;
506 }
507 const hasSession = thread.session && thread.session.status !== "stopped";
508 if (!hasSession) {
509 return yield* appendProviderFailureActivity({
510 threadId: event.payload.threadId,
511 kind: "provider.approval.respond.failed",
512 summary: "Provider approval response failed",
513 detail: "No active provider session is bound to this thread.",
514 turnId: null,
515 createdAt: event.payload.createdAt,
516 requestId: event.payload.requestId,
517 });
518 }
519​
520 yield* providerService
521 .respondToRequest({
522 threadId: event.payload.threadId,
523 requestId: event.payload.requestId,
524 decision: event.payload.decision,
525 })
526 .pipe(
527 Effect.catchCause((cause) =>
528 Effect.gen(function* () {
529 const error = Cause.squash(cause);
530 const detail = toErrorMessage(error);
531 yield* appendProviderFailureActivity({
532 threadId: event.payload.threadId,
533 kind: "provider.approval.respond.failed",
534 summary: "Provider approval response failed",
535 detail,
536 turnId: null,
537 createdAt: event.payload.createdAt,
538 requestId: event.payload.requestId,
539 });
540​
541 if (!isUnknownPendingApprovalRequestError(error)) return;
542 }),
543 ),
544 );
545 });
546​
547 const processUserInputResponseRequested = Effect.fnUntraced(function* (
548 event: Extract<ProviderIntentEvent, { type: "thread.user-input-response-requested" }>,
549 ) {
550 const thread = yield* resolveThread(event.payload.threadId);
551 if (!thread) {
552 return;
553 }
554 const hasSession = thread.session && thread.session.status !== "stopped";
555 if (!hasSession) {
556 return yield* appendProviderFailureActivity({
557 threadId: event.payload.threadId,
558 kind: "provider.user-input.respond.failed",
559 summary: "Provider user input response failed",
560 detail: "No active provider session is bound to this thread.",
561 turnId: null,
562 createdAt: event.payload.createdAt,
563 requestId: event.payload.requestId,
564 });
565 }
566​
567 yield* providerService
568 .respondToUserInput({
569 threadId: event.payload.threadId,
570 requestId: event.payload.requestId,
571 answers: event.payload.answers,
572 })
573 .pipe(
574 Effect.catchCause((cause) =>
575 Effect.gen(function* () {
576 const error = Cause.squash(cause);
577 yield* appendProviderFailureActivity({
578 threadId: event.payload.threadId,
579 kind: "provider.user-input.respond.failed",
580 summary: "Provider user input response failed",
581 detail: toErrorMessage(error),
582 turnId: null,
583 createdAt: event.payload.createdAt,
584 requestId: event.payload.requestId,
585 });
586 }),
587 ),
588 );
589 });
590​
591 const processSessionStopRequested = Effect.fnUntraced(function* (
592 event: Extract<ProviderIntentEvent, { type: "thread.session-stop-requested" }>,
593 ) {
594 const thread = yield* resolveThread(event.payload.threadId);
595 if (!thread) {
596 return;
597 }
598​
599 const now = event.payload.createdAt;
600 if (thread.session && thread.session.status !== "stopped") {
601 yield* providerService.stopSession({ threadId: thread.id });
602 }
603​
604 yield* setThreadSession({
605 threadId: thread.id,
606 session: {
607 threadId: thread.id,
608 status: "stopped",
609 providerName: thread.session?.providerName ?? null,
610 runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
611 activeTurnId: null,
612 lastError: thread.session?.lastError ?? null,
613 updatedAt: now,
614 },
615 createdAt: now,
616 });
617 });
618​
619 const processDomainEvent = (event: ProviderIntentEvent) =>
620 Effect.gen(function* () {
621 switch (event.type) {
622 case "thread.runtime-mode-set": {
623 const thread = yield* resolveThread(event.payload.threadId);
624 if (!thread?.session || thread.session.status === "stopped") {
625 return;
626 }
627 yield* ensureSessionForThread(event.payload.threadId, event.occurredAt);
628 return;
629 }
630 case "thread.turn-start-requested":
631 yield* processTurnStartRequested(event);
632 return;
633 case "thread.turn-interrupt-requested":
634 yield* processTurnInterruptRequested(event);
635 return;
636 case "thread.approval-response-requested":
637 yield* processApprovalResponseRequested(event);
638 return;
639 case "thread.user-input-response-requested":
640 yield* processUserInputResponseRequested(event);
641 return;
642 case "thread.session-stop-requested":
643 yield* processSessionStopRequested(event);
644 return;
645 }
646 });
647​
648 const processDomainEventSafely = (event: ProviderIntentEvent) =>
649 processDomainEvent(event).pipe(
650 Effect.catchCause((cause) => {
651 if (Cause.hasInterruptsOnly(cause)) {
652 return Effect.failCause(cause);
653 }
654 return Effect.logWarning("provider command reactor failed to process event", {
655 eventType: event.type,
656 cause: Cause.pretty(cause),
657 });
658 }),
659 );
660​
661 const start: ProviderCommandReactorShape["start"] = Effect.gen(function* () {
662 const queue = yield* Queue.unbounded<ProviderIntentEvent>();
663 yield* Effect.addFinalizer(() => Queue.shutdown(queue).pipe(Effect.asVoid));
664​
665 yield* Effect.forkScoped(
666 Effect.forever(Queue.take(queue).pipe(Effect.flatMap(processDomainEventSafely))),
667 );
668​
669 yield* Effect.forkScoped(
670 Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
671 if (
672 event.type !== "thread.runtime-mode-set" &&
673 event.type !== "thread.turn-start-requested" &&
674 event.type !== "thread.turn-interrupt-requested" &&
675 event.type !== "thread.approval-response-requested" &&
676 event.type !== "thread.user-input-response-requested" &&
677 event.type !== "thread.session-stop-requested"
678 ) {
679 return Effect.void;
680 }
681​
682 return Queue.offer(queue, event).pipe(Effect.asVoid);
683 }),
684 );
685 });
686​
687 return {
688 start,
689 } satisfies ProviderCommandReactorShape;
690});
691​
692export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make);