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

ProviderCommandReactor.ts

1,132 lines41.0 KB

1import {
2 type ChatAttachment,
3 CommandId,
4 EventId,
5 type ModelSelection,
6 type OrchestrationEvent,
7 ProviderDriverKind,
8 type ProjectId,
9 type OrchestrationSession,
10 ThreadId,
11 type ProviderSession,
12 type RuntimeMode,
13 type TurnId,
14} from "@t3tools/contracts";
15import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shared/git";
16import * as Cache from "effect/Cache";
17import * as Cause from "effect/Cause";
18import * as Crypto from "effect/Crypto";
19import * as Duration from "effect/Duration";
20import * as Effect from "effect/Effect";
21import * as Equal from "effect/Equal";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Schema from "effect/Schema";
25import * as Stream from "effect/Stream";
26import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
27​
28import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
29import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
30import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
31import type { ProviderServiceError } from "../../provider/Errors.ts";
32import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
33import { ProviderService } from "../../provider/Services/ProviderService.ts";
34import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
35import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
36import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
37import {
38 ProviderCommandReactor,
39 type ProviderCommandReactorShape,
40} from "../Services/ProviderCommandReactor.ts";
41import { ServerSettingsService } from "../../serverSettings.ts";
42import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
43import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
44const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
45const isProviderDriverKind = Schema.is(ProviderDriverKind);
46​
47type ProviderIntentEvent = Extract<
48 OrchestrationEvent,
49 {
50 type:
51 | "thread.runtime-mode-set"
52 | "thread.turn-start-requested"
53 | "thread.turn-interrupt-requested"
54 | "thread.approval-response-requested"
55 | "thread.user-input-response-requested"
56 | "thread.session-stop-requested"
57 | "thread.task-stop-requested";
58 }
59>;
60​
61function toNonEmptyProviderInput(value: string | undefined): string | undefined {
62 const normalized = value?.trim();
63 return normalized && normalized.length > 0 ? normalized : undefined;
65​
66function mapProviderSessionStatusToOrchestrationStatus(
67 status: "connecting" | "ready" | "running" | "error" | "closed",
68): OrchestrationSession["status"] {
69 switch (status) {
70 case "connecting":
71 return "starting";
72 case "running":
73 return "running";
74 case "error":
75 return "error";
76 case "closed":
77 return "stopped";
78 case "ready":
79 default:
80 return "ready";
81 }
83​
84const turnStartKeyForEvent = (event: ProviderIntentEvent): string =>
85 event.commandId !== null ? `command:${event.commandId}` : `event:${event.eventId}`;
86​
87const HANDLED_TURN_START_KEY_MAX = 10_000;
88const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
89const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
90const DEFAULT_THREAD_TITLE = "New thread";
91​
92export function providerErrorLabel(value: string | undefined): string {
93 const normalized = value?.trim();
94 return normalized && normalized.length > 0 ? normalized : "unknown";
96​
97export function providerErrorLabelFromInstanceHint(input: {
98 readonly instanceId?: string | undefined;
99 readonly modelSelectionInstanceId?: string | undefined;
100 readonly sessionProvider?: string | undefined;
101}): string {
102 return providerErrorLabel(
103 input.instanceId ?? input.modelSelectionInstanceId ?? input.sessionProvider,
104 );
106​
107function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
108 const trimmedCurrentTitle = currentTitle.trim();
109 if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) {
110 return true;
111 }
112​
113 const trimmedTitleSeed = titleSeed?.trim();
114 return trimmedTitleSeed !== undefined && trimmedTitleSeed.length > 0
115 ? trimmedCurrentTitle === trimmedTitleSeed
116 : false;
118​
119function findProviderAdapterRequestError(
120 cause: Cause.Cause<ProviderServiceError>,
121): ProviderAdapterRequestError | undefined {
122 const failReason = cause.reasons.find(Cause.isFailReason);
123 return isProviderAdapterRequestError(failReason?.error) ? failReason.error : undefined;
125​
126function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
127 const error = findProviderAdapterRequestError(cause);
128 if (error) {
129 const detail = error.detail.toLowerCase();
130 return (
131 detail.includes("unknown pending approval request") ||
132 detail.includes("unknown pending permission request")
133 );
134 }
135 const message = Cause.pretty(cause);
136 return (
137 message.includes("unknown pending approval request") ||
138 message.includes("unknown pending permission request")
139 );
141​
142function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
143 const error = findProviderAdapterRequestError(cause);
144 if (error) {
145 const detail = error.detail.toLowerCase();
146 return (
147 detail.includes("unknown pending user-input request") ||
148 detail.includes("unknown pending user input request") ||
149 detail.includes("unknown pending codex user input request")
150 );
151 }
152 const message = Cause.pretty(cause).toLowerCase();
153 return (
154 message.includes("unknown pending user-input request") ||
155 message.includes("unknown pending user input request") ||
156 message.includes("unknown pending codex user input request")
157 );
159​
160function stalePendingRequestDetail(
161 requestKind: "approval" | "user-input",
162 requestId: string,
163): string {
164 return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;
166​
167function buildGeneratedWorktreeBranchName(raw: string): string {
168 const normalized = raw
169 .trim()
170 .toLowerCase()
171 .replace(/^refs\/heads\//, "")
172 .replace(/['"`]/g, "");
173​
174 const withoutPrefix = normalized.startsWith(`${WORKTREE_BRANCH_PREFIX}/`)
175 ? normalized.slice(`${WORKTREE_BRANCH_PREFIX}/`.length)
176 : normalized;
177​
178 const branchFragment = withoutPrefix
179 .replace(/[^a-z0-9/_-]+/g, "-")
180 .replace(/\/+/g, "/")
181 .replace(/-+/g, "-")
182 .replace(/^[./_-]+|[./_-]+$/g, "")
183 .slice(0, 64)
184 .replace(/[./_-]+$/g, "");
185​
186 const safeFragment = branchFragment.length > 0 ? branchFragment : "update";
187 return `${WORKTREE_BRANCH_PREFIX}/${safeFragment}`;
189​
190const make = Effect.gen(function* () {
191 const crypto = yield* Crypto.Crypto;
192 const orchestrationEngine = yield* OrchestrationEngineService;
193 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
194 const providerService = yield* ProviderService;
195 const providerRegistry = yield* ProviderRegistry;
196 const gitWorkflow = yield* GitWorkflowService;
197 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
198 const textGeneration = yield* TextGeneration;
199 const serverSettingsService = yield* ServerSettingsService;
200 const serverCommandId = (tag: string) =>
201 crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
202 const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make));
203 const handledTurnStartKeys = yield* Cache.make<string, true>({
204 capacity: HANDLED_TURN_START_KEY_MAX,
205 timeToLive: HANDLED_TURN_START_KEY_TTL,
206 lookup: () => Effect.succeed(true),
207 });
208​
209 const hasHandledTurnStartRecently = (key: string) =>
210 Cache.getOption(handledTurnStartKeys, key).pipe(
211 Effect.flatMap((cached) =>
212 Cache.set(handledTurnStartKeys, key, true).pipe(Effect.as(Option.isSome(cached))),
213 ),
214 );
215​
216 const threadModelSelections = new Map<string, ModelSelection>();
217​
218 const appendProviderFailureActivity = (input: {
219 readonly threadId: ThreadId;
220 readonly kind:
221 | "provider.turn.start.failed"
222 | "provider.turn.interrupt.failed"
223 | "provider.task.stop.failed"
224 | "provider.approval.respond.failed"
225 | "provider.user-input.respond.failed"
226 | "provider.session.stop.failed";
227 readonly summary: string;
228 readonly detail: string;
229 readonly turnId: TurnId | null;
230 readonly createdAt: string;
231 readonly requestId?: string;
232 }) =>
233 Effect.all({
234 commandId: serverCommandId("provider-failure-activity"),
235 eventId: serverEventId(),
236 }).pipe(
237 Effect.flatMap(({ commandId, eventId }) =>
238 orchestrationEngine.dispatch({
239 type: "thread.activity.append",
240 commandId,
241 threadId: input.threadId,
242 activity: {
243 id: eventId,
244 tone: "error",
245 kind: input.kind,
246 summary: input.summary,
247 payload: {
248 detail: input.detail,
249 ...(input.requestId ? { requestId: input.requestId } : {}),
250 },
251 turnId: input.turnId,
252 createdAt: input.createdAt,
253 },
254 createdAt: input.createdAt,
255 }),
256 ),
257 );
258​
259 const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
260 const failReason = cause.reasons.find(Cause.isFailReason);
261 const providerError = isProviderAdapterRequestError(failReason?.error)
262 ? failReason.error
263 : undefined;
264 if (providerError) {
265 return providerError.detail;
266 }
267 return Cause.pretty(cause);
268 };
269​
270 const setThreadSession = (input: {
271 readonly threadId: ThreadId;
272 readonly session: OrchestrationSession;
273 readonly createdAt: string;
274 }) =>
275 serverCommandId("provider-session-set").pipe(
276 Effect.flatMap((commandId) =>
277 orchestrationEngine.dispatch({
278 type: "thread.session.set",
279 commandId,
280 threadId: input.threadId,
281 session: input.session,
282 createdAt: input.createdAt,
283 }),
284 ),
285 );
286​
287 const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {
288 readonly threadId: ThreadId;
289 readonly detail: string;
290 readonly createdAt: string;
291 }) {
292 const thread = yield* resolveThread(input.threadId);
293 const session = thread?.session;
294 if (!session) {
295 return;
296 }
297 yield* setThreadSession({
298 threadId: input.threadId,
299 session: {
300 ...session,
301 status: session.status === "stopped" ? "stopped" : "ready",
302 activeTurnId: null,
303 lastError: input.detail,
304 updatedAt: input.createdAt,
305 },
306 createdAt: input.createdAt,
307 });
308 });
309​
310 const resolveProject = Effect.fnUntraced(function* (projectId: ProjectId) {
311 return yield* projectionSnapshotQuery
312 .getProjectShellById(projectId)
313 .pipe(Effect.map(Option.getOrUndefined));
314 });
315​
316 const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
317 return yield* projectionSnapshotQuery
318 .getThreadDetailById(threadId)
319 .pipe(Effect.map(Option.getOrUndefined));
320 });
321​
322 const rejectStartedThreadModelChangeIfRequired = Effect.fnUntraced(function* (input: {
323 readonly threadId: ThreadId;
324 readonly currentModelSelection: ModelSelection;
325 readonly requestedModelSelection: ModelSelection | undefined;
326 }) {
327 const requestedModelSelection = input.requestedModelSelection;
328 if (
329 requestedModelSelection === undefined ||
330 (input.currentModelSelection.instanceId === requestedModelSelection.instanceId &&
331 input.currentModelSelection.model === requestedModelSelection.model)
332 ) {
333 return;
334 }
335 const providers = yield* providerRegistry.getProviders;
336 const requiresNewThread =
337 providers.find((snapshot) => snapshot.instanceId === input.currentModelSelection.instanceId)
338 ?.requiresNewThreadForModelChange === true ||
339 providers.find((snapshot) => snapshot.instanceId === requestedModelSelection.instanceId)
340 ?.requiresNewThreadForModelChange === true;
341 if (!requiresNewThread) {
342 return;
343 }
344 return yield* new ProviderAdapterRequestError({
345 provider: providerErrorLabelFromInstanceHint({
346 instanceId: String(requestedModelSelection.instanceId),
347 modelSelectionInstanceId: String(input.currentModelSelection.instanceId),
348 }),
349 method: "thread.turn.start",
350 detail: `Thread '${input.threadId}' cannot switch models after the conversation has started. Start a new thread to use '${requestedModelSelection.model}'.`,
351 });
352 });
353​
354 const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
355 threadId: ThreadId,
356 createdAt: string,
357 options?: {
358 readonly modelSelection?: ModelSelection;
359 },
360 ) {
361 const thread = yield* resolveThread(threadId);
362 if (!thread) {
363 return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
364 }
365​
366 const desiredRuntimeMode = thread.runtimeMode;
367 const requestedModelSelection = options?.modelSelection;
368 const resolveActiveSession = (threadId: ThreadId) =>
369 providerService
370 .listSessions()
371 .pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));
372​
373 const activeSession = yield* resolveActiveSession(threadId);
374 const activeThreadSession =
375 thread.session !== null && thread.session.status !== "stopped" && activeSession
376 ? thread.session
377 : null;
378 if (
379 activeThreadSession !== null &&
380 activeSession !== undefined &&
381 (activeThreadSession.providerInstanceId === undefined ||
382 activeSession.providerInstanceId === undefined)
383 ) {
384 return yield* new ProviderAdapterRequestError({
385 provider: providerErrorLabel(activeThreadSession.providerName ?? undefined),
386 method: "thread.turn.start",
387 detail: `Thread '${threadId}' has an active provider session without a provider instance id.`,
388 });
389 }
390 const currentInstanceId =
391 activeThreadSession !== null &&
392 activeSession !== undefined &&
393 activeSession.providerInstanceId !== undefined
394 ? activeSession.providerInstanceId
395 : thread.modelSelection.instanceId;
396 const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
397 const desiredInstanceId = desiredModelSelection.instanceId;
398 const currentInfo = yield* providerService.getInstanceInfo(currentInstanceId).pipe(
399 Effect.mapError(
400 () =>
401 new ProviderAdapterRequestError({
402 provider: providerErrorLabelFromInstanceHint({
403 instanceId: String(currentInstanceId),
404 modelSelectionInstanceId: String(thread.modelSelection.instanceId),
405 sessionProvider: thread.session?.providerName ?? undefined,
406 }),
407 method: "thread.turn.start",
408 detail: `Thread '${threadId}' references unknown provider instance '${currentInstanceId}'. The instance is not configured in this build.`,
409 }),
410 ),
411 );
412 const desiredInfo = yield* providerService.getInstanceInfo(desiredInstanceId).pipe(
413 Effect.mapError(
414 () =>
415 new ProviderAdapterRequestError({
416 provider: providerErrorLabelFromInstanceHint({
417 instanceId: String(desiredModelSelection.instanceId),
418 }),
419 method: "thread.turn.start",
420 detail: `Requested provider instance '${desiredInstanceId}' is not configured in this build.`,
421 }),
422 ),
423 );
424 const desiredDriverKind = desiredInfo.driverKind;
425 if (!isProviderDriverKind(desiredDriverKind)) {
426 return yield* new ProviderAdapterRequestError({
427 provider: providerErrorLabel(String(desiredDriverKind)),
428 method: "thread.turn.start",
429 detail: `Requested provider instance '${desiredInstanceId}' uses unknown provider driver '${desiredDriverKind}'. The driver is not installed in this build.`,
430 });
431 }
432 const preferredProvider: ProviderDriverKind = desiredDriverKind;
433 if (thread.session !== null) {
434 yield* rejectStartedThreadModelChangeIfRequired({
435 threadId,
436 currentModelSelection:
437 activeSession?.model !== undefined
438 ? {
439 ...thread.modelSelection,
440 instanceId: currentInstanceId,
441 model: activeSession.model,
442 }
443 : thread.modelSelection,
444 requestedModelSelection,
445 });
446 }
447 if (
448 thread.session !== null &&
449 requestedModelSelection !== undefined &&
450 requestedModelSelection.instanceId !== currentInstanceId
451 ) {
452 if (currentInfo.driverKind !== desiredInfo.driverKind) {
453 return yield* new ProviderAdapterRequestError({
454 provider: preferredProvider,
455 method: "thread.turn.start",
456 detail: `Thread '${threadId}' is bound to driver '${currentInfo.driverKind}' and cannot switch to '${desiredInfo.driverKind}'.`,
457 });
458 }
459 if (
460 currentInfo.continuationIdentity.continuationKey !==
461 desiredInfo.continuationIdentity.continuationKey
462 ) {
463 return yield* new ProviderAdapterRequestError({
464 provider: preferredProvider,
465 method: "thread.turn.start",
466 detail: `Thread '${threadId}' cannot switch from instance '${currentInstanceId}' to '${desiredInstanceId}' because their provider resume state is incompatible.`,
467 });
468 }
469 }
470 const project = yield* resolveProject(thread.projectId);
471 const effectiveCwd = resolveThreadWorkspaceCwd({
472 thread,
473 projects: project ? [project] : [],
474 });
475​
476 const startProviderSession = (input?: {
477 readonly resumeCursor?: unknown;
478 readonly provider?: ProviderDriverKind;
479 }) =>
480 providerService.startSession(threadId, {
481 threadId,
482 ...(preferredProvider ? { provider: preferredProvider } : {}),
483 providerInstanceId: desiredInstanceId,
484 ...(effectiveCwd ? { cwd: effectiveCwd } : {}),
485 modelSelection: desiredModelSelection,
486 ...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
487 runtimeMode: desiredRuntimeMode,
488 });
489​
490 const bindSessionToThread = (session: ProviderSession) =>
491 Effect.gen(function* () {
492 if (session.providerInstanceId === undefined) {
493 return yield* new ProviderAdapterRequestError({
494 provider: providerErrorLabel(session.provider),
495 method: "thread.turn.start",
496 detail: `Provider session '${session.threadId}' started without a provider instance id.`,
497 });
498 }
499 yield* setThreadSession({
500 threadId,
501 session: {
502 threadId,
503 status: mapProviderSessionStatusToOrchestrationStatus(session.status),
504 providerName: session.provider,
505 providerInstanceId: session.providerInstanceId,
506 runtimeMode: desiredRuntimeMode,
507 // Provider turn ids are not orchestration turn ids.
508 activeTurnId: null,
509 lastError: session.lastError ?? null,
510 updatedAt: session.updatedAt,
511 },
512 createdAt,
513 });
514 });
515​
516 const existingSessionThreadId =
517 thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
518 if (existingSessionThreadId) {
519 const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
520 const cwdChanged = effectiveCwd !== activeSession?.cwd;
521 const sessionModelSwitch = (yield* providerService.getCapabilities(desiredInstanceId))
522 .sessionModelSwitch;
523 const modelChanged =
524 requestedModelSelection !== undefined &&
525 requestedModelSelection.model !== activeSession?.model;
526 const instanceChanged =
527 requestedModelSelection !== undefined &&
528 activeSession?.providerInstanceId !== requestedModelSelection.instanceId;
529 const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
530 const previousModelSelection = threadModelSelections.get(threadId);
531 const shouldRestartForModelSelectionChange =
532 preferredProvider === "claudeAgent" &&
533 requestedModelSelection !== undefined &&
534 !Equal.equals(previousModelSelection, requestedModelSelection);
535​
536 if (
537 !runtimeModeChanged &&
538 !cwdChanged &&
539 !instanceChanged &&
540 !shouldRestartForModelChange &&
541 !shouldRestartForModelSelectionChange
542 ) {
543 return existingSessionThreadId;
544 }
545​
546 const resumeCursor = shouldRestartForModelChange
547 ? undefined
548 : (activeSession?.resumeCursor ?? undefined);
549 yield* Effect.logInfo("provider command reactor restarting provider session", {
550 threadId,
551 existingSessionThreadId,
552 currentProvider: activeSession?.provider,
553 currentInstanceId,
554 desiredInstanceId,
555 desiredProvider: desiredModelSelection.instanceId,
556 currentRuntimeMode: thread.session?.runtimeMode,
557 desiredRuntimeMode: thread.runtimeMode,
558 runtimeModeChanged,
559 previousCwd: activeSession?.cwd,
560 desiredCwd: effectiveCwd,
561 cwdChanged,
562 modelChanged,
563 instanceChanged,
564 shouldRestartForModelChange,
565 shouldRestartForModelSelectionChange,
566 hasResumeCursor: resumeCursor !== undefined,
567 });
568 const restartedSession = yield* startProviderSession(
569 resumeCursor !== undefined ? { resumeCursor } : undefined,
570 );
571 yield* Effect.logInfo("provider command reactor restarted provider session", {
572 threadId,
573 previousSessionId: existingSessionThreadId,
574 restartedSessionThreadId: restartedSession.threadId,
575 provider: restartedSession.provider,
576 runtimeMode: restartedSession.runtimeMode,
577 cwd: restartedSession.cwd,
578 });
579 yield* bindSessionToThread(restartedSession);
580 return restartedSession.threadId;
581 }
582​
583 const startedSession = yield* startProviderSession(undefined);
584 yield* bindSessionToThread(startedSession);
585 return startedSession.threadId;
586 });
587​
588 const buildSendTurnRequestForThread = Effect.fnUntraced(function* (input: {
589 readonly threadId: ThreadId;
590 readonly messageText: string;
591 readonly attachments?: ReadonlyArray<ChatAttachment>;
592 readonly modelSelection?: ModelSelection;
593 readonly interactionMode?: "default" | "plan";
594 readonly createdAt: string;
595 }) {
596 const thread = yield* resolveThread(input.threadId);
597 if (!thread) {
598 return yield* Effect.die(
599 new Error(`Thread '${input.threadId}' was not found in read model.`),
600 );
601 }
602 yield* ensureSessionForThread(
603 input.threadId,
604 input.createdAt,
605 input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {},
606 );
607 if (input.modelSelection !== undefined) {
608 threadModelSelections.set(input.threadId, input.modelSelection);
609 }
610 const normalizedInput = toNonEmptyProviderInput(input.messageText);
611 const normalizedAttachments = input.attachments ?? [];
612 const activeSession = yield* providerService
613 .listSessions()
614 .pipe(
615 Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),
616 );
617 const sessionModelSwitch =
618 activeSession === undefined
619 ? "in-session"
620 : activeSession.providerInstanceId === undefined
621 ? yield* new ProviderAdapterRequestError({
622 provider: providerErrorLabel(activeSession.provider),
623 method: "thread.turn.start",
624 detail: `Active provider session '${activeSession.threadId}' is missing a provider instance id.`,
625 })
626 : (yield* providerService.getCapabilities(activeSession.providerInstanceId))
627 .sessionModelSwitch;
628 const requestedModelSelection =
629 input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
630 const modelForTurn =
631 sessionModelSwitch === "unsupported" && input.modelSelection === undefined
632 ? activeSession?.model !== undefined
633 ? {
634 ...requestedModelSelection,
635 model: activeSession.model,
636 }
637 : requestedModelSelection
638 : input.modelSelection;
639​
640 return {
641 threadId: input.threadId,
642 ...(normalizedInput ? { input: normalizedInput } : {}),
643 ...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
644 ...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
645 ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
646 };
647 });
648​
649 const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn(
650 "maybeGenerateAndRenameWorktreeBranchForFirstTurn",
651 )(function* (input: {
652 readonly threadId: ThreadId;
653 readonly branch: string | null;
654 readonly worktreePath: string | null;
655 readonly messageText: string;
656 readonly attachments?: ReadonlyArray<ChatAttachment>;
657 }) {
658 if (!input.branch || !input.worktreePath) {
659 return;
660 }
661 if (!isTemporaryWorktreeBranch(input.branch)) {
662 return;
663 }
664​
665 const oldBranch = input.branch;
666 const cwd = input.worktreePath;
667 const attachments = input.attachments ?? [];
668 yield* Effect.gen(function* () {
669 const { textGenerationModelSelection: modelSelection } =
670 yield* serverSettingsService.getSettings;
671​
672 const generated = yield* textGeneration.generateBranchName({
673 cwd,
674 message: input.messageText,
675 ...(attachments.length > 0 ? { attachments } : {}),
676 modelSelection,
677 });
678 if (!generated) return;
679​
680 const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
681 if (targetBranch === oldBranch) return;
682​
683 const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
684 yield* orchestrationEngine.dispatch({
685 type: "thread.meta.update",
686 commandId: yield* serverCommandId("worktree-branch-rename"),
687 threadId: input.threadId,
688 branch: renamed.branch,
689 worktreePath: cwd,
690 });
691 yield* vcsStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
692 }).pipe(
693 Effect.catchCause((cause) =>
694 Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
695 threadId: input.threadId,
696 cwd,
697 oldBranch,
698 cause: Cause.pretty(cause),
699 }),
700 ),
701 );
702 });
703​
704 const maybeGenerateThreadTitleForFirstTurn = Effect.fn("maybeGenerateThreadTitleForFirstTurn")(
705 function* (input: {
706 readonly threadId: ThreadId;
707 readonly cwd: string;
708 readonly messageText: string;
709 readonly attachments?: ReadonlyArray<ChatAttachment>;
710 readonly titleSeed?: string;
711 }) {
712 const attachments = input.attachments ?? [];
713 yield* Effect.gen(function* () {
714 const { textGenerationModelSelection: modelSelection } =
715 yield* serverSettingsService.getSettings;
716​
717 const generated = yield* textGeneration.generateThreadTitle({
718 cwd: input.cwd,
719 message: input.messageText,
720 ...(attachments.length > 0 ? { attachments } : {}),
721 modelSelection,
722 });
723 if (!generated) return;
724​
725 const thread = yield* resolveThread(input.threadId);
726 if (!thread) return;
727 if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {
728 return;
729 }
730​
731 yield* orchestrationEngine.dispatch({
732 type: "thread.meta.update",
733 commandId: yield* serverCommandId("thread-title-rename"),
734 threadId: input.threadId,
735 title: generated.title,
736 });
737 }).pipe(
738 Effect.catchCause((cause) =>
739 Effect.logWarning("provider command reactor failed to generate or rename thread title", {
740 threadId: input.threadId,
741 cwd: input.cwd,
742 cause: Cause.pretty(cause),
743 }),
744 ),
745 );
746 },
747 );
748​
749 const processTurnStartRequested = Effect.fn("processTurnStartRequested")(function* (
750 event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
751 ) {
752 const key = turnStartKeyForEvent(event);
753 if (yield* hasHandledTurnStartRecently(key)) {
754 return;
755 }
756​
757 const thread = yield* resolveThread(event.payload.threadId);
758 if (!thread) {
759 return;
760 }
761​
762 const message = thread.messages.find((entry) => entry.id === event.payload.messageId);
763 if (!message || message.role !== "user") {
764 yield* appendProviderFailureActivity({
765 threadId: event.payload.threadId,
766 kind: "provider.turn.start.failed",
767 summary: "Provider turn start failed",
768 detail: `User message '${event.payload.messageId}' was not found for turn start request.`,
769 turnId: null,
770 createdAt: event.payload.createdAt,
771 });
772 return;
773 }
774​
775 const isFirstUserMessageTurn =
776 thread.messages.filter((entry) => entry.role === "user").length === 1;
777 if (isFirstUserMessageTurn) {
778 const project = yield* resolveProject(thread.projectId);
779 const generationCwd =
780 resolveThreadWorkspaceCwd({
781 thread,
782 projects: project ? [project] : [],
783 }) ?? process.cwd();
784 const generationInput = {
785 messageText: message.text,
786 ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
787 ...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}),
788 };
789​
790 yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({
791 threadId: event.payload.threadId,
792 branch: thread.branch,
793 worktreePath: thread.worktreePath,
794 ...generationInput,
795 }).pipe(Effect.forkScoped);
796​
797 if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) {
798 yield* maybeGenerateThreadTitleForFirstTurn({
799 threadId: event.payload.threadId,
800 cwd: generationCwd,
801 ...generationInput,
802 }).pipe(Effect.forkScoped);
803 }
804 }
805​
806 const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
807 if (Cause.hasInterruptsOnly(cause)) {
808 return Effect.void;
809 }
810 const detail = formatFailureDetail(cause);
811 return setThreadSessionErrorOnTurnStartFailure({
812 threadId: event.payload.threadId,
813 detail,
814 createdAt: event.payload.createdAt,
815 }).pipe(
816 Effect.flatMap(() =>
817 appendProviderFailureActivity({
818 threadId: event.payload.threadId,
819 kind: "provider.turn.start.failed",
820 summary: "Provider turn start failed",
821 detail,
822 turnId: null,
823 createdAt: event.payload.createdAt,
824 }),
825 ),
826 Effect.asVoid,
827 );
828 };
829​
830 const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
831 handleTurnStartFailure(cause).pipe(
832 Effect.catchCause((recoveryCause) =>
833 Effect.logWarning("provider command reactor failed to recover turn start failure", {
834 eventType: event.type,
835 threadId: event.payload.threadId,
836 cause: Cause.pretty(recoveryCause),
837 originalCause: Cause.pretty(cause),
838 }),
839 ),
840 );
841​
842 const sendTurnRequest = yield* buildSendTurnRequestForThread({
843 threadId: event.payload.threadId,
844 messageText: message.text,
845 ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
846 ...(event.payload.modelSelection !== undefined
847 ? { modelSelection: event.payload.modelSelection }
848 : {}),
849 interactionMode: event.payload.interactionMode,
850 createdAt: event.payload.createdAt,
851 }).pipe(
852 Effect.map(Option.some),
853 Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),
854 );
855​
856 if (Option.isNone(sendTurnRequest)) {
857 return;
858 }
859​
860 yield* providerService
861 .sendTurn(sendTurnRequest.value)
862 .pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
863 });
864​
865 const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
866 event: Extract<ProviderIntentEvent, { type: "thread.turn-interrupt-requested" }>,
867 ) {
868 const thread = yield* resolveThread(event.payload.threadId);
869 if (!thread) {
870 return;
871 }
872 const hasSession = thread.session && thread.session.status !== "stopped";
873 if (!hasSession) {
874 return yield* appendProviderFailureActivity({
875 threadId: event.payload.threadId,
876 kind: "provider.turn.interrupt.failed",
877 summary: "Provider turn interrupt failed",
878 detail: "No active provider session is bound to this thread.",
879 turnId: event.payload.turnId ?? null,
880 createdAt: event.payload.createdAt,
881 });
882 }
883​
884 // Orchestration turn ids are not provider turn ids, so interrupt by session.
885 yield* providerService.interruptTurn({ threadId: event.payload.threadId });
886 });
887​
888 const processApprovalResponseRequested = Effect.fn("processApprovalResponseRequested")(function* (
889 event: Extract<ProviderIntentEvent, { type: "thread.approval-response-requested" }>,
890 ) {
891 const thread = yield* resolveThread(event.payload.threadId);
892 if (!thread) {
893 return;
894 }
895 const hasSession = thread.session && thread.session.status !== "stopped";
896 if (!hasSession) {
897 return yield* appendProviderFailureActivity({
898 threadId: event.payload.threadId,
899 kind: "provider.approval.respond.failed",
900 summary: "Provider approval response failed",
901 detail: "No active provider session is bound to this thread.",
902 turnId: null,
903 createdAt: event.payload.createdAt,
904 requestId: event.payload.requestId,
905 });
906 }
907​
908 yield* providerService
909 .respondToRequest({
910 threadId: event.payload.threadId,
911 requestId: event.payload.requestId,
912 decision: event.payload.decision,
913 })
914 .pipe(
915 Effect.catchCause((cause) =>
916 appendProviderFailureActivity({
917 threadId: event.payload.threadId,
918 kind: "provider.approval.respond.failed",
919 summary: "Provider approval response failed",
920 detail: isUnknownPendingApprovalRequestError(cause)
921 ? stalePendingRequestDetail("approval", event.payload.requestId)
922 : Cause.pretty(cause),
923 turnId: null,
924 createdAt: event.payload.createdAt,
925 requestId: event.payload.requestId,
926 }),
927 ),
928 );
929 });
930​
931 const processUserInputResponseRequested = Effect.fn("processUserInputResponseRequested")(
932 function* (
933 event: Extract<ProviderIntentEvent, { type: "thread.user-input-response-requested" }>,
934 ) {
935 const thread = yield* resolveThread(event.payload.threadId);
936 if (!thread) {
937 return;
938 }
939 const hasSession = thread.session && thread.session.status !== "stopped";
940 if (!hasSession) {
941 return yield* appendProviderFailureActivity({
942 threadId: event.payload.threadId,
943 kind: "provider.user-input.respond.failed",
944 summary: "Provider user input response failed",
945 detail: "No active provider session is bound to this thread.",
946 turnId: null,
947 createdAt: event.payload.createdAt,
948 requestId: event.payload.requestId,
949 });
950 }
951​
952 yield* providerService
953 .respondToUserInput({
954 threadId: event.payload.threadId,
955 requestId: event.payload.requestId,
956 answers: event.payload.answers,
957 })
958 .pipe(
959 Effect.catchCause((cause) =>
960 appendProviderFailureActivity({
961 threadId: event.payload.threadId,
962 kind: "provider.user-input.respond.failed",
963 summary: "Provider user input response failed",
964 detail: isUnknownPendingUserInputRequestError(cause)
965 ? stalePendingRequestDetail("user-input", event.payload.requestId)
966 : Cause.pretty(cause),
967 turnId: null,
968 createdAt: event.payload.createdAt,
969 requestId: event.payload.requestId,
970 }),
971 ),
972 );
973 },
974 );
975​
976 const processSessionStopRequested = Effect.fn("processSessionStopRequested")(function* (
977 event: Extract<ProviderIntentEvent, { type: "thread.session-stop-requested" }>,
978 ) {
979 const thread = yield* resolveThread(event.payload.threadId);
980 if (!thread) {
981 return;
982 }
983​
984 const now = event.payload.createdAt;
985 if (thread.session && thread.session.status !== "stopped") {
986 yield* providerService.stopSession({ threadId: thread.id });
987 }
988​
989 yield* setThreadSession({
990 threadId: thread.id,
991 session: {
992 threadId: thread.id,
993 status: "stopped",
994 providerName: thread.session?.providerName ?? null,
995 ...(thread.session?.providerInstanceId !== undefined
996 ? { providerInstanceId: thread.session.providerInstanceId }
997 : {}),
998 runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
999 activeTurnId: null,
1000 lastError: thread.session?.lastError ?? null,
1001 updatedAt: now,
1002 },
1003 createdAt: now,
1004 });
1005 });
1006​
1007 const processTaskStopRequested = Effect.fn("processTaskStopRequested")(function* (
1008 event: Extract<ProviderIntentEvent, { type: "thread.task-stop-requested" }>,
1009 ) {
1010 const thread = yield* resolveThread(event.payload.threadId);
1011 if (!thread) {
1012 return;
1014 const hasSession = thread.session && thread.session.status !== "stopped";
1015 if (!hasSession) {
1016 return yield* appendProviderFailureActivity({
1017 threadId: event.payload.threadId,
1018 kind: "provider.task.stop.failed",
1019 summary: "Background task stop failed",
1020 detail: "No active provider session is bound to this thread.",
1021 turnId: null,
1022 createdAt: event.payload.createdAt,
1023 });
1025​
1026 yield* providerService
1027 .stopTask({
1028 threadId: event.payload.threadId,
1029 taskId: event.payload.taskId,
1030 })
1031 .pipe(
1032 Effect.catchCause((cause) =>
1033 appendProviderFailureActivity({
1034 threadId: event.payload.threadId,
1035 kind: "provider.task.stop.failed",
1036 summary: "Background task stop failed",
1037 detail: Cause.pretty(cause),
1038 turnId: null,
1039 createdAt: event.payload.createdAt,
1040 }),
1041 ),
1042 );
1043 });
1044​
1045 const processDomainEvent = Effect.fn("processDomainEvent")(function* (
1046 event: ProviderIntentEvent,
1047 ) {
1048 yield* Effect.annotateCurrentSpan({
1049 "orchestration.event_type": event.type,
1050 "orchestration.thread_id": event.payload.threadId,
1051 ...(event.commandId ? { "orchestration.command_id": event.commandId } : {}),
1052 });
1053 yield* increment(orchestrationEventsProcessedTotal, {
1054 eventType: event.type,
1055 });
1056 switch (event.type) {
1057 case "thread.runtime-mode-set": {
1058 const thread = yield* resolveThread(event.payload.threadId);
1059 if (!thread?.session || thread.session.status === "stopped") {
1060 return;
1062 const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
1063 yield* ensureSessionForThread(
1064 event.payload.threadId,
1065 event.occurredAt,
1066 cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
1067 );
1068 return;
1070 case "thread.turn-start-requested":
1071 yield* processTurnStartRequested(event);
1072 return;
1073 case "thread.turn-interrupt-requested":
1074 yield* processTurnInterruptRequested(event);
1075 return;
1076 case "thread.approval-response-requested":
1077 yield* processApprovalResponseRequested(event);
1078 return;
1079 case "thread.user-input-response-requested":
1080 yield* processUserInputResponseRequested(event);
1081 return;
1082 case "thread.session-stop-requested":
1083 yield* processSessionStopRequested(event);
1084 return;
1085 case "thread.task-stop-requested":
1086 yield* processTaskStopRequested(event);
1087 return;
1089 });
1090​
1091 const processDomainEventSafely = (event: ProviderIntentEvent) =>
1092 processDomainEvent(event).pipe(
1093 Effect.catchCause((cause) => {
1094 if (Cause.hasInterruptsOnly(cause)) {
1095 return Effect.failCause(cause);
1097 return Effect.logWarning("provider command reactor failed to process event", {
1098 eventType: event.type,
1099 cause: Cause.pretty(cause),
1100 });
1101 }),
1102 );
1103​
1104 const worker = yield* makeDrainableWorker(processDomainEventSafely);
1105​
1106 const start: ProviderCommandReactorShape["start"] = Effect.fn("start")(function* () {
1107 const processEvent = Effect.fn("processEvent")(function* (event: OrchestrationEvent) {
1108 if (
1109 event.type === "thread.runtime-mode-set" ||
1110 event.type === "thread.turn-start-requested" ||
1111 event.type === "thread.turn-interrupt-requested" ||
1112 event.type === "thread.approval-response-requested" ||
1113 event.type === "thread.user-input-response-requested" ||
1114 event.type === "thread.session-stop-requested" ||
1115 event.type === "thread.task-stop-requested"
1116 ) {
1117 return yield* worker.enqueue(event);
1119 });
1120​
1121 yield* Effect.forkScoped(
1122 Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent),
1123 );
1124 });
1125​
1126 return {
1127 start,
1128 drain: worker.drain,
1129 } satisfies ProviderCommandReactorShape;
1130});
1131​
1132export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make);