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

ThreadTitleRegenerationService.ts

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