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