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.make(`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.make(String(value));
61}
62
63function toApprovalRequestId(value: string | undefined): ApprovalRequestId | undefined {
64 return value === undefined ? undefined : ApprovalRequestId.make(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 ...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
469 },
470 turnId: toTurnId(event.turnId) ?? null,
471 ...maybeSequence,
472 },
473 ];
474 }
475
476 case "item.started": {
477 if (!isToolLifecycleItemType(event.payload.itemType)) {
478 return [];
479 }
480 return [
481 {
482 id: event.eventId,
483 createdAt: event.createdAt,
484 tone: "tool",
485 kind: "tool.started",
486 summary: `${event.payload.title ?? "Tool"} started`,
487 payload: {
488 itemType: event.payload.itemType,
489 ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
490 },
491 turnId: toTurnId(event.turnId) ?? null,
492 ...maybeSequence,
493 },
494 ];
495 }
496
497 default:
498 break;
499 }
500
501 return [];
502}
503
504const make = Effect.fn("make")(function* () {
505 const orchestrationEngine = yield* OrchestrationEngineService;
506 const providerService = yield* ProviderService;
507 const projectionTurnRepository = yield* ProjectionTurnRepository;
508 const serverSettingsService = yield* ServerSettingsService;
509
510 const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
511 capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
512 timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
513 lookup: () => Effect.succeed(new Set<MessageId>()),
514 });
515
516 const bufferedAssistantTextByMessageId = yield* Cache.make<MessageId, string>({
517 capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY,
518 timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL,
519 lookup: () => Effect.succeed(""),
520 });
521
522 const bufferedProposedPlanById = yield* Cache.make<string, { text: string; createdAt: string }>({
523 capacity: BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY,
524 timeToLive: BUFFERED_PROPOSED_PLAN_BY_ID_TTL,
525 lookup: () => Effect.succeed({ text: "", createdAt: "" }),
526 });
527
528 const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) {
529 const readModel = yield* orchestrationEngine.getReadModel();
530 const thread = readModel.threads.find((entry) => entry.id === threadId);
531 if (!thread) {
532 return false;
533 }
534 const workspaceCwd = resolveThreadWorkspaceCwd({
535 thread,
536 projects: readModel.projects,
537 });
538 if (!workspaceCwd) {
539 return false;
540 }
541 return isGitRepository(workspaceCwd);
542 });
543
544 const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
545 Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(
546 Effect.flatMap((existingIds) =>
547 Cache.set(
548 turnMessageIdsByTurnKey,
549 providerTurnKey(threadId, turnId),
550 Option.match(existingIds, {
551 onNone: () => new Set([messageId]),
552 onSome: (ids) => {
553 const nextIds = new Set(ids);
554 nextIds.add(messageId);
555 return nextIds;
556 },
557 }),
558 ),
559 ),
560 );
561
562 const forgetAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
563 Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(
564 Effect.flatMap((existingIds) =>
565 Option.match(existingIds, {
566 onNone: () => Effect.void,
567 onSome: (ids) => {
568 const nextIds = new Set(ids);
569 nextIds.delete(messageId);
570 if (nextIds.size === 0) {
571 return Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));
572 }
573 return Cache.set(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId), nextIds);
574 },
575 }),
576 ),
577 );
578
579 const getAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) =>
580 Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(
581 Effect.map((existingIds) =>
582 Option.getOrElse(existingIds, (): Set<MessageId> => new Set<MessageId>()),
583 ),
584 );
585
586 const clearAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) =>
587 Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));
588
589 const appendBufferedAssistantText = (messageId: MessageId, delta: string) =>
590 Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
591 Effect.flatMap(
592 Effect.fn("appendBufferedAssistantText")(function* (existingText) {
593 const nextText = Option.match(existingText, {
594 onNone: () => delta,
595 onSome: (text) => `${text}${delta}`,
596 });
597 if (nextText.length <= MAX_BUFFERED_ASSISTANT_CHARS) {
598 yield* Cache.set(bufferedAssistantTextByMessageId, messageId, nextText);
599 return "";
600 }
601
602 // Safety valve: flush full buffered text as an assistant delta to cap memory.
603 yield* Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
604 return nextText;
605 }),
606 ),
607 );
608
609 const takeBufferedAssistantText = (messageId: MessageId) =>
610 Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
611 Effect.flatMap((existingText) =>
612 Cache.invalidate(bufferedAssistantTextByMessageId, messageId).pipe(
613 Effect.as(Option.getOrElse(existingText, () => "")),
614 ),
615 ),
616 );
617
618 const clearBufferedAssistantText = (messageId: MessageId) =>
619 Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
620
621 const appendBufferedProposedPlan = (planId: string, delta: string, createdAt: string) =>
622 Cache.getOption(bufferedProposedPlanById, planId).pipe(
623 Effect.flatMap((existingEntry) => {
624 const existing = Option.getOrUndefined(existingEntry);
625 return Cache.set(bufferedProposedPlanById, planId, {
626 text: `${existing?.text ?? ""}${delta}`,
627 createdAt:
628 existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt,
629 });
630 }),
631 );
632
633 const takeBufferedProposedPlan = (planId: string) =>
634 Cache.getOption(bufferedProposedPlanById, planId).pipe(
635 Effect.flatMap((existingEntry) =>
636 Cache.invalidate(bufferedProposedPlanById, planId).pipe(
637 Effect.as(Option.getOrUndefined(existingEntry)),
638 ),
639 ),
640 );
641
642 const clearBufferedProposedPlan = (planId: string) =>
643 Cache.invalidate(bufferedProposedPlanById, planId);
644
645 const clearAssistantMessageState = (messageId: MessageId) =>
646 clearBufferedAssistantText(messageId);
647
648 const finalizeAssistantMessage = Effect.fn("finalizeAssistantMessage")(function* (input: {
649 event: ProviderRuntimeEvent;
650 threadId: ThreadId;
651 messageId: MessageId;
652 turnId?: TurnId;
653 createdAt: string;
654 commandTag: string;
655 finalDeltaCommandTag: string;
656 fallbackText?: string;
657 }) {
658 const bufferedText = yield* takeBufferedAssistantText(input.messageId);
659 const text =
660 bufferedText.length > 0
661 ? bufferedText
662 : (input.fallbackText?.trim().length ?? 0) > 0
663 ? input.fallbackText!
664 : "";
665
666 if (text.length > 0) {
667 yield* orchestrationEngine.dispatch({
668 type: "thread.message.assistant.delta",
669 commandId: providerCommandId(input.event, input.finalDeltaCommandTag),
670 threadId: input.threadId,
671 messageId: input.messageId,
672 delta: text,
673 ...(input.turnId ? { turnId: input.turnId } : {}),
674 createdAt: input.createdAt,
675 });
676 }
677
678 yield* orchestrationEngine.dispatch({
679 type: "thread.message.assistant.complete",
680 commandId: providerCommandId(input.event, input.commandTag),
681 threadId: input.threadId,
682 messageId: input.messageId,
683 ...(input.turnId ? { turnId: input.turnId } : {}),
684 createdAt: input.createdAt,
685 });
686 yield* clearAssistantMessageState(input.messageId);
687 });
688
689 const upsertProposedPlan = Effect.fn("upsertProposedPlan")(function* (input: {
690 event: ProviderRuntimeEvent;
691 threadId: ThreadId;
692 threadProposedPlans: ReadonlyArray<{
693 id: string;
694 createdAt: string;
695 implementedAt: string | null;
696 implementationThreadId: ThreadId | null;
697 }>;
698 planId: string;
699 turnId?: TurnId;
700 planMarkdown: string | undefined;
701 createdAt: string;
702 updatedAt: string;
703 }) {
704 const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown);
705 if (!planMarkdown) {
706 return;
707 }
708
709 const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId);
710 yield* orchestrationEngine.dispatch({
711 type: "thread.proposed-plan.upsert",
712 commandId: providerCommandId(input.event, "proposed-plan-upsert"),
713 threadId: input.threadId,
714 proposedPlan: {
715 id: input.planId,
716 turnId: input.turnId ?? null,
717 planMarkdown,
718 implementedAt: existingPlan?.implementedAt ?? null,
719 implementationThreadId: existingPlan?.implementationThreadId ?? null,
720 createdAt: existingPlan?.createdAt ?? input.createdAt,
721 updatedAt: input.updatedAt,
722 },
723 createdAt: input.updatedAt,
724 });
725 });
726
727 const finalizeBufferedProposedPlan = Effect.fn("finalizeBufferedProposedPlan")(function* (input: {
728 event: ProviderRuntimeEvent;
729 threadId: ThreadId;
730 threadProposedPlans: ReadonlyArray<{
731 id: string;
732 createdAt: string;
733 implementedAt: string | null;
734 implementationThreadId: ThreadId | null;
735 }>;
736 planId: string;
737 turnId?: TurnId;
738 fallbackMarkdown?: string;
739 updatedAt: string;
740 }) {
741 const bufferedPlan = yield* takeBufferedProposedPlan(input.planId);
742 const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text);
743 const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown);
744 const planMarkdown = bufferedMarkdown ?? fallbackMarkdown;
745 if (!planMarkdown) {
746 return;
747 }
748
749 yield* upsertProposedPlan({
750 event: input.event,
751 threadId: input.threadId,
752 threadProposedPlans: input.threadProposedPlans,
753 planId: input.planId,
754 ...(input.turnId ? { turnId: input.turnId } : {}),
755 planMarkdown,
756 createdAt:
757 bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0
758 ? bufferedPlan.createdAt
759 : input.updatedAt,
760 updatedAt: input.updatedAt,
761 });
762 yield* clearBufferedProposedPlan(input.planId);
763 });
764
765 const clearTurnStateForSession = Effect.fn("clearTurnStateForSession")(function* (
766 threadId: ThreadId,
767 ) {
768 const prefix = `${threadId}:`;
769 const proposedPlanPrefix = `plan:${threadId}:`;
770 const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey));
771 const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById));
772 yield* Effect.forEach(
773 turnKeys,
774 Effect.fn(function* (key) {
775 if (!key.startsWith(prefix)) {
776 return;
777 }
778
779 const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key);
780 if (Option.isSome(messageIds)) {
781 yield* Effect.forEach(messageIds.value, clearAssistantMessageState, {
782 concurrency: 1,
783 }).pipe(Effect.asVoid);
784 }
785
786 yield* Cache.invalidate(turnMessageIdsByTurnKey, key);
787 }),
788 { concurrency: 1 },
789 ).pipe(Effect.asVoid);
790 yield* Effect.forEach(
791 proposedPlanKeys,
792 (key) =>
793 key.startsWith(proposedPlanPrefix)
794 ? Cache.invalidate(bufferedProposedPlanById, key)
795 : Effect.void,
796 { concurrency: 1 },
797 ).pipe(Effect.asVoid);
798 });
799
800 const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn(
801 "getSourceProposedPlanReferenceForPendingTurnStart",
802 )(function* (threadId: ThreadId) {
803 const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
804 threadId,
805 });
806 if (Option.isNone(pendingTurnStart)) {
807 return null;
808 }
809
810 const sourceThreadId = pendingTurnStart.value.sourceProposedPlanThreadId;
811 const sourcePlanId = pendingTurnStart.value.sourceProposedPlanId;
812 if (sourceThreadId === null || sourcePlanId === null) {
813 return null;
814 }
815
816 return {
817 sourceThreadId,
818 sourcePlanId,
819 } as const;
820 });
821
822 const getExpectedProviderTurnIdForThread = Effect.fn("getExpectedProviderTurnIdForThread")(
823 function* (threadId: ThreadId) {
824 const sessions = yield* providerService.listSessions();
825 const session = sessions.find((entry) => entry.threadId === threadId);
826 return session?.activeTurnId;
827 },
828 );
829
830 const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fn(
831 "getSourceProposedPlanReferenceForAcceptedTurnStart",
832 )(function* (threadId: ThreadId, eventTurnId: TurnId | undefined) {
833 if (eventTurnId === undefined) {
834 return null;
835 }
836
837 const expectedTurnId = yield* getExpectedProviderTurnIdForThread(threadId);
838 if (!sameId(expectedTurnId, eventTurnId)) {
839 return null;
840 }
841
842 return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId);
843 });
844
845 const markSourceProposedPlanImplemented = Effect.fn("markSourceProposedPlanImplemented")(
846 function* (
847 sourceThreadId: ThreadId,
848 sourcePlanId: OrchestrationProposedPlanId,
849 implementationThreadId: ThreadId,
850 implementedAt: string,
851 ) {
852 const readModel = yield* orchestrationEngine.getReadModel();
853 const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
854 const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
855 if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
856 return;
857 }
858
859 yield* orchestrationEngine.dispatch({
860 type: "thread.proposed-plan.upsert",
861 commandId: CommandId.make(
862 `provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
863 ),
864 threadId: sourceThread.id,
865 proposedPlan: {
866 ...sourcePlan,
867 implementedAt,
868 implementationThreadId,
869 updatedAt: implementedAt,
870 },
871 createdAt: implementedAt,
872 });
873 },
874 );
875
876 const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
877 event: ProviderRuntimeEvent,
878 ) {
879 const readModel = yield* orchestrationEngine.getReadModel();
880 const thread = readModel.threads.find((entry) => entry.id === event.threadId);
881 if (!thread) return;
882
883 const now = event.createdAt;
884 const eventTurnId = toTurnId(event.turnId);
885 const activeTurnId = thread.session?.activeTurnId ?? null;
886
887 const conflictsWithActiveTurn =
888 activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
889 const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
890
891 const shouldApplyThreadLifecycle = (() => {
892 if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
893 return true;
894 }
895 switch (event.type) {
896 case "session.exited":
897 return true;
898 case "session.started":
899 case "thread.started":
900 return true;
901 case "turn.started":
902 return !conflictsWithActiveTurn;
903 case "turn.completed":
904 if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
905 return false;
906 }
907 // Only the active turn may close the lifecycle state.
908 if (activeTurnId !== null && eventTurnId !== undefined) {
909 return sameId(activeTurnId, eventTurnId);
910 }
911 // If no active turn is tracked, accept completion scoped to this thread.
912 return true;
913 default:
914 return true;
915 }
916 })();
917 const acceptedTurnStartedSourcePlan =
918 event.type === "turn.started" && shouldApplyThreadLifecycle
919 ? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)
920 : null;
921
922 if (
923 event.type === "session.started" ||
924 event.type === "session.state.changed" ||
925 event.type === "session.exited" ||
926 event.type === "thread.started" ||
927 event.type === "turn.started" ||
928 event.type === "turn.completed"
929 ) {
930 const nextActiveTurnId =
931 event.type === "turn.started"
932 ? (eventTurnId ?? null)
933 : event.type === "turn.completed" || event.type === "session.exited"
934 ? null
935 : activeTurnId;
936 const status = (() => {
937 switch (event.type) {
938 case "session.state.changed":
939 return orchestrationSessionStatusFromRuntimeState(event.payload.state);
940 case "turn.started":
941 return "running";
942 case "session.exited":
943 return "stopped";
944 case "turn.completed":
945 return normalizeRuntimeTurnState(event.payload.state) === "failed" ? "error" : "ready";
946 case "session.started":
947 case "thread.started":
948 // Provider thread/session start notifications can arrive during an
949 // active turn; preserve turn-running state in that case.
950 return activeTurnId !== null ? "running" : "ready";
951 }
952 })();
953 const lastError =
954 event.type === "session.state.changed" && event.payload.state === "error"
955 ? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error")
956 : event.type === "turn.completed" &&
957 normalizeRuntimeTurnState(event.payload.state) === "failed"
958 ? (event.payload.errorMessage ?? thread.session?.lastError ?? "Turn failed")
959 : status === "ready"
960 ? null
961 : (thread.session?.lastError ?? null);
962
963 if (shouldApplyThreadLifecycle) {
964 if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) {
965 yield* markSourceProposedPlanImplemented(
966 acceptedTurnStartedSourcePlan.sourceThreadId,
967 acceptedTurnStartedSourcePlan.sourcePlanId,
968 thread.id,
969 now,
970 ).pipe(
971 Effect.catchCause((cause) =>
972 Effect.logWarning("provider runtime ingestion failed to mark source proposed plan", {
973 eventId: event.eventId,
974 eventType: event.type,
975 cause: Cause.pretty(cause),
976 }),
977 ),
978 );
979 }
980
981 yield* orchestrationEngine.dispatch({
982 type: "thread.session.set",
983 commandId: providerCommandId(event, "thread-session-set"),
984 threadId: thread.id,
985 session: {
986 threadId: thread.id,
987 status,
988 providerName: event.provider,
989 runtimeMode: thread.session?.runtimeMode ?? "full-access",
990 activeTurnId: nextActiveTurnId,
991 lastError,
992 updatedAt: now,
993 },
994 createdAt: now,
995 });
996 }
997 }
998
999 const assistantDelta =
1000 event.type === "content.delta" && event.payload.streamKind === "assistant_text"
1001 ? event.payload.delta
1002 : undefined;
1003 const proposedPlanDelta =
1004 event.type === "turn.proposed.delta" ? event.payload.delta : undefined;
1005
1006 if (assistantDelta && assistantDelta.length > 0) {
1007 const assistantMessageId = MessageId.make(
1008 `assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
1009 );
1010 const turnId = toTurnId(event.turnId);
1011 if (turnId) {
1012 yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
1013 }
1014
1015 const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
1016 serverSettingsService.getSettings,
1017 (settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
1018 );
1019 if (assistantDeliveryMode === "buffered") {
1020 const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
1021 if (spillChunk.length > 0) {
1022 yield* orchestrationEngine.dispatch({
1023 type: "thread.message.assistant.delta",
1024 commandId: providerCommandId(event, "assistant-delta-buffer-spill"),
1025 threadId: thread.id,
1026 messageId: assistantMessageId,
1027 delta: spillChunk,
1028 ...(turnId ? { turnId } : {}),
1029 createdAt: now,
1030 });
1031 }
1032 } else {
1033 yield* orchestrationEngine.dispatch({
1034 type: "thread.message.assistant.delta",
1035 commandId: providerCommandId(event, "assistant-delta"),
1036 threadId: thread.id,
1037 messageId: assistantMessageId,
1038 delta: assistantDelta,
1039 ...(turnId ? { turnId } : {}),
1040 createdAt: now,
1041 });
1042 }
1043 }
1044
1045 if (proposedPlanDelta && proposedPlanDelta.length > 0) {
1046 const planId = proposedPlanIdFromEvent(event, thread.id);
1047 yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now);
1048 }
1049
1050 const assistantCompletion =
1051 event.type === "item.completed" && event.payload.itemType === "assistant_message"
1052 ? {
1053 messageId: MessageId.make(`assistant:${event.itemId ?? event.turnId ?? event.eventId}`),
1054 fallbackText: event.payload.detail,
1055 }
1056 : undefined;
1057 const proposedPlanCompletion =
1058 event.type === "turn.proposed.completed"
1059 ? {
1060 planId: proposedPlanIdFromEvent(event, thread.id),
1061 turnId: toTurnId(event.turnId),
1062 planMarkdown: event.payload.planMarkdown,
1063 }
1064 : undefined;
1065
1066 if (assistantCompletion) {
1067 const assistantMessageId = assistantCompletion.messageId;
1068 const turnId = toTurnId(event.turnId);
1069 const existingAssistantMessage = thread.messages.find(
1070 (entry) => entry.id === assistantMessageId,
1071 );
1072 const shouldApplyFallbackCompletionText =
1073 !existingAssistantMessage || existingAssistantMessage.text.length === 0;
1074 if (turnId) {
1075 yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
1076 }
1077
1078 yield* finalizeAssistantMessage({
1079 event,
1080 threadId: thread.id,
1081 messageId: assistantMessageId,
1082 ...(turnId ? { turnId } : {}),
1083 createdAt: now,
1084 commandTag: "assistant-complete",
1085 finalDeltaCommandTag: "assistant-delta-finalize",
1086 ...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText
1087 ? { fallbackText: assistantCompletion.fallbackText }
1088 : {}),
1089 });
1090
1091 if (turnId) {
1092 yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId);
1093 }
1094 }
1095
1096 if (proposedPlanCompletion) {
1097 yield* finalizeBufferedProposedPlan({
1098 event,
1099 threadId: thread.id,
1100 threadProposedPlans: thread.proposedPlans,
1101 planId: proposedPlanCompletion.planId,
1102 ...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
1103 fallbackMarkdown: proposedPlanCompletion.planMarkdown,
1104 updatedAt: now,
1105 });
1106 }
1107
1108 if (event.type === "turn.completed") {
1109 const turnId = toTurnId(event.turnId);
1110 if (turnId) {
1111 const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
1112 yield* Effect.forEach(
1113 assistantMessageIds,
1114 (assistantMessageId) =>
1115 finalizeAssistantMessage({
1116 event,
1117 threadId: thread.id,
1118 messageId: assistantMessageId,
1119 turnId,
1120 createdAt: now,
1121 commandTag: "assistant-complete-finalize",
1122 finalDeltaCommandTag: "assistant-delta-finalize-fallback",
1123 }),
1124 { concurrency: 1 },
1125 ).pipe(Effect.asVoid);
1126 yield* clearAssistantMessageIdsForTurn(thread.id, turnId);
1127
1128 yield* finalizeBufferedProposedPlan({
1129 event,
1130 threadId: thread.id,
1131 threadProposedPlans: thread.proposedPlans,
1132 planId: proposedPlanIdForTurn(thread.id, turnId),
1133 turnId,
1134 updatedAt: now,
1135 });
1136 }
1137 }
1138
1139 if (event.type === "session.exited") {
1140 yield* clearTurnStateForSession(thread.id);
1141 }
1142
1143 if (event.type === "runtime.error") {
1144 const runtimeErrorMessage = event.payload.message;
1145
1146 const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
1147 ? true
1148 : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId);
1149
1150 if (shouldApplyRuntimeError) {
1151 yield* orchestrationEngine.dispatch({
1152 type: "thread.session.set",
1153 commandId: providerCommandId(event, "runtime-error-session-set"),
1154 threadId: thread.id,
1155 session: {
1156 threadId: thread.id,
1157 status: "error",
1158 providerName: event.provider,
1159 runtimeMode: thread.session?.runtimeMode ?? "full-access",
1160 activeTurnId: eventTurnId ?? null,
1161 lastError: runtimeErrorMessage,
1162 updatedAt: now,
1163 },
1164 createdAt: now,
1165 });
1166 }
1167 }
1168
1169 if (event.type === "thread.metadata.updated" && event.payload.name) {
1170 yield* orchestrationEngine.dispatch({
1171 type: "thread.meta.update",
1172 commandId: providerCommandId(event, "thread-meta-update"),
1173 threadId: thread.id,
1174 title: event.payload.name,
1175 });
1176 }
1177
1178 if (event.type === "turn.diff.updated") {
1179 const turnId = toTurnId(event.turnId);
1180 if (turnId && (yield* isGitRepoForThread(thread.id))) {
1181 // Skip if a checkpoint already exists for this turn. A real
1182 // (non-placeholder) capture from CheckpointReactor should not
1183 // be clobbered, and dispatching a duplicate placeholder for the
1184 // same turnId would produce an unstable checkpointTurnCount.
1185 if (thread.checkpoints.some((c) => c.turnId === turnId)) {
1186 // Already tracked; no-op.
1187 } else {
1188 const assistantMessageId = MessageId.make(
1189 `assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
1190 );
1191 const maxTurnCount = thread.checkpoints.reduce(
1192 (max, c) => Math.max(max, c.checkpointTurnCount),
1193 0,
1194 );
1195 yield* orchestrationEngine.dispatch({
1196 type: "thread.turn.diff.complete",
1197 commandId: providerCommandId(event, "thread-turn-diff-complete"),
1198 threadId: thread.id,
1199 turnId,
1200 completedAt: now,
1201 checkpointRef: CheckpointRef.make(`provider-diff:${event.eventId}`),
1202 status: "missing",
1203 files: [],
1204 assistantMessageId,
1205 checkpointTurnCount: maxTurnCount + 1,
1206 createdAt: now,
1207 });
1208 }
1209 }
1210 }
1211
1212 const activities = runtimeEventToActivities(event);
1213 yield* Effect.forEach(activities, (activity) =>
1214 orchestrationEngine.dispatch({
1215 type: "thread.activity.append",
1216 commandId: providerCommandId(event, "thread-activity-append"),
1217 threadId: thread.id,
1218 activity,
1219 createdAt: activity.createdAt,
1220 }),
1221 ).pipe(Effect.asVoid);
1222 });
1223
1224 const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void;
1225
1226 const processInput = (input: RuntimeIngestionInput) =>
1227 input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);
1228
1229 const processInputSafely = (input: RuntimeIngestionInput) =>
1230 processInput(input).pipe(
1231 Effect.catchCause((cause) => {
1232 if (Cause.hasInterruptsOnly(cause)) {
1233 return Effect.failCause(cause);
1234 }
1235 return Effect.logWarning("provider runtime ingestion failed to process event", {
1236 source: input.source,
1237 eventId: input.event.eventId,
1238 eventType: input.event.type,
1239 cause: Cause.pretty(cause),
1240 });
1241 }),
1242 );
1243
1244 const worker = yield* makeDrainableWorker(processInputSafely);
1245
1246 const start: ProviderRuntimeIngestionShape["start"] = Effect.fn("start")(function* () {
1247 yield* Effect.forkScoped(
1248 Stream.runForEach(providerService.streamEvents, (event) =>
1249 worker.enqueue({ source: "runtime", event }),
1250 ),
1251 );
1252 yield* Effect.forkScoped(
1253 Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
1254 if (event.type !== "thread.turn-start-requested") {
1255 return Effect.void;
1256 }
1257 return worker.enqueue({ source: "domain", event });
1258 }),
1259 );
1260 });
1261
1262 return {
1263 start,
1264 drain: worker.drain,
1265 } satisfies ProviderRuntimeIngestionShape;
1266});
1267
1268export const ProviderRuntimeIngestionLive = Layer.effect(
1269 ProviderRuntimeIngestionService,
1270 make(),
1271).pipe(Layer.provide(ProjectionTurnRepositoryLive));