Open History to see the last commit
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.`;
18}
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;
42}
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}`;
51}
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 // "provider" marks an adapter-buffered wake, which ClaudeAdapterV2
205 // detects to attach the buffered CLI output and drop this text. A
206 // message_text wake has no buffered output, so it must not carry that
207 // marker or the turn settles immediately having prompted nothing.
208 creationSource: request.delivery === "message_text" ? "server" : "provider",
209 });
210 // This catch sits outside dispatchIfCurrent so an adapter that clears
211 // its own sticky offer flag on dispatch failure (inside
212 // dispatchIfCurrent) observes the raw failure first. Not every adapter
213 // self-clears that way, so the explicit callback is called here too;
214 // clearIfCurrent implementations are idempotent, so a source that
215 // already cleared is unaffected.
216 const logInstanceDisabled = (
217 error: ThreadManagementService.ThreadManagementProviderInstanceDisabledError,
218 ) =>
219 Effect.logInfo("orchestration-v2.provider-continuation.instance-disabled", {
220 threadId: request.threadId,
221 providerThreadId: request.providerThreadId,
222 projectId: error.projectId,
223 instanceId: error.instanceId,
224 }).pipe(
225 Effect.andThen(
226 request.clearIfCurrent !== undefined ? request.clearIfCurrent() : Effect.void,
227 ),
228 );
229 if (request.dispatchIfCurrent === undefined) {
230 yield* dispatch.pipe(
231 Effect.catchTags({
232 ThreadManagementProviderInstanceDisabledError: logInstanceDisabled,
233 }),
234 );
235 return;
236 }
237 yield* request.dispatchIfCurrent(dispatch).pipe(
238 Effect.catchTags({
239 ThreadManagementProviderInstanceDisabledError: logInstanceDisabled,
240 }),
241 );
242 },
243 );
244
245 yield* requests.take.pipe(
246 Effect.flatMap((request) =>
247 dispatchContinuation(request).pipe(
248 Effect.catchCause((cause) =>
249 Effect.gen(function* () {
250 yield* Effect.logWarning("orchestration-v2.provider-continuation.dispatch-failed", {
251 threadId: request.threadId,
252 providerThreadId: request.providerThreadId,
253 cause,
254 });
255 if (request.delegatedCompletion !== undefined) {
256 const completion = request.delegatedCompletion;
257 const retryKey = delegatedCompletionRetryKey(request, completion);
258 const retryDelay = yield* nextRetryDelay(retryKey);
259 yield* Effect.gen(function* () {
260 yield* Effect.sleep(`${retryDelay} millis`);
261 const projection = yield* threads.getThreadRecords(
262 request.threadId,
263 ["messages", "runs", "providerTurns"],
264 {
265 messageIds:
266 request.delegatedCompletion === undefined
267 ? []
268 : [request.delegatedCompletion.messageId],
269 },
270 );
271 if (currentDelegatedCompletionDelivery(projection, completion) !== undefined) {
272 yield* requests.offer(request);
273 } else {
274 yield* clearRetryAttempt(retryKey);
275 }
276 }).pipe(
277 Effect.catchCause((retryCause) =>
278 Effect.logWarning("orchestration-v2.provider-continuation.retry-check-failed", {
279 threadId: request.threadId,
280 providerThreadId: request.providerThreadId,
281 cause: retryCause,
282 }).pipe(Effect.andThen(requests.offer(request))),
283 ),
284 Effect.forkScoped,
285 );
286 }
287 }),
288 ),
289 ),
290 ),
291 Effect.forever,
292 Effect.forkScoped,
293 );
294 }),
295);