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
53/**
54 * Drains ProviderContinuationRequests and dispatches an internal
55 * message.dispatch per request so the wake turn buffered by the adapter is
56 * ingested as a normal run. Delegated completions are durable mailbox offers:
57 * the orchestrator selects native steering or queued delivery under its thread
58 * lock. Adapter-buffered continuations still queue behind active work.
59 */
60export const layer = Layer.effectDiscard(
61 Effect.gen(function* () {
62 const ids = yield* IdAllocator.IdAllocatorV2;
63 const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
64 const threads = yield* ThreadManagementService.ThreadManagementService;
65 const retryAttempts = yield* Ref.make(new Map<string, number>());
66
67 const clearRetryAttempt = (key: string) =>
68 Ref.update(retryAttempts, (current) => {
69 if (!current.has(key)) return current;
70 const updated = new Map(current);
71 updated.delete(key);
72 return updated;
73 });
74
75 const nextRetryDelay = (key: string) =>
76 Ref.modify(retryAttempts, (current) => {
77 const attempt = current.get(key) ?? 0;
78 const updated = new Map(current);
79 updated.set(key, attempt + 1);
80 return [Math.min(100 * 2 ** Math.min(attempt, 6), 5_000), updated] as const;
81 });
82
83 const dispatchContinuation = Effect.fn("ProviderContinuationService.dispatchContinuation")(
84 function* (request: ProviderContinuationRequests.ProviderContinuationRequest) {
85 const projection = yield* threads.getThreadRecords(
86 request.threadId,
87 ["messages", "runs", "providerTurns"],
88 {
89 messageIds:
90 request.delegatedCompletion === undefined
91 ? []
92 : [request.delegatedCompletion.messageId],
93 },
94 );
95 if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) {
96 yield* Effect.logInfo("orchestration-v2.provider-continuation.thread-archived", {
97 threadId: request.threadId,
98 providerThreadId: request.providerThreadId,
99 });
100 if (request.delegatedCompletion !== undefined) {
101 yield* clearRetryAttempt(
102 delegatedCompletionRetryKey(request, request.delegatedCompletion),
103 );
104 }
105 // No continuation turn will start to clear the adapter's sticky offer.
106 if (request.clearIfCurrent !== undefined) {
107 yield* request.clearIfCurrent();
108 } else if (request.dispatchIfCurrent !== undefined) {
109 // Backward compatibility for request producers without an explicit
110 // drop callback.
111 yield* request.dispatchIfCurrent(Effect.void);
112 }
113 return;
114 }
115 if (request.delegatedCompletion !== undefined) {
116 const retryKey = delegatedCompletionRetryKey(request, request.delegatedCompletion);
117 const delivery = currentDelegatedCompletionDelivery(
118 projection,
119 request.delegatedCompletion,
120 );
121 if (delivery === undefined) {
122 yield* clearRetryAttempt(retryKey);
123 return;
124 }
125 const commandId = yield* ids.allocate.command({
126 fixtureName: "delegated-completion",
127 commandName: "dispatch",
128 });
129 yield* threads.dispatch({
130 type: "message.dispatch",
131 commandId,
132 threadId: request.threadId,
133 messageId: delivery.messageId,
134 text: delegatedCompletionText(delivery.taskIds),
135 attachments: [],
136 dispatchMode: { type: "queue_after_active" },
137 createdBy: "agent",
138 creationSource: "server",
139 delegatedCompletion: {
140 parentRunId: request.delegatedCompletion.parentRunId,
141 generation: delivery.generation,
142 taskIds: delivery.taskIds,
143 },
144 });
145 yield* clearRetryAttempt(retryKey);
146 return;
147 }
148 // The ordinal is display metadata only: allocate.message appends a
149 // random UUID, so a stale projection read here cannot collide ids.
150 const messageId =
151 request.messageId ??
152 (yield* ids.allocate.message({
153 threadId: request.threadId,
154 ordinal: projection.messages.length + 1,
155 }));
156 const commandId = CommandId.make(`provider-continuation:${messageId}`);
157 const dispatch = threads.dispatch({
158 type: "message.dispatch",
159 commandId,
160 threadId: request.threadId,
161 messageId,
162 text: request.detail ?? CONTINUATION_MESSAGE_TEXT,
163 notification: request.notification ?? {
164 source: { kind: "background_task" },
165 outcome: "updated",
166 summary: "Background activity updated",
167 },
168 attachments: [],
169 dispatchMode: { type: "queue_after_active" },
170 createdBy: "agent",
171 // "provider" marks an adapter-buffered wake, which ClaudeAdapterV2
172 // detects to attach the buffered CLI output and drop this text. A
173 // message_text wake has no buffered output, so it must not carry that
174 // marker or the turn settles immediately having prompted nothing.
175 creationSource: request.delivery === "message_text" ? "server" : "provider",
176 });
177 if (request.dispatchIfCurrent === undefined) {
178 yield* dispatch;
179 return;
180 }
181 yield* request.dispatchIfCurrent(dispatch);
182 },
183 );
184
185 yield* requests.take.pipe(
186 Effect.flatMap((request) =>
187 dispatchContinuation(request).pipe(
188 Effect.catchCause((cause) =>
189 Effect.gen(function* () {
190 yield* Effect.logWarning("orchestration-v2.provider-continuation.dispatch-failed", {
191 threadId: request.threadId,
192 providerThreadId: request.providerThreadId,
193 cause,
194 });
195 if (request.delegatedCompletion !== undefined) {
196 const completion = request.delegatedCompletion;
197 const retryKey = delegatedCompletionRetryKey(request, completion);
198 const retryDelay = yield* nextRetryDelay(retryKey);
199 yield* Effect.gen(function* () {
200 yield* Effect.sleep(`${retryDelay} millis`);
201 const projection = yield* threads.getThreadRecords(
202 request.threadId,
203 ["messages", "runs", "providerTurns"],
204 {
205 messageIds:
206 request.delegatedCompletion === undefined
207 ? []
208 : [request.delegatedCompletion.messageId],
209 },
210 );
211 if (currentDelegatedCompletionDelivery(projection, completion) !== undefined) {
212 yield* requests.offer(request);
213 } else {
214 yield* clearRetryAttempt(retryKey);
215 }
216 }).pipe(
217 Effect.catchCause((retryCause) =>
218 Effect.logWarning("orchestration-v2.provider-continuation.retry-check-failed", {
219 threadId: request.threadId,
220 providerThreadId: request.providerThreadId,
221 cause: retryCause,
222 }).pipe(Effect.andThen(requests.offer(request))),
223 ),
224 Effect.forkScoped,
225 );
226 }
227 }),
228 ),
229 ),
230 ),
231 Effect.forever,
232 Effect.forkScoped,
233 );
234 }),
235);