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

ThreadDeletion.ts

215 lines7.3 KB

1import type {
2 OrchestrationV2Command,
3 OrchestrationV2DomainEvent,
4 OrchestrationV2ThreadProjection,
5} from "@t3tools/contracts";
6import type * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8​
9import type { PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";
10import type { IdAllocatorV2, IdAllocatorV2Error } from "./IdAllocator.ts";
11import { applyToProjection } from "./ProjectionStore.ts";
12​
13export interface ThreadDeletionPlan {
14 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
15 readonly effects: ReadonlyArray<PendingOrchestrationEffectV2>;
17​
18/** Plan the same durable cleanup for direct thread deletion and project removal. */
19export const planThreadDeletion = Effect.fn("ThreadDeletion.planThreadDeletion")(function* (input: {
20 readonly command: Extract<OrchestrationV2Command, { readonly type: "thread.delete" }>;
21 readonly projection: OrchestrationV2ThreadProjection;
22 readonly now: DateTime.Utc;
23 readonly idAllocator: IdAllocatorV2["Service"];
24}): Effect.fn.Return<ThreadDeletionPlan, IdAllocatorV2Error> {
25 const { command, projection, now, idAllocator } = input;
26 const events: Array<OrchestrationV2DomainEvent> = [];
27 const effects: Array<PendingOrchestrationEffectV2> = [];
28 let current = projection;
29 const emitEvent = Effect.fn("ThreadDeletion.emitEvent")(function* <
30 Event extends OrchestrationV2DomainEvent,
31 >(event: Omit<Event, "id">) {
32 const id = yield* idAllocator.allocate.event({
33 threadId: event.threadId,
34 commandId: command.commandId,
35 });
36 const withId = { ...event, id } as Event;
37 events.push(withId);
38 current = applyToProjection(current, withId);
39 });
40​
41 yield* emitEvent({
42 type: "thread.deleted",
43 threadId: command.threadId,
44 providerInstanceId: projection.thread.providerInstanceId,
45 occurredAt: now,
46 payload: {
47 ...projection.thread,
48 deletedAt: projection.thread.deletedAt ?? now,
49 titleRegeneration: null,
50 updatedAt: now,
51 },
52 });
53​
54 const activeRuns = projection.runs.filter((run) =>
55 ["preparing", "queued", "starting", "running", "waiting"].includes(run.status),
56 );
57 const activeRunById = new Map(activeRuns.map((run) => [run.id, run]));
58 for (const run of activeRuns) {
59 yield* emitEvent({
60 type: "run.updated",
61 threadId: command.threadId,
62 runId: run.id,
63 providerInstanceId: run.providerInstanceId,
64 occurredAt: now,
65 payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
66 });
67 }
68 for (const attempt of projection.attempts) {
69 const run = activeRunById.get(attempt.runId);
70 if (run === undefined || (attempt.status !== "pending" && attempt.status !== "running")) {
71 continue;
72 }
73 yield* emitEvent({
74 type: "run-attempt.updated",
75 threadId: command.threadId,
76 runId: attempt.runId,
77 nodeId: attempt.rootNodeId,
78 providerInstanceId: run.providerInstanceId,
79 occurredAt: now,
80 payload: { ...attempt, status: "cancelled", completedAt: now },
81 });
82 }
83 for (const node of projection.nodes) {
84 const run = node.runId === null ? undefined : activeRunById.get(node.runId);
85 if (run === undefined || !["pending", "running", "waiting"].includes(node.status)) {
86 continue;
87 }
88 yield* emitEvent({
89 type: "node.updated",
90 threadId: command.threadId,
91 runId: run.id,
92 nodeId: node.id,
93 providerInstanceId: run.providerInstanceId,
94 occurredAt: now,
95 payload: { ...node, status: "cancelled", completedAt: now },
96 });
97 }
98 for (const request of projection.runtimeRequests.filter(
99 (request) => request.status === "pending",
100 )) {
101 yield* emitEvent({
102 type: "runtime-request.updated",
103 threadId: command.threadId,
104 nodeId: request.nodeId,
105 occurredAt: now,
106 payload: {
107 ...request,
108 status: "cancelled",
109 responseCapability: { type: "not_resumable", reason: "The thread was deleted." },
110 resolvedAt: now,
111 },
112 });
113 }
114​
115 const cohortRunIds = new Set([
116 ...current.runs.filter((run) => run.delegatedCompletion !== undefined).map((run) => run.id),
117 ...current.subagents
118 .filter((task) => task.origin === "app_owned" && task.runId !== null)
119 .map((task) => task.runId!),
120 ]);
121 for (const parentRunId of cohortRunIds) {
122 // Use the projected cancellation so disposing a cohort cannot revive its run.
123 const parentRun = current.runs.find((run) => run.id === parentRunId);
124 if (parentRun === undefined) continue;
125 const cohort = parentRun.delegatedCompletion;
126 const tasks = current.subagents.filter(
127 (task) => task.origin === "app_owned" && task.runId === parentRunId,
128 );
129 yield* emitEvent({
130 type: "run.updated",
131 threadId: parentRun.threadId,
132 runId: parentRun.id,
133 ...(parentRun.rootNodeId === null ? {} : { nodeId: parentRun.rootNodeId }),
134 providerInstanceId: parentRun.providerInstanceId,
135 occurredAt: now,
136 payload: {
137 ...parentRun,
138 delegatedCompletion: {
139 disposition: "disposed",
140 nextGeneration: cohort?.nextGeneration ?? 1,
141 settledDeliveryCount: cohort?.settledDeliveryCount ?? 0,
142 delivery: null,
143 },
144 },
145 });
146 for (const task of tasks) {
147 if (
148 task.completionDelivery?.state === "acknowledged" ||
149 task.completionDelivery?.state === "delivered" ||
150 task.completionDelivery?.state === "disposed"
151 ) {
152 continue;
153 }
154 yield* emitEvent({
155 type: "subagent.updated",
156 threadId: parentRun.threadId,
157 ...(task.runId === null ? {} : { runId: task.runId }),
158 nodeId: task.id,
159 driver: task.driver,
160 providerInstanceId: task.providerInstanceId,
161 occurredAt: now,
162 payload: {
163 ...task,
164 completionDelivery: { state: "disposed", observedByRunId: null },
165 updatedAt: now,
166 },
167 });
168 }
169 }
170​
171 for (const session of projection.providerSessions) {
172 if (session.status === "stopped" || session.status === "error") continue;
173 yield* emitEvent({
174 type: "provider-session.detached",
175 threadId: command.threadId,
176 driver: session.driver,
177 providerInstanceId: session.providerInstanceId,
178 occurredAt: now,
179 payload: {
180 providerSessionId: session.id,
181 detachedAt: now,
182 reason: "Thread deleted.",
183 },
184 });
185 effects.push({
186 id: `effect:${command.commandId}:provider-session.detach:${session.id}`,
187 commandId: command.commandId,
188 threadId: command.threadId,
189 request: {
190 type: "provider-session.detach",
191 providerSessionId: session.id,
192 detail: "Thread deleted.",
193 revokeMcpCredential: true,
194 },
195 });
196 }
197 effects.push({
198 id: `effect:${command.commandId}:terminal.cleanup`,
199 commandId: command.commandId,
200 threadId: command.threadId,
201 request: { type: "terminal.cleanup" },
202 });
203 const attachmentIds = Array.from(
204 new Set(projection.messages.flatMap((message) => message.attachments.map((item) => item.id))),
205 );
206 if (attachmentIds.length > 0) {
207 effects.push({
208 id: `effect:${command.commandId}:attachment.cleanup`,
209 commandId: command.commandId,
210 threadId: command.threadId,
211 request: { type: "attachment.cleanup", attachmentIds },
212 });
213 }
214 return { events, effects };
215});