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

ThreadTitleRegenerationService.ts

151 lines5.5 KB

1import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
2import {
3 CommandId,
4 type ChatAttachment,
5 type MessageId,
6 type ServerSettingsError,
7 type ThreadId,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Context from "effect/Context";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Schedule from "effect/Schedule";
15​
16import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
17import { ProjectionProjectRepository } from "../persistence/Services/ProjectionProjects.ts";
18import * as ServerSettings from "../serverSettings.ts";
19import * as TextGeneration from "../textGeneration/TextGeneration.ts";
20import type { OrchestratorV2Error } from "./Orchestrator.ts";
21import { ThreadManagementService } from "./ThreadManagementService.ts";
22​
23import { formatThreadTitleContext } from "../textGeneration/ThreadTitleContext.ts";
24export { formatThreadTitleContext } from "../textGeneration/ThreadTitleContext.ts";
25​
26export class ThreadTitleRegenerationService extends Context.Service<
27 ThreadTitleRegenerationService,
28 {
29 readonly execute: (input: {
30 readonly threadId: ThreadId;
31 readonly requestId: CommandId;
32 readonly kind:
33 | { readonly type: "initial"; readonly messageId: MessageId }
34 | { readonly type: "regenerate" };
35 }) => Effect.Effect<
36 void,
37 OrchestratorV2Error | ProjectionRepositoryError | ServerSettingsError
38 >;
39 }
40>()("t3/orchestration-v2/ThreadTitleRegenerationService") {}
41​
42const make = Effect.gen(function* () {
43 const threads = yield* ThreadManagementService;
44 const projects = yield* ProjectionProjectRepository;
45 const serverSettings = yield* ServerSettings.ServerSettingsService;
46 const textGeneration = yield* TextGeneration.TextGeneration;
47​
48 const complete = (input: {
49 readonly threadId: ThreadId;
50 readonly requestId: CommandId;
51 readonly title?: string;
52 }) =>
53 threads
54 .dispatch({
55 type: "thread.title.regeneration.complete",
56 commandId: CommandId.make(`${input.requestId}:title-complete`),
57 threadId: input.threadId,
58 requestId: input.requestId,
59 ...(input.title === undefined ? {} : { title: input.title }),
60 })
61 .pipe(Effect.asVoid);
62​
63 const execute: ThreadTitleRegenerationService["Service"]["execute"] = Effect.fn(
64 "ThreadTitleRegenerationService.execute",
65 )(function* (input) {
66 const outcome:
67 | { readonly type: "stale" }
68 | { readonly type: "complete"; readonly title?: string } = yield* Effect.gen(function* () {
69 const projection = yield* threads.getThreadRecords(
70 input.threadId,
71 ["messages"],
72 input.kind.type === "initial"
73 ? { messageIds: [input.kind.messageId] }
74 : { messageRoles: ["user", "assistant"] },
75 );
76 if (projection.thread.titleRegeneration?.requestId !== input.requestId) {
77 return { type: "stale" as const };
78 }
79​
80 const project = yield* projects.getById({ projectId: projection.thread.projectId });
81 if (Option.isNone(project)) {
82 return { type: "complete" as const };
83 }
84​
85 let context: {
86 readonly message: string;
87 readonly attachments: ReadonlyArray<ChatAttachment>;
88 };
89 if (input.kind.type === "initial") {
90 const messageId = input.kind.messageId;
91 const message = projection.messages.find(
92 (candidate) => candidate.id === messageId && !candidate.streaming,
93 );
94 context =
95 message === undefined
96 ? { message: "", attachments: [] }
97 : { message: message.text, attachments: message.attachments };
98 } else {
99 context = formatThreadTitleContext(
100 projection.messages.filter((message) => !message.streaming),
101 );
102 }
103 if (context.message.length === 0 && context.attachments.length === 0) {
104 return { type: "complete" as const };
105 }
106​
107 const settings = resolveProjectSettings(
108 yield* serverSettings.getSettings,
109 projection.thread.projectId,
110 ).settings;
111 const result = yield* textGeneration.generateThreadTitle({
112 cwd: projection.thread.worktreePath ?? project.value.workspaceRoot,
113 message: context.message,
114 attachments: context.attachments,
115 ...(input.kind.type === "regenerate" ? { previousTitle: projection.thread.title } : {}),
116 modelSelection: settings.textGenerationModelSelection,
117 });
118 const generatedTitle = result.title.trim();
119 return generatedTitle === "New thread" ||
120 (input.kind.type === "regenerate" && generatedTitle === projection.thread.title.trim())
121 ? { type: "complete" as const }
122 : { type: "complete" as const, title: result.title };
123 }).pipe(
124 Effect.retry({
125 times: input.kind.type === "initial" ? 2 : 0,
126 schedule: Schedule.exponential("2 seconds"),
127 }),
128 Effect.catchCause((cause) =>
129 Cause.hasInterruptsOnly(cause)
130 ? Effect.interrupt
131 : Effect.logWarning("Thread title generation failed", {
132 threadId: input.threadId,
133 requestId: input.requestId,
134 cause,
135 }).pipe(Effect.as({ type: "complete" as const })),
136 ),
137 );
138​
139 if (outcome.type === "stale") {
140 return;
141 }
142 yield* complete({
143 ...input,
144 ...(outcome.title === undefined ? {} : { title: outcome.title }),
145 });
146 });
147​
148 return ThreadTitleRegenerationService.of({ execute });
149});
150​
151export const layer = Layer.effect(ThreadTitleRegenerationService, make);