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