Open History to see the last commit
1import type { ChatMessage } from "./types";
2
3export interface BootstrapInputResult {
4 text: string;
5 includedCount: number;
6 omittedCount: number;
7 truncated: boolean;
8}
9
10const BOOTSTRAP_PREAMBLE =
11 "Continue this conversation using the transcript context below. The final section is the latest user request to answer now.";
12const TRANSCRIPT_HEADER = "Transcript context:";
13const LATEST_PROMPT_HEADER = "Latest user request (answer this now):";
14const OMITTED_SUMMARY = (count: number) =>
15 `[${count} earlier message(s) omitted to stay within input limits.]`;
16
17function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
18 return message.role === "assistant" ? "ASSISTANT" : "USER";
19}
20
21function attachmentSummary(message: ChatMessage): string | null {
22 const imageAttachments = message.attachments?.filter((attachment) => attachment.type === "image");
23 const count = imageAttachments?.length ?? 0;
24 if (count === 0) {
25 return null;
26 }
27
28 const names = imageAttachments?.slice(0, 3).map((image) => image.name) ?? [];
29 const namesSummary = names.join(", ");
30 const extraCount = count - names.length;
31 const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";
32 return `[Attached image${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
33}
34
35function buildMessageBlock(message: ChatMessage): string {
36 const text = message.text;
37 const attachments = attachmentSummary(message);
38
39 if (text && attachments) {
40 return `${messageRoleLabel(message)}:\n${text}\n${attachments}`;
41 }
42 if (text) {
43 return `${messageRoleLabel(message)}:\n${text}`;
44 }
45 if (attachments) {
46 return `${messageRoleLabel(message)}:\n${attachments}`;
47 }
48 return `${messageRoleLabel(message)}:\n(empty message)`;
49}
50
51function finalizeWithPrompt(
52 transcriptBody: string,
53 latestPrompt: string,
54 maxChars: number,
55): string | null {
56 const text = `${BOOTSTRAP_PREAMBLE}\n\n${TRANSCRIPT_HEADER}\n${transcriptBody}\n\n${LATEST_PROMPT_HEADER}\n${latestPrompt}`;
57 return text.length <= maxChars ? text : null;
58}
59
60export function buildBootstrapInput(
61 previousMessages: ChatMessage[],
62 latestPrompt: string,
63 maxChars: number,
64): BootstrapInputResult {
65 const budget = Number.isFinite(maxChars) ? Math.max(1, Math.floor(maxChars)) : 1;
66 const promptOnly = latestPrompt.length <= budget ? latestPrompt : latestPrompt.slice(0, budget);
67
68 if (previousMessages.length === 0) {
69 return {
70 text: promptOnly,
71 includedCount: 0,
72 omittedCount: 0,
73 truncated: promptOnly.length !== latestPrompt.length,
74 };
75 }
76
77 const newestFirstBlocks: string[] = [];
78 for (let index = previousMessages.length - 1; index >= 0; index -= 1) {
79 const message = previousMessages[index];
80 if (!message) continue;
81 newestFirstBlocks.push(buildMessageBlock(message));
82 }
83
84 if (newestFirstBlocks.length === 0) {
85 return {
86 text: promptOnly,
87 includedCount: 0,
88 omittedCount: previousMessages.length,
89 truncated: true,
90 };
91 }
92
93 // Include a contiguous suffix from newest to oldest, then reverse to chronological.
94 let includedNewestFirst: string[] = [];
95 for (const block of newestFirstBlocks) {
96 const nextNewestFirst = [...includedNewestFirst, block];
97 const nextChronological = nextNewestFirst.toReversed();
98 const omittedCount = newestFirstBlocks.length - nextChronological.length;
99 const transcriptBody =
100 omittedCount > 0
101 ? `${OMITTED_SUMMARY(omittedCount)}\n\n${nextChronological.join("\n\n")}`
102 : nextChronological.join("\n\n");
103 if (!finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
104 break;
105 }
106 includedNewestFirst = nextNewestFirst;
107 }
108
109 let includedChronological = includedNewestFirst.toReversed();
110 while (true) {
111 const omittedCount = newestFirstBlocks.length - includedChronological.length;
112 const transcriptBody =
113 omittedCount > 0
114 ? includedChronological.length > 0
115 ? `${OMITTED_SUMMARY(omittedCount)}\n\n${includedChronological.join("\n\n")}`
116 : OMITTED_SUMMARY(omittedCount)
117 : includedChronological.join("\n\n");
118 const finalized = finalizeWithPrompt(transcriptBody, latestPrompt, budget);
119 if (finalized) {
120 return {
121 text: finalized,
122 includedCount: includedChronological.length,
123 omittedCount,
124 truncated: omittedCount > 0 || latestPrompt.length !== promptOnly.length,
125 };
126 }
127
128 if (includedChronological.length === 0) {
129 return {
130 text: promptOnly,
131 includedCount: 0,
132 omittedCount: previousMessages.length,
133 truncated: true,
134 };
135 }
136
137 includedChronological = includedChronological.slice(1);
138 }
139}