Open History to see the last commit
1import type { ChatAttachment } from "@t3tools/contracts";
2import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
3
4export type ThreadTitleMessage = {
5 readonly role: "user" | "assistant" | "system" | "reasoning";
6 readonly text: string;
7 readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
8};
9
10const MAX_CONTEXT = 8_000;
11const MAX_MESSAGE = 2_000;
12const OMITTED = "[Earlier content truncated]\n\n";
13const TRUNCATED = "\n[Content truncated]\n";
14
15export function limitTitleMessage(text: string, budget: number): string {
16 if (text.length <= budget) return text;
17 if (budget <= TRUNCATED.length) return "";
18 const available = budget - TRUNCATED.length;
19 const head = Math.ceil(available / 2);
20 const tail = available - head;
21 return `${text.slice(0, head)}${TRUNCATED}${tail > 0 ? text.slice(-tail) : ""}`;
22}
23
24export function formatThreadTitleContext(messages: ReadonlyArray<ThreadTitleMessage>) {
25 const sections = messages.flatMap((message, index) => {
26 // Thinking traces are working notes, not what the thread is about, and they
27 // dwarf the answer they precede. Titling on them would be worse and costlier.
28 if (
29 message.role === "system" ||
30 message.role === "reasoning" ||
31 (!message.text.trim() && !message.attachments?.length)
32 )
33 return [];
34 return [{ index, message, prefix: `${message.role.toUpperCase()}:\n` }];
35 });
36 const formatted = new Map<number, string>();
37 const contentsFor = (section: (typeof sections)[number]) => {
38 const cached = formatted.get(section.index);
39 if (cached !== undefined) return cached;
40 const text = assistantCitationsToPlainText(section.message.text).trim();
41 const names = section.message.attachments?.map((attachment) => attachment.name).join(", ");
42 const contents = [text, ...(names ? [`[Attachments: ${names}]`] : [])]
43 .filter(Boolean)
44 .join("\n");
45 formatted.set(section.index, contents);
46 return contents;
47 };
48 const selected = new Map<number, string>();
49 let remaining = MAX_CONTEXT - OMITTED.length;
50 const add = (section: (typeof sections)[number], budget: number) => {
51 if (selected.has(section.index)) return;
52 const limit = Math.min(budget, remaining) - section.prefix.length - 2;
53 if (limit <= TRUNCATED.length) return;
54 const contents = limitTitleMessage(contentsFor(section), limit);
55 if (!contents) return;
56 const text = section.prefix + contents;
57 selected.set(section.index, text);
58 remaining -= text.length + 2;
59 };
60
61 const firstUser = sections.find((section) => section.message.role === "user");
62 if (firstUser) add(firstUser, MAX_MESSAGE);
63 for (const section of sections.toReversed()) {
64 if (section.message.role === "user") {
65 add(section, Math.min(MAX_MESSAGE, remaining - 2_000));
66 }
67 }
68 for (const section of sections.toReversed()) {
69 if (section.message.role === "assistant") add(section, MAX_MESSAGE);
70 }
71 for (const role of ["user", "assistant"] as const) {
72 for (const section of sections.toReversed()) {
73 const previous = selected.get(section.index);
74 if (section.message.role !== role || previous === undefined) continue;
75 const expanded =
76 section.prefix +
77 limitTitleMessage(
78 contentsFor(section),
79 previous.length + remaining - section.prefix.length,
80 );
81 remaining -= expanded.length - previous.length;
82 selected.set(section.index, expanded);
83 }
84 }
85 const retained = sections.filter((section) => selected.has(section.index));
86 const truncated = retained.some(
87 (section) => selected.get(section.index) !== section.prefix + contentsFor(section),
88 );
89 const attachments = retained.flatMap((section) => section.message.attachments ?? []);
90 const firstAttachment = firstUser?.message.attachments?.[0];
91 const recentAttachments = attachments.filter(
92 (attachment) => attachment.id !== firstAttachment?.id,
93 );
94 return {
95 message: `${truncated || retained.length < sections.length ? OMITTED : ""}${retained.map((section) => selected.get(section.index)).join("\n\n")}`,
96 attachments: [
97 ...(firstAttachment ? [firstAttachment] : []),
98 ...recentAttachments.slice(firstAttachment ? -3 : -4),
99 ],
100 };
101}