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

ProviderContinuationService.ts

287 lines11.7 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: "acknowledge-disabled",
155 })
156 .pipe(
157 Effect.flatMap((ackCommandId) =>
158 threads.dispatch({
159 type: "delegated_task.completion-delivery.acknowledge",
160 commandId: ackCommandId,
161 parentThreadId: request.threadId,
162 taskId,
163 observedByRunId: null,
164 }),
165 ),
166 ),
167 { discard: true },
168 ),
169 ),
170 Effect.andThen(
171 request.clearIfCurrent !== undefined
172 ? request.clearIfCurrent()
173 : request.dispatchIfCurrent !== undefined
174 ? request.dispatchIfCurrent(Effect.void)
175 : Effect.void,
176 ),
177 ),
178 }),
179 );
180 yield* clearRetryAttempt(retryKey);
181 return;
182 }
183 const messageId =
184 request.messageId ??
185 (yield* ids.allocate.message({
186 threadId: request.threadId,
187 ordinal: projection.messages.length + 1,
188 }));
189 const commandId = CommandId.make(`provider-continuation:${messageId}`);
190 const dispatch = threads.dispatch({
191 type: "message.dispatch",
192 commandId,
193 threadId: request.threadId,
194 messageId,
195 text: request.detail ?? CONTINUATION_MESSAGE_TEXT,
196 notification: request.notification ?? {
197 source: { kind: "background_task" },
198 outcome: "updated",
199 summary: "Background activity updated",
200 },
201 attachments: [],
202 dispatchMode: { type: "queue_after_active" },
203 createdBy: "agent",
204 // Only buffered wakes use creationSource "provider"; Claude would drain an empty buffer instead of prompting message_text.
205 creationSource: request.delivery === "message_text" ? "server" : "provider",
206 });
207 // Catch after dispatchIfCurrent so adapters see raw failures first; clearIfCurrent is idempotent and covers others.
208 const logInstanceDisabled = (
209 error: ThreadManagementService.ThreadManagementProviderInstanceDisabledError,
210 ) =>
211 Effect.logInfo("orchestration-v2.provider-continuation.instance-disabled", {
212 threadId: request.threadId,
213 providerThreadId: request.providerThreadId,
214 projectId: error.projectId,
215 instanceId: error.instanceId,
216 }).pipe(
217 Effect.andThen(
218 request.clearIfCurrent !== undefined ? request.clearIfCurrent() : Effect.void,
219 ),
220 );
221 if (request.dispatchIfCurrent === undefined) {
222 yield* dispatch.pipe(
223 Effect.catchTags({
224 ThreadManagementProviderInstanceDisabledError: logInstanceDisabled,
225 }),
226 );
227 return;
228 }
229 yield* request.dispatchIfCurrent(dispatch).pipe(
230 Effect.catchTags({
231 ThreadManagementProviderInstanceDisabledError: logInstanceDisabled,
232 }),
233 );
234 },
235 );
236​
237 yield* requests.take.pipe(
238 Effect.flatMap((request) =>
239 dispatchContinuation(request).pipe(
240 Effect.catchCause((cause) =>
241 Effect.gen(function* () {
242 yield* Effect.logWarning("orchestration-v2.provider-continuation.dispatch-failed", {
243 threadId: request.threadId,
244 providerThreadId: request.providerThreadId,
245 cause,
246 });
247 if (request.delegatedCompletion !== undefined) {
248 const completion = request.delegatedCompletion;
249 const retryKey = delegatedCompletionRetryKey(request, completion);
250 const retryDelay = yield* nextRetryDelay(retryKey);
251 yield* Effect.gen(function* () {
252 yield* Effect.sleep(`${retryDelay} millis`);
253 const projection = yield* threads.getThreadRecords(
254 request.threadId,
255 ["messages", "runs", "providerTurns"],
256 {
257 messageIds:
258 request.delegatedCompletion === undefined
259 ? []
260 : [request.delegatedCompletion.messageId],
261 },
262 );
263 if (currentDelegatedCompletionDelivery(projection, completion) !== undefined) {
264 yield* requests.offer(request);
265 } else {
266 yield* clearRetryAttempt(retryKey);
267 }
268 }).pipe(
269 Effect.catchCause((retryCause) =>
270 Effect.logWarning("orchestration-v2.provider-continuation.retry-check-failed", {
271 threadId: request.threadId,
272 providerThreadId: request.providerThreadId,
273 cause: retryCause,
274 }).pipe(Effect.andThen(requests.offer(request))),
275 ),
276 Effect.forkScoped,
277 );
278 }
279 }),
280 ),
281 ),
282 ),
283 Effect.forever,
284 Effect.forkScoped,
285 );
286 }),
287);