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