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

ProviderContinuationService.ts

286 lines11.6 KB

1import { CommandId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Ref from "effect/Ref";
5​
6import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
7import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
8import * as ThreadManagementService from "./ThreadManagementService.ts";
9import { isUndeliveredMailboxSteer } from "./NotificationMailbox.ts";
10​
11const CONTINUATION_MESSAGE_TEXT = "Background task completed.";
12​
13function delegatedCompletionText(taskIds: ReadonlyArray<string>): string {
14 const taskList = taskIds.join(", ");
15 return taskIds.length === 1
16 ? `Delegated task ${taskList} reached a terminal state. Use task_status with taskId ${taskList} to read the result.`
17 : `Delegated tasks ${taskList} reached terminal states. Use task_status with each taskId to read the results.`;
19​
20function currentDelegatedCompletionDelivery(
21 projection: Pick<OrchestrationV2ThreadProjection, "messages" | "runs" | "providerTurns">,
22 completion: NonNullable<
23 ProviderContinuationRequests.ProviderContinuationRequest["delegatedCompletion"]
24 >,
25) {
26 const sourceRun = projection.runs.find((candidate) => candidate.id === completion.parentRunId);
27 const delivery = sourceRun?.delegatedCompletion?.delivery;
28 const alreadyDispatched = projection.messages.some(
29 (message) => message.id === completion.messageId,
30 );
31 if (
32 sourceRun?.delegatedCompletion?.disposition !== "open" ||
33 delivery === null ||
34 delivery === undefined ||
35 delivery.generation !== completion.generation ||
36 delivery.messageId !== completion.messageId ||
37 (alreadyDispatched && !isUndeliveredMailboxSteer(projection, completion.messageId))
38 ) {
39 return undefined;
40 }
41 return delivery;
43​
44function delegatedCompletionRetryKey(
45 request: ProviderContinuationRequests.ProviderContinuationRequest,
46 completion: NonNullable<
47 ProviderContinuationRequests.ProviderContinuationRequest["delegatedCompletion"]
48 >,
49): string {
50 return `${request.threadId}:${completion.parentRunId}:${completion.generation}:${completion.messageId}`;
52​
53export const layer = Layer.effectDiscard(
54 Effect.gen(function* () {
55 const ids = yield* IdAllocator.IdAllocatorV2;
56 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
57 const threads = yield* ThreadManagementService.ThreadManagementService;
58 const retryAttempts = yield* Ref.make(new Map<string, number>());
59​
60 const clearRetryAttempt = (key: string) =>
61 Ref.update(retryAttempts, (current) => {
62 if (!current.has(key)) return current;
63 const updated = new Map(current);
64 updated.delete(key);
65 return updated;
66 });
67​
68 const nextRetryDelay = (key: string) =>
69 Ref.modify(retryAttempts, (current) => {
70 const attempt = current.get(key) ?? 0;
71 const updated = new Map(current);
72 updated.set(key, attempt + 1);
73 return [Math.min(100 * 2 ** Math.min(attempt, 6), 5_000), updated] as const;
74 });
75​
76 const dispatchContinuation = Effect.fn("ProviderContinuationService.dispatchContinuation")(
77 function* (request: ProviderContinuationRequests.ProviderContinuationRequest) {
78 const projection = yield* threads.getThreadRecords(
79 request.threadId,
80 ["messages", "runs", "providerTurns"],
81 {
82 messageIds:
83 request.delegatedCompletion === undefined
84 ? []
85 : [request.delegatedCompletion.messageId],
86 },
87 );
88 if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) {
89 yield* Effect.logInfo("orchestration-v2.provider-continuation.thread-archived", {
90 threadId: request.threadId,
91 providerThreadId: request.providerThreadId,
92 });
93 if (request.delegatedCompletion !== undefined) {
94 yield* clearRetryAttempt(
95 delegatedCompletionRetryKey(request, request.delegatedCompletion),
96 );
97 }
98 if (request.clearIfCurrent !== undefined) {
99 yield* request.clearIfCurrent();
100 } else if (request.dispatchIfCurrent !== undefined) {
101 yield* request.dispatchIfCurrent(Effect.void);
102 }
103 return;
104 }
105 if (request.delegatedCompletion !== undefined) {
106 const retryKey = delegatedCompletionRetryKey(request, request.delegatedCompletion);
107 const delivery = currentDelegatedCompletionDelivery(
108 projection,
109 request.delegatedCompletion,
110 );
111 if (delivery === undefined) {
112 yield* clearRetryAttempt(retryKey);
113 return;
114 }
115 const commandId = yield* ids.allocate.command({
116 fixtureName: "delegated-completion",
117 commandName: "dispatch",
118 });
119 yield* threads
120 .dispatch({
121 type: "message.dispatch",
122 commandId,
123 threadId: request.threadId,
124 messageId: delivery.messageId,
125 text: delegatedCompletionText(delivery.taskIds),
126 attachments: [],
127 dispatchMode: { type: "queue_after_active" },
128 createdBy: "agent",
129 creationSource: "server",
130 delegatedCompletion: {
131 parentRunId: request.delegatedCompletion.parentRunId,
132 generation: delivery.generation,
133 taskIds: delivery.taskIds,
134 },
135 })
136 .pipe(
137 Effect.catchTags({
138 ThreadManagementProviderInstanceDisabledError: (error) =>
139 Effect.logInfo(
140 "orchestration-v2.provider-continuation.delegated-completion-disabled",
141 {
142 threadId: request.threadId,
143 projectId: error.projectId,
144 instanceId: error.instanceId,
145 },
146 ).pipe(
147 Effect.andThen(
148 Effect.forEach(
149 delivery.taskIds,
150 (taskId) =>
151 ids.allocate
152 .command({
153 fixtureName: "delegated-completion",
154 commandName: "dispose-disabled",
155 })
156 .pipe(
157 Effect.flatMap((disposeCommandId) =>
158 threads.dispatch({
159 type: "delegated_task.completion-delivery.dispose",
160 commandId: disposeCommandId,
161 parentThreadId: request.threadId,
162 taskId,
163 }),
164 ),
165 ),
166 { discard: true },
167 ),
168 ),
169 Effect.andThen(
170 request.clearIfCurrent !== undefined
171 ? request.clearIfCurrent()
172 : request.dispatchIfCurrent !== undefined
173 ? request.dispatchIfCurrent(Effect.void)
174 : Effect.void,
175 ),
176 ),
177 }),
178 );
179 yield* clearRetryAttempt(retryKey);
180 return;
181 }
182 const messageId =
183 request.messageId ??
184 (yield* ids.allocate.message({
185 threadId: request.threadId,
186 ordinal: projection.messages.length + 1,
187 }));
188 const commandId = CommandId.make(`provider-continuation:${messageId}`);
189 const dispatch = threads.dispatch({
190 type: "message.dispatch",
191 commandId,
192 threadId: request.threadId,
193 messageId,
194 text: request.detail ?? CONTINUATION_MESSAGE_TEXT,
195 notification: request.notification ?? {
196 source: { kind: "background_task" },
197 outcome: "updated",
198 summary: "Background activity updated",
199 },
200 attachments: [],
201 dispatchMode: { type: "queue_after_active" },
202 createdBy: "agent",
203 // Only buffered wakes use creationSource "provider"; Claude would drain an empty buffer instead of prompting message_text.
204 creationSource: request.delivery === "message_text" ? "server" : "provider",
205 });
206 // Catch after dispatchIfCurrent so adapters see raw failures first; clearIfCurrent is idempotent and covers others.
207 const logInstanceDisabled = (
208 error: ThreadManagementService.ThreadManagementProviderInstanceDisabledError,
209 ) =>
210 Effect.logInfo("orchestration-v2.provider-continuation.instance-disabled", {
211 threadId: request.threadId,
212 providerThreadId: request.providerThreadId,
213 projectId: error.projectId,
214 instanceId: error.instanceId,
215 }).pipe(
216 Effect.andThen(
217 request.clearIfCurrent !== undefined ? request.clearIfCurrent() : Effect.void,
218 ),
219 );
220 if (request.dispatchIfCurrent === undefined) {
221 yield* dispatch.pipe(
222 Effect.catchTags({
223 ThreadManagementProviderInstanceDisabledError: logInstanceDisabled,
224 }),
225 );
226 return;
227 }
228 yield* request.dispatchIfCurrent(dispatch).pipe(
229 Effect.catchTags({
230 ThreadManagementProviderInstanceDisabledError: logInstanceDisabled,
231 }),
232 );
233 },
234 );
235​
236 yield* requests.take.pipe(
237 Effect.flatMap((request) =>
238 dispatchContinuation(request).pipe(
239 Effect.catchCause((cause) =>
240 Effect.gen(function* () {
241 yield* Effect.logWarning("orchestration-v2.provider-continuation.dispatch-failed", {
242 threadId: request.threadId,
243 providerThreadId: request.providerThreadId,
244 cause,
245 });
246 if (request.delegatedCompletion !== undefined) {
247 const completion = request.delegatedCompletion;
248 const retryKey = delegatedCompletionRetryKey(request, completion);
249 const retryDelay = yield* nextRetryDelay(retryKey);
250 yield* Effect.gen(function* () {
251 yield* Effect.sleep(`${retryDelay} millis`);
252 const projection = yield* threads.getThreadRecords(
253 request.threadId,
254 ["messages", "runs", "providerTurns"],
255 {
256 messageIds:
257 request.delegatedCompletion === undefined
258 ? []
259 : [request.delegatedCompletion.messageId],
260 },
261 );
262 if (currentDelegatedCompletionDelivery(projection, completion) !== undefined) {
263 yield* requests.offer(request);
264 } else {
265 yield* clearRetryAttempt(retryKey);
266 }
267 }).pipe(
268 Effect.catchCause((retryCause) =>
269 Effect.logWarning("orchestration-v2.provider-continuation.retry-check-failed", {
270 threadId: request.threadId,
271 providerThreadId: request.providerThreadId,
272 cause: retryCause,
273 }).pipe(Effect.andThen(requests.offer(request))),
274 ),
275 Effect.forkScoped,
276 );
277 }
278 }),
279 ),
280 ),
281 ),
282 Effect.forever,
283 Effect.forkScoped,
284 );
285 }),
286);