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