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 dwarf answers without identifying the thread subject.
27 if (
28 message.role === "system" ||
29 message.role === "reasoning" ||
30 (!message.text.trim() && !message.attachments?.length)
31 )
32 return [];
33 return [{ index, message, prefix: `${message.role.toUpperCase()}:\n` }];
34 });
35 const formatted = new Map<number, string>();
36 const contentsFor = (section: (typeof sections)[number]) => {
37 const cached = formatted.get(section.index);
38 if (cached !== undefined) return cached;
39 const text = assistantCitationsToPlainText(section.message.text).trim();
40 const names = section.message.attachments?.map((attachment) => attachment.name).join(", ");
41 const contents = [text, ...(names ? [`[Attachments: ${names}]`] : [])]
42 .filter(Boolean)
43 .join("\n");
44 formatted.set(section.index, contents);
45 return contents;
46 };
47 const selected = new Map<number, string>();
48 let remaining = MAX_CONTEXT - OMITTED.length;
49 const add = (section: (typeof sections)[number], budget: number) => {
50 if (selected.has(section.index)) return;
51 const limit = Math.min(budget, remaining) - section.prefix.length - 2;
52 if (limit <= TRUNCATED.length) return;
53 const contents = limitTitleMessage(contentsFor(section), limit);
54 if (!contents) return;
55 const text = section.prefix + contents;
56 selected.set(section.index, text);
57 remaining -= text.length + 2;
58 };
59
60 const firstUser = sections.find((section) => section.message.role === "user");
61 if (firstUser) add(firstUser, MAX_MESSAGE);
62 for (const section of sections.toReversed()) {
63 if (section.message.role === "user") {
64 add(section, Math.min(MAX_MESSAGE, remaining - 2_000));
65 }
66 }
67 for (const section of sections.toReversed()) {
68 if (section.message.role === "assistant") add(section, MAX_MESSAGE);
69 }
70 for (const role of ["user", "assistant"] as const) {
71 for (const section of sections.toReversed()) {
72 const previous = selected.get(section.index);
73 if (section.message.role !== role || previous === undefined) continue;
74 const expanded =
75 section.prefix +
76 limitTitleMessage(
77 contentsFor(section),
78 previous.length + remaining - section.prefix.length,
79 );
80 remaining -= expanded.length - previous.length;
81 selected.set(section.index, expanded);
82 }
83 }
84 const retained = sections.filter((section) => selected.has(section.index));
85 const truncated = retained.some(
86 (section) => selected.get(section.index) !== section.prefix + contentsFor(section),
87 );
88 const attachments = retained.flatMap((section) => section.message.attachments ?? []);
89 const firstAttachment = firstUser?.message.attachments?.[0];
90 const recentAttachments = attachments.filter(
91 (attachment) => attachment.id !== firstAttachment?.id,
92 );
93 return {
94 message: `${truncated || retained.length < sections.length ? OMITTED : ""}${retained.map((section) => selected.get(section.index)).join("\n\n")}`,
95 attachments: [
96 ...(firstAttachment ? [firstAttachment] : []),
97 ...recentAttachments.slice(firstAttachment ? -3 : -4),
98 ],
99 };
100}