Open History to see the last commit
1import {
2 ApprovalRequestId,
3 type AssistantDeliveryMode,
4 CommandId,
5 MessageId,
6 type OrchestrationEvent,
7 CheckpointRef,
8 ThreadId,
9 TurnId,
10 type OrchestrationThreadActivity,
11 type ProviderRuntimeEvent,
12} from "@t3tools/contracts";
13import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Ref, Stream } from "effect";
14
15import { ProviderService } from "../../provider/Services/ProviderService.ts";
16import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
17import { isGitRepository } from "../../git/isRepo.ts";
18import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
19import {
20 ProviderRuntimeIngestionService,
21 type ProviderRuntimeIngestionShape,
22} from "../Services/ProviderRuntimeIngestion.ts";
23
24const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
25const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
26 CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
27
28const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
29const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
30const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
31const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
32const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120);
33const BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY = 10_000;
34const BUFFERED_PROPOSED_PLAN_BY_ID_TTL = Duration.minutes(120);
35const MAX_BUFFERED_ASSISTANT_CHARS = 24_000;
36const STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== "0";
37
38type TurnStartRequestedDomainEvent = Extract<
39 OrchestrationEvent,
40 { type: "thread.turn-start-requested" }
41>;
42
43type RuntimeIngestionInput =
44 | {
45 source: "runtime";
46 event: ProviderRuntimeEvent;
47 }
48 | {
49 source: "domain";
50 event: TurnStartRequestedDomainEvent;
51 };
52
53function toTurnId(value: TurnId | string | undefined): TurnId | undefined {
54 return value === undefined ? undefined : TurnId.makeUnsafe(String(value));
55}
56
57function toApprovalRequestId(value: string | undefined): ApprovalRequestId | undefined {
58 return value === undefined ? undefined : ApprovalRequestId.makeUnsafe(value);
59}
60
61function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
62 if (left === null || left === undefined || right === null || right === undefined) {
63 return false;
64 }
65 return left === right;
66}
67
68function truncateDetail(value: string, limit = 180): string {
69 return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
70}
71
72function normalizeProposedPlanMarkdown(planMarkdown: string | undefined): string | undefined {
73 const trimmed = planMarkdown?.trim();
74 if (!trimmed) {
75 return undefined;
76 }
77 return trimmed;
78}
79
80function proposedPlanIdForTurn(threadId: ThreadId, turnId: TurnId): string {
81 return `plan:${threadId}:turn:${turnId}`;
82}
83
84function proposedPlanIdFromEvent(event: ProviderRuntimeEvent, threadId: ThreadId): string {
85 const turnId = toTurnId(event.turnId);
86 if (turnId) {
87 return proposedPlanIdForTurn(threadId, turnId);
88 }
89 if (event.itemId) {
90 return `plan:${threadId}:item:${event.itemId}`;
91 }
92 return `plan:${threadId}:event:${event.eventId}`;
93}
94
95function asString(value: unknown): string | undefined {
96 return typeof value === "string" ? value : undefined;
97}
98
99function runtimePayloadRecord(event: ProviderRuntimeEvent): Record<string, unknown> | undefined {
100 const payload = (event as { payload?: unknown }).payload;
101 if (!payload || typeof payload !== "object") {
102 return undefined;
103 }
104 return payload as Record<string, unknown>;
105}
106
107function normalizeRuntimeTurnState(
108 value: string | undefined,
109): "completed" | "failed" | "interrupted" | "cancelled" {
110 switch (value) {
111 case "failed":
112 case "interrupted":
113 case "cancelled":
114 case "completed":
115 return value;
116 default:
117 return "completed";
118 }
119}
120
121function runtimeTurnState(
122 event: ProviderRuntimeEvent,
123): "completed" | "failed" | "interrupted" | "cancelled" {
124 const payloadState = asString(runtimePayloadRecord(event)?.state);
125 return normalizeRuntimeTurnState(payloadState);
126}
127
128function runtimeTurnErrorMessage(event: ProviderRuntimeEvent): string | undefined {
129 const payloadErrorMessage = asString(runtimePayloadRecord(event)?.errorMessage);
130 return payloadErrorMessage;
131}
132
133function runtimeErrorMessageFromEvent(event: ProviderRuntimeEvent): string | undefined {
134 const payloadMessage = asString(runtimePayloadRecord(event)?.message);
135 return payloadMessage;
136}
137
138function orchestrationSessionStatusFromRuntimeState(
139 state: "starting" | "running" | "waiting" | "ready" | "interrupted" | "stopped" | "error",
140): "starting" | "running" | "ready" | "interrupted" | "stopped" | "error" {
141 switch (state) {
142 case "starting":
143 return "starting";
144 case "running":
145 case "waiting":
146 return "running";
147 case "ready":
148 return "ready";
149 case "interrupted":
150 return "interrupted";
151 case "stopped":
152 return "stopped";
153 case "error":
154 return "error";
155 }
156}
157
158function requestKindFromCanonicalRequestType(
159 requestType: string | undefined,
160): "command" | "file-read" | "file-change" | undefined {
161 switch (requestType) {
162 case "command_execution_approval":
163 case "exec_command_approval":
164 return "command";
165 case "file_read_approval":
166 return "file-read";
167 case "file_change_approval":
168 case "apply_patch_approval":
169 return "file-change";
170 default:
171 return undefined;
172 }
173}
174
175function isToolLifecycleItemType(itemType: string): boolean {
176 return (
177 itemType === "command_execution" ||
178 itemType === "file_change" ||
179 itemType === "mcp_tool_call" ||
180 itemType === "dynamic_tool_call" ||
181 itemType === "collab_agent_tool_call" ||
182 itemType === "web_search" ||
183 itemType === "image_view"
184 );
185}
186
187function runtimeEventToActivities(
188 event: ProviderRuntimeEvent,
189): ReadonlyArray<OrchestrationThreadActivity> {
190 const maybeSequence = (() => {
191 const eventWithSequence = event as ProviderRuntimeEvent & { sessionSequence?: number };
192 return eventWithSequence.sessionSequence !== undefined
193 ? { sequence: eventWithSequence.sessionSequence }
194 : {};
195 })();
196 switch (event.type) {
197 case "request.opened": {
198 if (event.payload.requestType === "tool_user_input") {
199 return [];
200 }
201 const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType);
202 return [
203 {
204 id: event.eventId,
205 createdAt: event.createdAt,
206 tone: "approval",
207 kind: "approval.requested",
208 summary:
209 requestKind === "command"
210 ? "Command approval requested"
211 : requestKind === "file-read"
212 ? "File-read approval requested"
213 : requestKind === "file-change"
214 ? "File-change approval requested"
215 : "Approval requested",
216 payload: {
217 requestId: toApprovalRequestId(event.requestId),
218 ...(requestKind ? { requestKind } : {}),
219 requestType: event.payload.requestType,
220 ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
221 },
222 turnId: toTurnId(event.turnId) ?? null,
223 ...maybeSequence,
224 },
225 ];
226 }
227
228 case "request.resolved": {
229 if (event.payload.requestType === "tool_user_input") {
230 return [];
231 }
232 const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType);
233 return [
234 {
235 id: event.eventId,
236 createdAt: event.createdAt,
237 tone: "approval",
238 kind: "approval.resolved",
239 summary: "Approval resolved",
240 payload: {
241 requestId: toApprovalRequestId(event.requestId),
242 ...(requestKind ? { requestKind } : {}),
243 requestType: event.payload.requestType,
244 ...(event.payload.decision ? { decision: event.payload.decision } : {}),
245 },
246 turnId: toTurnId(event.turnId) ?? null,
247 ...maybeSequence,
248 },
249 ];
250 }
251
252 case "runtime.error": {
253 const message = runtimeErrorMessageFromEvent(event);
254 if (!message) {
255 return [];
256 }
257 return [
258 {
259 id: event.eventId,
260 createdAt: event.createdAt,
261 tone: "error",
262 kind: "runtime.error",
263 summary: "Runtime error",
264 payload: {
265 message: truncateDetail(message),
266 },
267 turnId: toTurnId(event.turnId) ?? null,
268 ...maybeSequence,
269 },
270 ];
271 }
272
273 case "runtime.warning": {
274 return [
275 {
276 id: event.eventId,
277 createdAt: event.createdAt,
278 tone: "info",
279 kind: "runtime.warning",
280 summary: "Runtime warning",
281 payload: {
282 message: truncateDetail(event.payload.message),
283 ...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
284 },
285 turnId: toTurnId(event.turnId) ?? null,
286 ...maybeSequence,
287 },
288 ];
289 }
290
291 case "turn.plan.updated": {
292 return [
293 {
294 id: event.eventId,
295 createdAt: event.createdAt,
296 tone: "info",
297 kind: "turn.plan.updated",
298 summary: "Plan updated",
299 payload: {
300 plan: event.payload.plan,
301 ...(event.payload.explanation !== undefined ? { explanation: event.payload.explanation } : {}),
302 },
303 turnId: toTurnId(event.turnId) ?? null,
304 ...maybeSequence,
305 },
306 ];
307 }
308
309 case "user-input.requested": {
310 return [
311 {
312 id: event.eventId,
313 createdAt: event.createdAt,
314 tone: "info",
315 kind: "user-input.requested",
316 summary: "User input requested",
317 payload: {
318 ...(event.requestId ? { requestId: event.requestId } : {}),
319 questions: event.payload.questions,
320 },
321 turnId: toTurnId(event.turnId) ?? null,
322 ...maybeSequence,
323 },
324 ];
325 }
326
327 case "user-input.resolved": {
328 return [
329 {
330 id: event.eventId,
331 createdAt: event.createdAt,
332 tone: "info",
333 kind: "user-input.resolved",
334 summary: "User input submitted",
335 payload: {
336 ...(event.requestId ? { requestId: event.requestId } : {}),
337 answers: event.payload.answers,
338 },
339 turnId: toTurnId(event.turnId) ?? null,
340 ...maybeSequence,
341 },
342 ];
343 }
344
345 case "task.started": {
346 return [
347 {
348 id: event.eventId,
349 createdAt: event.createdAt,
350 tone: "info",
351 kind: "task.started",
352 summary:
353 event.payload.taskType === "plan"
354 ? "Plan task started"
355 : event.payload.taskType
356 ? `${event.payload.taskType} task started`
357 : "Task started",
358 payload: {
359 taskId: event.payload.taskId,
360 ...(event.payload.taskType ? { taskType: event.payload.taskType } : {}),
361 ...(event.payload.description ? { detail: truncateDetail(event.payload.description) } : {}),
362 },
363 turnId: toTurnId(event.turnId) ?? null,
364 ...maybeSequence,
365 },
366 ];
367 }
368
369 case "task.progress": {
370 return [
371 {
372 id: event.eventId,
373 createdAt: event.createdAt,
374 tone: "info",
375 kind: "task.progress",
376 summary: "Reasoning update",
377 payload: {
378 taskId: event.payload.taskId,
379 detail: truncateDetail(event.payload.description),
380 ...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
381 ...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
382 },
383 turnId: toTurnId(event.turnId) ?? null,
384 ...maybeSequence,
385 },
386 ];
387 }
388
389 case "task.completed": {
390 return [
391 {
392 id: event.eventId,
393 createdAt: event.createdAt,
394 tone: event.payload.status === "failed" ? "error" : "info",
395 kind: "task.completed",
396 summary:
397 event.payload.status === "failed"
398 ? "Task failed"
399 : event.payload.status === "stopped"
400 ? "Task stopped"
401 : "Task completed",
402 payload: {
403 taskId: event.payload.taskId,
404 status: event.payload.status,
405 ...(event.payload.summary ? { detail: truncateDetail(event.payload.summary) } : {}),
406 ...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
407 },
408 turnId: toTurnId(event.turnId) ?? null,
409 ...maybeSequence,
410 },
411 ];
412 }
413
414 case "item.updated": {
415 if (!isToolLifecycleItemType(event.payload.itemType)) {
416 return [];
417 }
418 return [
419 {
420 id: event.eventId,
421 createdAt: event.createdAt,
422 tone: "tool",
423 kind: "tool.updated",
424 summary: event.payload.title ?? "Tool updated",
425 payload: {
426 itemType: event.payload.itemType,
427 ...(event.payload.status ? { status: event.payload.status } : {}),
428 ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
429 ...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
430 },
431 turnId: toTurnId(event.turnId) ?? null,
432 ...maybeSequence,
433 },
434 ];
435 }
436
437 case "item.completed": {
438 if (!isToolLifecycleItemType(event.payload.itemType)) {
439 return [];
440 }
441 return [
442 {
443 id: event.eventId,
444 createdAt: event.createdAt,
445 tone: "tool",
446 kind: "tool.completed",
447 summary: `${event.payload.title ?? "Tool"} complete`,
448 payload: {
449 itemType: event.payload.itemType,
450 ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
451 },
452 turnId: toTurnId(event.turnId) ?? null,
453 ...maybeSequence,
454 },
455 ];
456 }
457
458 case "item.started": {
459 if (!isToolLifecycleItemType(event.payload.itemType)) {
460 return [];
461 }
462 return [
463 {
464 id: event.eventId,
465 createdAt: event.createdAt,
466 tone: "tool",
467 kind: "tool.started",
468 summary: `${event.payload.title ?? "Tool"} started`,
469 payload: {
470 itemType: event.payload.itemType,
471 ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
472 },
473 turnId: toTurnId(event.turnId) ?? null,
474 ...maybeSequence,
475 },
476 ];
477 }
478
479 default:
480 break;
481 }
482
483 return [];
484}
485
486const make = Effect.gen(function* () {
487 const orchestrationEngine = yield* OrchestrationEngineService;
488 const providerService = yield* ProviderService;
489
490 const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
491 DEFAULT_ASSISTANT_DELIVERY_MODE,
492 );
493
494 const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
495 capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
496 timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
497 lookup: () => Effect.succeed(new Set<MessageId>()),
498 });
499
500 const bufferedAssistantTextByMessageId = yield* Cache.make<MessageId, string>({
501 capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY,
502 timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL,
503 lookup: () => Effect.succeed(""),
504 });
505
506 const bufferedProposedPlanById = yield* Cache.make<string, { text: string; createdAt: string }>({
507 capacity: BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY,
508 timeToLive: BUFFERED_PROPOSED_PLAN_BY_ID_TTL,
509 lookup: () => Effect.succeed({ text: "", createdAt: "" }),
510 });
511
512 const isGitRepoForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
513 const readModel = yield* orchestrationEngine.getReadModel();
514 const thread = readModel.threads.find((entry) => entry.id === threadId);
515 if (!thread) {
516 return false;
517 }
518 const workspaceCwd = resolveThreadWorkspaceCwd({
519 thread,
520 projects: readModel.projects,
521 });
522 if (!workspaceCwd) {
523 return false;
524 }
525 return isGitRepository(workspaceCwd);
526 });
527
528 const rememberAssistantMessageId = (
529 threadId: ThreadId,
530 turnId: TurnId,
531 messageId: MessageId,
532 ) =>
533 Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(
534 Effect.flatMap((existingIds) =>
535 Cache.set(
536 turnMessageIdsByTurnKey,
537 providerTurnKey(threadId, turnId),
538 Option.match(existingIds, {
539 onNone: () => new Set([messageId]),
540 onSome: (ids) => {
541 const nextIds = new Set(ids);
542 nextIds.add(messageId);
543 return nextIds;
544 },
545 }),
546 ),
547 ),
548 );
549
550 const forgetAssistantMessageId = (
551 threadId: ThreadId,
552 turnId: TurnId,
553 messageId: MessageId,
554 ) =>
555 Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(
556 Effect.flatMap((existingIds) =>
557 Option.match(existingIds, {
558 onNone: () => Effect.void,
559 onSome: (ids) => {
560 const nextIds = new Set(ids);
561 nextIds.delete(messageId);
562 if (nextIds.size === 0) {
563 return Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));
564 }
565 return Cache.set(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId), nextIds);
566 },
567 }),
568 ),
569 );
570
571 const getAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) =>
572 Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(
573 Effect.map((existingIds) =>
574 Option.getOrElse(existingIds, (): Set<MessageId> => new Set<MessageId>()),
575 ),
576 );
577
578 const clearAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) =>
579 Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));
580
581 const appendBufferedAssistantText = (messageId: MessageId, delta: string) =>
582 Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
583 Effect.flatMap((existingText) =>
584 Effect.gen(function* () {
585 const nextText = Option.match(existingText, {
586 onNone: () => delta,
587 onSome: (text) => `${text}${delta}`,
588 });
589 if (nextText.length <= MAX_BUFFERED_ASSISTANT_CHARS) {
590 yield* Cache.set(bufferedAssistantTextByMessageId, messageId, nextText);
591 return "";
592 }
593
594 // Safety valve: flush full buffered text as an assistant delta to cap memory.
595 yield* Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
596 return nextText;
597 }),
598 ),
599 );
600
601 const takeBufferedAssistantText = (messageId: MessageId) =>
602 Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
603 Effect.flatMap((existingText) =>
604 Cache.invalidate(bufferedAssistantTextByMessageId, messageId).pipe(
605 Effect.as(Option.getOrElse(existingText, () => "")),
606 ),
607 ),
608 );
609
610 const clearBufferedAssistantText = (messageId: MessageId) =>
611 Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
612
613 const appendBufferedProposedPlan = (planId: string, delta: string, createdAt: string) =>
614 Cache.getOption(bufferedProposedPlanById, planId).pipe(
615 Effect.flatMap((existingEntry) => {
616 const existing = Option.getOrUndefined(existingEntry);
617 return Cache.set(bufferedProposedPlanById, planId, {
618 text: `${existing?.text ?? ""}${delta}`,
619 createdAt: existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt,
620 });
621 }),
622 );
623
624 const takeBufferedProposedPlan = (planId: string) =>
625 Cache.getOption(bufferedProposedPlanById, planId).pipe(
626 Effect.flatMap((existingEntry) =>
627 Cache.invalidate(bufferedProposedPlanById, planId).pipe(
628 Effect.as(Option.getOrUndefined(existingEntry)),
629 ),
630 ),
631 );
632
633 const clearBufferedProposedPlan = (planId: string) =>
634 Cache.invalidate(bufferedProposedPlanById, planId);
635
636 const clearAssistantMessageState = (messageId: MessageId) => clearBufferedAssistantText(messageId);
637
638 const finalizeAssistantMessage = (input: {
639 event: ProviderRuntimeEvent;
640 threadId: ThreadId;
641 messageId: MessageId;
642 turnId?: TurnId;
643 createdAt: string;
644 commandTag: string;
645 finalDeltaCommandTag: string;
646 fallbackText?: string;
647 }) =>
648 Effect.gen(function* () {
649 const bufferedText = yield* takeBufferedAssistantText(input.messageId);
650 const text =
651 bufferedText.length > 0
652 ? bufferedText
653 : (input.fallbackText?.trim().length ?? 0) > 0
654 ? input.fallbackText!
655 : "";
656
657 if (text.length > 0) {
658 yield* orchestrationEngine.dispatch({
659 type: "thread.message.assistant.delta",
660 commandId: providerCommandId(input.event, input.finalDeltaCommandTag),
661 threadId: input.threadId,
662 messageId: input.messageId,
663 delta: text,
664 ...(input.turnId ? { turnId: input.turnId } : {}),
665 createdAt: input.createdAt,
666 });
667 }
668
669 yield* orchestrationEngine.dispatch({
670 type: "thread.message.assistant.complete",
671 commandId: providerCommandId(input.event, input.commandTag),
672 threadId: input.threadId,
673 messageId: input.messageId,
674 ...(input.turnId ? { turnId: input.turnId } : {}),
675 createdAt: input.createdAt,
676 });
677 yield* clearAssistantMessageState(input.messageId);
678 });
679
680 const upsertProposedPlan = (input: {
681 event: ProviderRuntimeEvent;
682 threadId: ThreadId;
683 threadProposedPlans: ReadonlyArray<{
684 id: string;
685 createdAt: string;
686 }>;
687 planId: string;
688 turnId?: TurnId;
689 planMarkdown: string | undefined;
690 createdAt: string;
691 updatedAt: string;
692 }) =>
693 Effect.gen(function* () {
694 const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown);
695 if (!planMarkdown) {
696 return;
697 }
698
699 const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId);
700 yield* orchestrationEngine.dispatch({
701 type: "thread.proposed-plan.upsert",
702 commandId: providerCommandId(input.event, "proposed-plan-upsert"),
703 threadId: input.threadId,
704 proposedPlan: {
705 id: input.planId,
706 turnId: input.turnId ?? null,
707 planMarkdown,
708 createdAt: existingPlan?.createdAt ?? input.createdAt,
709 updatedAt: input.updatedAt,
710 },
711 createdAt: input.updatedAt,
712 });
713 });
714
715 const finalizeBufferedProposedPlan = (input: {
716 event: ProviderRuntimeEvent;
717 threadId: ThreadId;
718 threadProposedPlans: ReadonlyArray<{
719 id: string;
720 createdAt: string;
721 }>;
722 planId: string;
723 turnId?: TurnId;
724 fallbackMarkdown?: string;
725 updatedAt: string;
726 }) =>
727 Effect.gen(function* () {
728 const bufferedPlan = yield* takeBufferedProposedPlan(input.planId);
729 const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text);
730 const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown);
731 const planMarkdown = bufferedMarkdown ?? fallbackMarkdown;
732 if (!planMarkdown) {
733 return;
734 }
735
736 yield* upsertProposedPlan({
737 event: input.event,
738 threadId: input.threadId,
739 threadProposedPlans: input.threadProposedPlans,
740 planId: input.planId,
741 ...(input.turnId ? { turnId: input.turnId } : {}),
742 planMarkdown,
743 createdAt:
744 bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0
745 ? bufferedPlan.createdAt
746 : input.updatedAt,
747 updatedAt: input.updatedAt,
748 });
749 yield* clearBufferedProposedPlan(input.planId);
750 });
751
752 const clearTurnStateForSession = (threadId: ThreadId) =>
753 Effect.gen(function* () {
754 const prefix = `${threadId}:`;
755 const proposedPlanPrefix = `plan:${threadId}:`;
756 const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey));
757 const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById));
758 yield* Effect.forEach(
759 turnKeys,
760 (key) =>
761 Effect.gen(function* () {
762 if (!key.startsWith(prefix)) {
763 return;
764 }
765
766 const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key);
767 if (Option.isSome(messageIds)) {
768 yield* Effect.forEach(messageIds.value, clearAssistantMessageState, {
769 concurrency: 1,
770 }).pipe(Effect.asVoid);
771 }
772
773 yield* Cache.invalidate(turnMessageIdsByTurnKey, key);
774 }),
775 { concurrency: 1 },
776 ).pipe(Effect.asVoid);
777 yield* Effect.forEach(
778 proposedPlanKeys,
779 (key) =>
780 key.startsWith(proposedPlanPrefix)
781 ? Cache.invalidate(bufferedProposedPlanById, key)
782 : Effect.void,
783 { concurrency: 1 },
784 ).pipe(Effect.asVoid);
785 });
786
787 const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
788 Effect.gen(function* () {
789 const readModel = yield* orchestrationEngine.getReadModel();
790 const thread = readModel.threads.find((entry) => entry.id === event.threadId);
791 if (!thread) return;
792
793 const now = event.createdAt;
794 const eventTurnId = toTurnId(event.turnId);
795 const activeTurnId = thread.session?.activeTurnId ?? null;
796
797 const conflictsWithActiveTurn =
798 activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
799 const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
800
801 const shouldApplyThreadLifecycle = (() => {
802 if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
803 return true;
804 }
805 switch (event.type) {
806 case "session.exited":
807 return true;
808 case "session.started":
809 case "thread.started":
810 return true;
811 case "turn.started":
812 return !conflictsWithActiveTurn;
813 case "turn.completed":
814 if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
815 return false;
816 }
817 // Only the active turn may close the lifecycle state.
818 if (activeTurnId !== null && eventTurnId !== undefined) {
819 return sameId(activeTurnId, eventTurnId);
820 }
821 // If no active turn is tracked, accept completion scoped to this thread.
822 return true;
823 default:
824 return true;
825 }
826 })();
827
828 if (
829 event.type === "session.started" ||
830 event.type === "session.state.changed" ||
831 event.type === "session.exited" ||
832 event.type === "thread.started" ||
833 event.type === "turn.started" ||
834 event.type === "turn.completed"
835 ) {
836 const nextActiveTurnId =
837 event.type === "turn.started"
838 ? (eventTurnId ?? null)
839 : event.type === "turn.completed" || event.type === "session.exited"
840 ? null
841 : activeTurnId;
842 const status = (() => {
843 switch (event.type) {
844 case "session.state.changed":
845 return orchestrationSessionStatusFromRuntimeState(event.payload.state);
846 case "turn.started":
847 return "running";
848 case "session.exited":
849 return "stopped";
850 case "turn.completed":
851 return runtimeTurnState(event) === "failed" ? "error" : "ready";
852 case "session.started":
853 case "thread.started":
854 // Provider thread/session start notifications can arrive during an
855 // active turn; preserve turn-running state in that case.
856 return activeTurnId !== null ? "running" : "ready";
857 }
858 })();
859 const lastError =
860 event.type === "session.state.changed" && event.payload.state === "error"
861 ? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error")
862 : event.type === "turn.completed" && runtimeTurnState(event) === "failed"
863 ? (runtimeTurnErrorMessage(event) ?? thread.session?.lastError ?? "Turn failed")
864 : status === "ready"
865 ? null
866 : (thread.session?.lastError ?? null);
867
868 if (shouldApplyThreadLifecycle) {
869 yield* orchestrationEngine.dispatch({
870 type: "thread.session.set",
871 commandId: providerCommandId(event, "thread-session-set"),
872 threadId: thread.id,
873 session: {
874 threadId: thread.id,
875 status,
876 providerName: event.provider,
877 runtimeMode: thread.session?.runtimeMode ?? "full-access",
878 activeTurnId: nextActiveTurnId,
879 lastError,
880 updatedAt: now,
881 },
882 createdAt: now,
883 });
884 }
885 }
886
887 const assistantDelta =
888 event.type === "content.delta" && event.payload.streamKind === "assistant_text"
889 ? event.payload.delta
890 : undefined;
891 const proposedPlanDelta =
892 event.type === "turn.proposed.delta" ? event.payload.delta : undefined;
893
894 if (assistantDelta && assistantDelta.length > 0) {
895 const assistantMessageId = MessageId.makeUnsafe(
896 `assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
897 );
898 const turnId = toTurnId(event.turnId);
899 if (turnId) {
900 yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
901 }
902
903 const assistantDeliveryMode = yield* Ref.get(assistantDeliveryModeRef);
904 if (assistantDeliveryMode === "buffered") {
905 const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
906 if (spillChunk.length > 0) {
907 yield* orchestrationEngine.dispatch({
908 type: "thread.message.assistant.delta",
909 commandId: providerCommandId(event, "assistant-delta-buffer-spill"),
910 threadId: thread.id,
911 messageId: assistantMessageId,
912 delta: spillChunk,
913 ...(turnId ? { turnId } : {}),
914 createdAt: now,
915 });
916 }
917 } else {
918 yield* orchestrationEngine.dispatch({
919 type: "thread.message.assistant.delta",
920 commandId: providerCommandId(event, "assistant-delta"),
921 threadId: thread.id,
922 messageId: assistantMessageId,
923 delta: assistantDelta,
924 ...(turnId ? { turnId } : {}),
925 createdAt: now,
926 });
927 }
928 }
929
930 if (proposedPlanDelta && proposedPlanDelta.length > 0) {
931 const planId = proposedPlanIdFromEvent(event, thread.id);
932 yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now);
933 }
934
935 const assistantCompletion =
936 event.type === "item.completed" && event.payload.itemType === "assistant_message"
937 ? {
938 messageId: MessageId.makeUnsafe(`assistant:${event.itemId ?? event.turnId ?? event.eventId}`),
939 fallbackText: event.payload.detail,
940 }
941 : undefined;
942 const proposedPlanCompletion =
943 event.type === "turn.proposed.completed"
944 ? {
945 planId: proposedPlanIdFromEvent(event, thread.id),
946 turnId: toTurnId(event.turnId),
947 planMarkdown: event.payload.planMarkdown,
948 }
949 : undefined;
950
951 if (assistantCompletion) {
952 const assistantMessageId = assistantCompletion.messageId;
953 const turnId = toTurnId(event.turnId);
954 if (turnId) {
955 yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
956 }
957
958 yield* finalizeAssistantMessage({
959 event,
960 threadId: thread.id,
961 messageId: assistantMessageId,
962 ...(turnId ? { turnId } : {}),
963 createdAt: now,
964 commandTag: "assistant-complete",
965 finalDeltaCommandTag: "assistant-delta-finalize",
966 ...(assistantCompletion.fallbackText !== undefined
967 ? { fallbackText: assistantCompletion.fallbackText }
968 : {}),
969 });
970
971 if (turnId) {
972 yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId);
973 }
974 }
975
976 if (proposedPlanCompletion) {
977 yield* finalizeBufferedProposedPlan({
978 event,
979 threadId: thread.id,
980 threadProposedPlans: thread.proposedPlans,
981 planId: proposedPlanCompletion.planId,
982 ...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
983 fallbackMarkdown: proposedPlanCompletion.planMarkdown,
984 updatedAt: now,
985 });
986 }
987
988 if (event.type === "turn.completed") {
989 const turnId = toTurnId(event.turnId);
990 if (turnId) {
991 const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
992 yield* Effect.forEach(
993 assistantMessageIds,
994 (assistantMessageId) =>
995 finalizeAssistantMessage({
996 event,
997 threadId: thread.id,
998 messageId: assistantMessageId,
999 turnId,
1000 createdAt: now,
1001 commandTag: "assistant-complete-finalize",
1002 finalDeltaCommandTag: "assistant-delta-finalize-fallback",
1003 }),
1004 { concurrency: 1 },
1005 ).pipe(Effect.asVoid);
1006 yield* clearAssistantMessageIdsForTurn(thread.id, turnId);
1007
1008 yield* finalizeBufferedProposedPlan({
1009 event,
1010 threadId: thread.id,
1011 threadProposedPlans: thread.proposedPlans,
1012 planId: proposedPlanIdForTurn(thread.id, turnId),
1013 turnId,
1014 updatedAt: now,
1015 });
1016 }
1017 }
1018
1019 if (event.type === "session.exited") {
1020 yield* clearTurnStateForSession(thread.id);
1021 }
1022
1023 if (event.type === "runtime.error") {
1024 const runtimeErrorMessage = runtimeErrorMessageFromEvent(event) ?? "Provider runtime error";
1025
1026 const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
1027 ? true
1028 : activeTurnId === null ||
1029 eventTurnId === undefined ||
1030 sameId(activeTurnId, eventTurnId);
1031
1032 if (shouldApplyRuntimeError) {
1033 yield* orchestrationEngine.dispatch({
1034 type: "thread.session.set",
1035 commandId: providerCommandId(event, "runtime-error-session-set"),
1036 threadId: thread.id,
1037 session: {
1038 threadId: thread.id,
1039 status: "error",
1040 providerName: event.provider,
1041 runtimeMode: thread.session?.runtimeMode ?? "full-access",
1042 activeTurnId: eventTurnId ?? null,
1043 lastError: runtimeErrorMessage,
1044 updatedAt: now,
1045 },
1046 createdAt: now,
1047 });
1048 }
1049 }
1050
1051 if (event.type === "thread.metadata.updated" && event.payload.name) {
1052 yield* orchestrationEngine.dispatch({
1053 type: "thread.meta.update",
1054 commandId: providerCommandId(event, "thread-meta-update"),
1055 threadId: thread.id,
1056 title: event.payload.name,
1057 });
1058 }
1059
1060 if (event.type === "turn.diff.updated") {
1061 const turnId = toTurnId(event.turnId);
1062 if (turnId && (yield* isGitRepoForThread(thread.id))) {
1063 const assistantMessageId = MessageId.makeUnsafe(
1064 `assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
1065 );
1066 yield* orchestrationEngine.dispatch({
1067 type: "thread.turn.diff.complete",
1068 commandId: providerCommandId(event, "thread-turn-diff-complete"),
1069 threadId: thread.id,
1070 turnId,
1071 completedAt: now,
1072 checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`),
1073 status: "missing",
1074 files: [],
1075 assistantMessageId,
1076 checkpointTurnCount: thread.checkpoints.length + 1,
1077 createdAt: now,
1078 });
1079 }
1080 }
1081
1082 const activities = runtimeEventToActivities(event);
1083 yield* Effect.forEach(activities, (activity) =>
1084 orchestrationEngine.dispatch({
1085 type: "thread.activity.append",
1086 commandId: providerCommandId(event, "thread-activity-append"),
1087 threadId: thread.id,
1088 activity,
1089 createdAt: activity.createdAt,
1090 }),
1091 ).pipe(Effect.asVoid);
1092 });
1093
1094 const processDomainEvent = (event: TurnStartRequestedDomainEvent) =>
1095 Ref.set(
1096 assistantDeliveryModeRef,
1097 event.payload.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
1098 );
1099
1100 const processInput = (input: RuntimeIngestionInput) =>
1101 input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);
1102
1103 const processInputSafely = (input: RuntimeIngestionInput) =>
1104 processInput(input).pipe(
1105 Effect.catchCause((cause) => {
1106 if (Cause.hasInterruptsOnly(cause)) {
1107 return Effect.failCause(cause);
1108 }
1109 return Effect.logWarning("provider runtime ingestion failed to process event", {
1110 source: input.source,
1111 eventId: input.event.eventId,
1112 eventType: input.event.type,
1113 cause: Cause.pretty(cause),
1114 });
1115 }),
1116 );
1117
1118 const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () {
1119 const inputQueue = yield* Queue.unbounded<RuntimeIngestionInput>();
1120 yield* Effect.addFinalizer(() => Queue.shutdown(inputQueue).pipe(Effect.asVoid));
1121
1122 yield* Effect.forkScoped(
1123 Effect.forever(Queue.take(inputQueue).pipe(Effect.flatMap(processInputSafely))),
1124 );
1125 yield* Effect.forkScoped(
1126 Stream.runForEach(providerService.streamEvents, (event) =>
1127 Queue.offer(inputQueue, { source: "runtime", event }).pipe(Effect.asVoid),
1128 ),
1129 );
1130 yield* Effect.forkScoped(
1131 Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
1132 if (event.type !== "thread.turn-start-requested") {
1133 return Effect.void;
1134 }
1135 return Queue.offer(inputQueue, { source: "domain", event }).pipe(Effect.asVoid);
1136 }),
1137 );
1138 });
1139
1140 return {
1141 start,
1142 } satisfies ProviderRuntimeIngestionShape;
1143});
1144
1145export const ProviderRuntimeIngestionLive = Layer.effect(ProviderRuntimeIngestionService, make);