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

ThreadTitleRegenerationService.ts

270 lines10.6 KB

1import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
2import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
3import {
4 CommandId,
5 type ChatAttachment,
6 type MessageId,
7 type OrchestrationV2AppThread,
8 type OrchestrationV2ConversationMessage,
9 type RunId,
10 type ServerSettingsError,
11 TextGenerationError,
12 type ThreadId,
13} from "@t3tools/contracts";
14import * as Cause from "effect/Cause";
15import * as Context from "effect/Context";
16import * as Effect from "effect/Effect";
17import type * as DateTime from "effect/DateTime";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Schedule from "effect/Schedule";
22import * as Schema from "effect/Schema";
23​
24import * as ServerSettings from "../serverSettings.ts";
25import * as TextGeneration from "../textGeneration/TextGeneration.ts";
26import type { OrchestratorV2Error } from "./Orchestrator.ts";
27import * as ProjectStore from "./ProjectStore.ts";
28import { forkInheritedRunOrdinals, ProjectionStoreThreadNotFoundError } from "./ProjectionStore.ts";
29import * as ThreadManagementService from "./ThreadManagementService.ts";
30​
31import { formatThreadTitleContext } from "@t3tools/provider-core/server/threadTitleContext";
32export { formatThreadTitleContext } from "@t3tools/provider-core/server/threadTitleContext";
33​
34export class ThreadTitleRegenerationService extends Context.Service<
35 ThreadTitleRegenerationService,
36 {
37 readonly execute: (input: {
38 readonly threadId: ThreadId;
39 readonly requestId: CommandId;
40 readonly kind:
41 | { readonly type: "initial"; readonly messageId: MessageId }
42 | { readonly type: "regenerate" };
43 }) => Effect.Effect<
44 void,
45 | OrchestratorV2Error
46 | ProjectStore.ProjectStoreV2Error
47 | ServerSettingsError
48 | ThreadManagementService.ThreadManagementProviderInstanceDisabledError
49 >;
50 }
51>()("t3/orchestration-v2/ThreadTitleRegenerationService") {}
52​
53type Outcome =
54 | { readonly status: "renamed"; readonly title: string }
55 | { readonly status: "unchanged" }
56 | { readonly status: "failed"; readonly message: string };
57​
58const MAX_FAILURE_MESSAGE_LENGTH = 300;
59const isTextGenerationError = Schema.is(TextGenerationError);
60const isProjectionStoreThreadNotFoundError = Schema.is(ProjectionStoreThreadNotFoundError);
61// An auth, permission or quota refusal fails the same way on every attempt.
62const PROVIDER_REFUSAL = /\b(?:40[13]|forbidden|unauthori[sz]ed|quota|usage limit)\b/iu;
63​
64const isRetryableFailure = (error: unknown) =>
65 !(isTextGenerationError(error) && PROVIDER_REFUSAL.test(error.detail));
66​
67function failureMessage(cause: Cause.Cause<unknown>): string {
68 const error = Cause.squash(cause);
69 const lines = isTextGenerationError(error)
70 ? error.detail
71 .split("\n")
72 .map((line) => line.trim())
73 .filter((line) => line.length > 0)
74 : [];
75 const detail = lines.at(-1);
76 if (detail === undefined) return "Title generation failed.";
77 if (detail.length <= MAX_FAILURE_MESSAGE_LENGTH) return detail;
78 const keep = MAX_FAILURE_MESSAGE_LENGTH - 1;
79 const last = detail.charCodeAt(keep - 1);
80 const end = keep - (last >= 0xd800 && last <= 0xdbff ? 1 : 0);
81 return `${detail.slice(0, end)}…`;
83​
84const make = Effect.gen(function* () {
85 const threads = yield* ThreadManagementService.ThreadManagementService;
86 const projects = yield* ProjectStore.ProjectStoreV2;
87 const serverSettings = yield* ServerSettings.ServerSettingsService;
88 const textGeneration = yield* TextGeneration.TextGeneration;
89 const fileSystem = yield* FileSystem.FileSystem;
90​
91 const complete = (input: {
92 readonly threadId: ThreadId;
93 readonly requestId: CommandId;
94 readonly kind: { readonly type: "initial" | "regenerate" };
95 readonly outcome: Outcome;
96 }) =>
97 threads
98 .dispatch({
99 type: "thread.title.regeneration.complete",
100 commandId: CommandId.make(`${input.requestId}:title-complete`),
101 threadId: input.threadId,
102 requestId: input.requestId,
103 ...(input.outcome.status === "renamed" ? { title: input.outcome.title } : {}),
104 ...(input.kind.type === "regenerate"
105 ? {
106 outcome: {
107 status: input.outcome.status,
108 ...(input.outcome.status === "failed" ? { message: input.outcome.message } : {}),
109 },
110 }
111 : {}),
112 })
113 .pipe(Effect.asVoid);
114​
115 const messagesThroughRun = Effect.fn("ThreadTitleRegenerationService.messagesThroughRun")(
116 function* (threadId: ThreadId, runId: RunId, forkCreatedAt: DateTime.Utc) {
117 const source = yield* threads.getThreadRecords(threadId, ["messages", "runs"], {
118 messageRoles: ["user", "assistant"],
119 });
120 const ordinals = forkInheritedRunOrdinals(source.runs, forkCreatedAt);
121 const forkOrdinal = ordinals.get(runId);
122 if (forkOrdinal === undefined) return undefined;
123 const messages = source.messages.filter((message) => {
124 if (message.streaming) return false;
125 if (message.runId === null) return source.thread.historyOrigin === "v1_import";
126 return (ordinals.get(message.runId) ?? Infinity) <= forkOrdinal;
127 });
128 return { thread: source.thread, messages };
129 },
130 );
131​
132 // A fork starts with no messages of its own, so its subject lives in the history it inherited.
133 const forkSource = Effect.fn("ThreadTitleRegenerationService.forkSource")(function* (
134 thread: OrchestrationV2AppThread,
135 ) {
136 let title: string | undefined;
137 const history: Array<ReadonlyArray<OrchestrationV2ConversationMessage>> = [];
138 const seen = new Set([thread.id]);
139 let current = thread;
140 while (
141 current.forkedFrom?.type === "run" &&
142 current.lineage.sideChat !== true &&
143 !seen.has(current.forkedFrom.threadId)
144 ) {
145 const { threadId, runId } = current.forkedFrom;
146 seen.add(threadId);
147 const source = yield* messagesThroughRun(threadId, runId, current.createdAt);
148 if (source === undefined) break;
149 history.push(source.messages);
150 title ??= source.thread.title;
151 current = source.thread;
152 }
153 const context = formatThreadTitleContext(history.reverse().flat());
154 return title === undefined || context.message.length === 0
155 ? undefined
156 : { title, history: context.message };
157 });
158​
159 const execute: ThreadTitleRegenerationService["Service"]["execute"] = Effect.fn(
160 "ThreadTitleRegenerationService.execute",
161 )(function* (input) {
162 const outcome: Outcome | { readonly status: "stale" } = yield* Effect.gen(function* () {
163 const projection = yield* threads.getThreadRecords(
164 input.threadId,
165 ["messages"],
166 input.kind.type === "initial"
167 ? { messageIds: [input.kind.messageId] }
168 : { messageRoles: ["user", "assistant"] },
169 );
170 if (projection.thread.titleRegeneration?.requestId !== input.requestId) {
171 return { status: "stale" as const };
172 }
173​
174 const project = yield* projects.get(projection.thread.projectId);
175 if (Option.isNone(project)) {
176 return { status: "failed" as const, message: "This thread's project no longer exists." };
177 }
178​
179 let context: {
180 readonly message: string;
181 readonly attachments: ReadonlyArray<ChatAttachment>;
182 };
183 if (input.kind.type === "initial") {
184 const messageId = input.kind.messageId;
185 const message = projection.messages.find(
186 (candidate) => candidate.id === messageId && !candidate.streaming,
187 );
188 context =
189 message === undefined
190 ? { message: "", attachments: [] }
191 : {
192 message: isAttachmentOnlyBootstrapPrompt(message.text) ? "" : message.text,
193 attachments: message.attachments,
194 };
195 } else {
196 context = formatThreadTitleContext(
197 projection.messages.filter((message) => !message.streaming),
198 );
199 }
200 // A deleted source should not cost the fork its title.
201 const inherited = yield* forkSource(projection.thread).pipe(
202 Effect.catchTags({
203 OrchestratorProjectionError: (error) =>
204 isProjectionStoreThreadNotFoundError(error.cause)
205 ? Effect.undefined
206 : Effect.fail(error),
207 }),
208 );
209 if (
210 context.message.length === 0 &&
211 context.attachments.length === 0 &&
212 inherited === undefined
213 ) {
214 return {
215 status: "failed" as const,
216 message: "This thread has no messages to title yet.",
217 };
218 }
219 const settings = resolveProjectSettings(
220 yield* serverSettings.getSettings,
221 projection.thread.projectId,
222 ).settings;
223 // Storage cleanup removes worktrees but keeps the path; CLIs cannot spawn in a missing cwd.
224 const worktreePath = projection.thread.worktreePath;
225 const worktreeExists =
226 worktreePath !== null &&
227 (yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => false)));
228 const result = yield* textGeneration.generateThreadTitle({
229 cwd: worktreeExists ? worktreePath : project.value.workspaceRoot,
230 message: context.message,
231 projectTitle: project.value.title,
232 attachments: context.attachments,
233 ...(input.kind.type === "regenerate" ? { previousTitle: projection.thread.title } : {}),
234 ...(inherited === undefined ? {} : { forkSource: inherited }),
235 instructions: settings.threadTitleInstructions,
236 modelSelection: settings.textGenerationModelSelection,
237 projectId: projection.thread.projectId,
238 });
239 const generatedTitle = result.title.trim();
240 return generatedTitle === "New thread" ||
241 (input.kind.type === "regenerate" && generatedTitle === projection.thread.title.trim())
242 ? { status: "unchanged" as const }
243 : { status: "renamed" as const, title: result.title };
244 }).pipe(
245 Effect.retry({
246 times: input.kind.type === "initial" ? 2 : 0,
247 schedule: Schedule.exponential("2 seconds"),
248 while: isRetryableFailure,
249 }),
250 Effect.catchCause((cause) =>
251 Cause.hasInterruptsOnly(cause)
252 ? Effect.interrupt
253 : Effect.logWarning("Thread title generation failed", {
254 threadId: input.threadId,
255 requestId: input.requestId,
256 cause,
257 }).pipe(Effect.as({ status: "failed" as const, message: failureMessage(cause) })),
258 ),
259 );
260​
261 if (outcome.status === "stale") {
262 return;
263 }
264 yield* complete({ ...input, outcome });
265 });
266​
267 return ThreadTitleRegenerationService.of({ execute });
268});
269​
270export const layer = Layer.effect(ThreadTitleRegenerationService, make);