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

ThreadManagementService.ts

472 lines16.5 KB

1import {
2 type ChatAttachment,
3 type CommandId,
4 type MessageId,
5 type ModelSelection,
6 type OrchestrationV2Actor,
7 type OrchestrationV2Command,
8 type OrchestrationV2ConversationMessage,
9 type OrchestrationV2CreationSource,
10 type OrchestrationV2Run,
11 type OrchestrationV2ThreadShellSnapshot,
12 type OrchestrationV2ThreadProjection,
13 type OrchestrationV2ThreadShell,
14 type OrchestrationV2TurnItem,
15 type ProjectId,
16 type RunId,
17 type ThreadId,
18} from "@t3tools/contracts";
19import * as Context from "effect/Context";
20import * as DateTime from "effect/DateTime";
21import * as Duration from "effect/Duration";
22import * as Effect from "effect/Effect";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Schema from "effect/Schema";
26​
27import {
28 OrchestratorV2,
29 type OrchestratorV2DispatchResult,
30 type OrchestratorV2Error,
31} from "./Orchestrator.ts";
32​
33export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart";
34​
35export interface ThreadManagementProvenance {
36 readonly createdBy: OrchestrationV2Actor;
37 readonly creationSource: OrchestrationV2CreationSource;
39​
40export function withCreationProvenance(
41 command: OrchestrationV2Command,
42 provenance: ThreadManagementProvenance,
43): OrchestrationV2Command {
44 switch (command.type) {
45 case "thread.create":
46 case "message.dispatch":
47 case "thread.fork":
48 case "thread.merge_back":
49 case "delegated_task.request":
50 return { ...command, ...provenance };
51 default:
52 return command;
53 }
55​
56export type ThreadManagementTerminalRunStatus = Extract<
57 OrchestrationV2Run["status"],
58 "completed" | "failed" | "cancelled" | "interrupted" | "rolled_back"
59>;
60​
61export interface ThreadManagementSendInput {
62 readonly projectId: ProjectId;
63 readonly commandId: CommandId;
64 readonly threadId: ThreadId;
65 readonly messageId: MessageId;
66 readonly text: string;
67 readonly attachments: ReadonlyArray<ChatAttachment>;
68 readonly modelSelection?: ModelSelection;
69 readonly mode: ThreadManagementSendMode;
70 readonly createdBy: OrchestrationV2Actor;
71 readonly creationSource: OrchestrationV2CreationSource;
73​
74export interface ThreadManagementSendResult {
75 readonly dispatch: OrchestratorV2DispatchResult;
76 readonly projection: OrchestrationV2ThreadProjection;
77 readonly message: OrchestrationV2ConversationMessage;
78 readonly run: OrchestrationV2Run;
79 readonly turnItem: Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }>;
80 readonly delivery: "started" | "queued" | "steered" | "restarted";
82​
83export interface ThreadManagementWaitInput {
84 readonly projectId: ProjectId;
85 readonly threadId: ThreadId;
86 readonly runId?: RunId;
87 readonly timeoutMs: number;
88 readonly pollIntervalMs?: number;
90​
91export interface ThreadManagementWaitResult {
92 readonly threadId: ThreadId;
93 readonly run: OrchestrationV2Run | null;
94 readonly timedOut: boolean;
96​
97export interface ThreadManagementInterruptInput {
98 readonly projectId: ProjectId;
99 readonly commandId: CommandId;
100 readonly threadId: ThreadId;
101 readonly runId?: RunId;
102 readonly reason?: string;
104​
105export type ThreadManagementInterruptResult =
106 | {
107 readonly type: "interrupt_requested";
108 readonly run: OrchestrationV2Run;
109 readonly dispatch: OrchestratorV2DispatchResult;
110 }
111 | { readonly type: "no_active_run" }
112 | {
113 readonly type: "already_terminal";
114 readonly run: OrchestrationV2Run & { readonly status: ThreadManagementTerminalRunStatus };
115 };
116​
117export class ThreadManagementError extends Schema.TaggedErrorClass<ThreadManagementError>()(
118 "ThreadManagementError",
119 {
120 code: Schema.Literals([
121 "thread_not_found",
122 "run_not_found",
123 "thread_not_sendable",
124 "thread_not_interruptible",
125 "orchestration_error",
126 ]),
127 message: Schema.String,
128 cause: Schema.optional(Schema.Defect()),
129 },
130) {}
131​
132type ThreadManagementFailure = ThreadManagementError | OrchestratorV2Error;
133​
134export interface ThreadManagementServiceShape {
135 readonly dispatch: (
136 command: OrchestrationV2Command,
137 ) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;
138 readonly getThreadProjection: (
139 threadId: ThreadId,
140 ) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;
141 readonly getThreadSnapshot: OrchestratorV2["Service"]["getThreadSnapshot"];
142 readonly getProjectThread: (input: {
143 readonly projectId: ProjectId;
144 readonly threadId: ThreadId;
145 }) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadManagementError>;
146 readonly getShellSnapshot: () => Effect.Effect<
147 OrchestrationV2ThreadShellSnapshot,
148 OrchestratorV2Error
149 >;
150 readonly listProjectThreads: (input: {
151 readonly projectId: ProjectId;
152 readonly includeSubagents: boolean;
153 }) => Effect.Effect<ReadonlyArray<OrchestrationV2ThreadShell>, ThreadManagementError>;
154 readonly sendToThread: (
155 input: ThreadManagementSendInput,
156 ) => Effect.Effect<ThreadManagementSendResult, ThreadManagementFailure>;
157 readonly waitForThread: (
158 input: ThreadManagementWaitInput,
159 ) => Effect.Effect<ThreadManagementWaitResult, ThreadManagementError>;
160 readonly interruptThread: (
161 input: ThreadManagementInterruptInput,
162 ) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
163 readonly getThreadEventSequence: OrchestratorV2["Service"]["getThreadEventSequence"];
164 readonly streamStoredEvents: OrchestratorV2["Service"]["streamStoredEvents"];
165 readonly streamStoredEventsFrom: OrchestratorV2["Service"]["streamStoredEventsFrom"];
166 readonly streamDomainEvents: OrchestratorV2["Service"]["streamDomainEvents"];
168​
169export class ThreadManagementService extends Context.Service<
170 ThreadManagementService,
171 ThreadManagementServiceShape
172>()("t3/orchestration-v2/ThreadManagementService") {}
173​
174export function isActiveRun(run: OrchestrationV2Run): boolean {
175 return (
176 run.status === "preparing" ||
177 run.status === "starting" ||
178 run.status === "running" ||
179 run.status === "waiting"
180 );
182​
183export function isTerminalRunStatus(
184 status: OrchestrationV2Run["status"],
185): status is ThreadManagementTerminalRunStatus {
186 return (
187 status === "completed" ||
188 status === "failed" ||
189 status === "cancelled" ||
190 status === "interrupted" ||
191 status === "rolled_back"
192 );
194​
195export function latestRun(
196 projection: OrchestrationV2ThreadProjection,
197): OrchestrationV2Run | undefined {
198 return projection.runs.toSorted((left, right) => right.ordinal - left.ordinal)[0];
200​
201export function latestActiveRun(
202 projection: OrchestrationV2ThreadProjection,
203): OrchestrationV2Run | undefined {
204 return projection.runs
205 .filter(isActiveRun)
206 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
208​
209export function latestSteerableRun(
210 projection: OrchestrationV2ThreadProjection,
211): OrchestrationV2Run | undefined {
212 return projection.runs
213 .filter(
214 (run) =>
215 run.status === "running" &&
216 run.activeAttemptId !== null &&
217 projection.providerTurns.some(
218 (turn) => turn.runAttemptId === run.activeAttemptId && turn.status === "running",
219 ),
220 )
221 .toSorted((left, right) => right.ordinal - left.ordinal)[0];
223​
224function errorMessage(error: unknown): string {
225 return error instanceof Error ? error.message : String(error);
227​
228function managementError(
229 code: ThreadManagementError["code"],
230 message: string,
231 cause?: unknown,
232): ThreadManagementError {
233 return new ThreadManagementError({ code, message, ...(cause === undefined ? {} : { cause }) });
235​
236const make = Effect.gen(function* () {
237 const orchestrator = yield* OrchestratorV2;
238​
239 const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
240 orchestrator.getThreadProjection(input.threadId).pipe(
241 Effect.mapError((cause) =>
242 managementError(
243 "thread_not_found",
244 `Thread ${input.threadId} was not found in project ${input.projectId}.`,
245 cause,
246 ),
247 ),
248 Effect.flatMap((projection) =>
249 projection.thread.projectId === input.projectId && projection.thread.deletedAt === null
250 ? Effect.succeed(projection)
251 : Effect.fail(
252 managementError(
253 "thread_not_found",
254 `Thread ${input.threadId} was not found in project ${input.projectId}.`,
255 ),
256 ),
257 ),
258 );
259​
260 const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) =>
261 orchestrator.getShellSnapshot().pipe(
262 Effect.mapError((cause) =>
263 managementError(
264 "orchestration_error",
265 `Unable to list threads in project ${input.projectId}: ${errorMessage(cause)}`,
266 cause,
267 ),
268 ),
269 Effect.map((snapshot) =>
270 snapshot.threads
271 .filter((thread) => thread.projectId === input.projectId)
272 .filter(
273 (thread) =>
274 input.includeSubagents || thread.lineage.relationshipToParent !== "subagent",
275 )
276 .toSorted(
277 (left, right) =>
278 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
279 right.id.localeCompare(left.id),
280 ),
281 ),
282 );
283​
284 const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
285 Effect.gen(function* () {
286 const target = yield* getProjectThread(input);
287 if (target.thread.archivedAt !== null) {
288 return yield* managementError(
289 "thread_not_sendable",
290 `Thread ${input.threadId} is archived and cannot receive messages.`,
291 );
292 }
293​
294 const steerableRun = latestSteerableRun(target);
295 let dispatchMode: Extract<
296 OrchestrationV2Command,
297 { readonly type: "message.dispatch" }
298 >["dispatchMode"];
299 if (input.mode === "steer" || input.mode === "restart") {
300 if (steerableRun === undefined) {
301 return yield* managementError(
302 "thread_not_sendable",
303 `Thread ${input.threadId} has no running turn that can be ${input.mode === "steer" ? "steered" : "restarted"}.`,
304 );
305 }
306 dispatchMode = {
307 type: input.mode === "steer" ? "steer_active" : "restart_active",
308 targetRunId: steerableRun.id,
309 };
310 } else if (input.mode === "auto" && steerableRun !== undefined) {
311 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
312 } else {
313 dispatchMode = {
314 type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
315 };
316 }
317​
318 const dispatch = yield* orchestrator.dispatch({
319 type: "message.dispatch",
320 commandId: input.commandId,
321 threadId: input.threadId,
322 messageId: input.messageId,
323 text: input.text,
324 attachments: input.attachments,
325 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
326 dispatchMode,
327 createdBy: input.createdBy,
328 creationSource: input.creationSource,
329 });
330 const projection = yield* getProjectThread(input);
331 const message = projection.messages.find((candidate) => candidate.id === input.messageId);
332 const run =
333 message?.runId === null || message?.runId === undefined
334 ? undefined
335 : projection.runs.find((candidate) => candidate.id === message.runId);
336 const turnItem = projection.turnItems.find(
337 (
338 candidate,
339 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
340 candidate.type === "user_message" && candidate.messageId === input.messageId,
341 );
342 if (message === undefined || run === undefined || turnItem === undefined) {
343 return yield* managementError(
344 "orchestration_error",
345 `Message ${input.messageId} was accepted without a durable run projection.`,
346 );
347 }
348 const delivery: ThreadManagementSendResult["delivery"] =
349 turnItem.inputIntent === "turn_start"
350 ? "started"
351 : turnItem.inputIntent === "queued_turn"
352 ? "queued"
353 : input.mode === "restart"
354 ? "restarted"
355 : "steered";
356 return { dispatch, projection, message, run, turnItem, delivery };
357 });
358​
359 const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
360 Effect.gen(function* () {
361 const target = yield* getProjectThread(input);
362 const selectedRun =
363 input.runId === undefined
364 ? latestRun(target)
365 : target.runs.find((candidate) => candidate.id === input.runId);
366 if (input.runId !== undefined && selectedRun === undefined) {
367 return yield* managementError(
368 "run_not_found",
369 `Run ${input.runId} does not belong to thread ${input.threadId}.`,
370 );
371 }
372 if (selectedRun === undefined) {
373 return { threadId: input.threadId, run: null, timedOut: false };
374 }
375 if (isTerminalRunStatus(selectedRun.status)) {
376 return { threadId: input.threadId, run: selectedRun, timedOut: false };
377 }
378​
379 const wait = Effect.gen(function* () {
380 while (true) {
381 const current = yield* getProjectThread(input);
382 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
383 if (run === undefined) {
384 return yield* managementError(
385 "run_not_found",
386 `Run ${selectedRun.id} no longer belongs to thread ${input.threadId}.`,
387 );
388 }
389 if (isTerminalRunStatus(run.status)) return run;
390 yield* Effect.sleep(Duration.millis(Math.max(1, input.pollIntervalMs ?? 250)));
391 }
392 }).pipe(Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))));
393 const waited = yield* wait;
394 if (Option.isSome(waited)) {
395 return { threadId: input.threadId, run: waited.value, timedOut: false };
396 }
397 const current = yield* getProjectThread(input);
398 const run = current.runs.find((candidate) => candidate.id === selectedRun.id);
399 if (run === undefined) {
400 return yield* managementError(
401 "run_not_found",
402 `Run ${selectedRun.id} no longer belongs to thread ${input.threadId}.`,
403 );
404 }
405 return { threadId: input.threadId, run, timedOut: true };
406 });
407​
408 const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
409 Effect.gen(function* () {
410 const target = yield* getProjectThread(input);
411 const explicitRun =
412 input.runId === undefined
413 ? undefined
414 : target.runs.find((candidate) => candidate.id === input.runId);
415 if (input.runId !== undefined && explicitRun === undefined) {
416 return yield* managementError(
417 "run_not_found",
418 `Run ${input.runId} does not belong to thread ${input.threadId}.`,
419 );
420 }
421 if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
422 return {
423 type: "already_terminal",
424 run: explicitRun as OrchestrationV2Run & {
425 readonly status: ThreadManagementTerminalRunStatus;
426 },
427 } as const;
428 }
429 const interruptibleRun = latestActiveRun(target);
430 if (input.runId === undefined && interruptibleRun === undefined) {
431 return { type: "no_active_run" } as const;
432 }
433 if (
434 interruptibleRun === undefined ||
435 (explicitRun !== undefined && interruptibleRun.id !== explicitRun.id)
436 ) {
437 return yield* managementError(
438 "thread_not_interruptible",
439 `Run ${explicitRun?.id ?? input.runId} is not currently interruptible.`,
440 );
441 }
442 const dispatch = yield* orchestrator.dispatch({
443 type: "run.interrupt",
444 commandId: input.commandId,
445 threadId: input.threadId,
446 runId: interruptibleRun.id,
447 ...(input.reason === undefined ? {} : { reason: input.reason }),
448 });
449 return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
450 });
451​
452 return ThreadManagementService.of({
453 dispatch: orchestrator.dispatch,
454 getThreadProjection: orchestrator.getThreadProjection,
455 getThreadSnapshot: orchestrator.getThreadSnapshot,
456 getProjectThread,
457 getShellSnapshot: orchestrator.getShellSnapshot,
458 listProjectThreads,
459 sendToThread,
460 waitForThread,
461 interruptThread,
462 getThreadEventSequence: orchestrator.getThreadEventSequence,
463 streamStoredEvents: orchestrator.streamStoredEvents,
464 streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
465 streamDomainEvents: orchestrator.streamDomainEvents,
466 });
467});
468​
469export const layer: Layer.Layer<ThreadManagementService, never, OrchestratorV2> = Layer.effect(
470 ThreadManagementService,
471 make,
472);