Open History to see the last commit
1import { type ThreadId } from "@t3tools/contracts";
2
3import { extractTrailingElementContexts, type ParsedElementContextEntry } from "./elementContext";
4
5export interface TerminalContextSelection {
6 terminalId: string;
7 terminalLabel: string;
8 lineStart: number;
9 lineEnd: number;
10 text: string;
11}
12
13export interface TerminalContextDraft extends TerminalContextSelection {
14 id: string;
15 threadId: ThreadId;
16 createdAt: string;
17}
18
19export interface ExtractedTerminalContexts {
20 promptText: string;
21 contextCount: number;
22 previewTitle: string | null;
23 contexts: ParsedTerminalContextEntry[];
24}
25
26export interface DisplayedUserMessageState {
27 visibleText: string;
28 copyText: string;
29 contextCount: number;
30 previewTitle: string | null;
31 contexts: ParsedTerminalContextEntry[];
32 /**
33 * Element-context entries extracted from the trailing `<element_context>`
34 * block (if any). Stripped from `visibleText` so the raw block doesn't
35 * leak into the user's bubble.
36 */
37 elementContexts: ParsedElementContextEntry[];
38}
39
40export interface ParsedTerminalContextEntry {
41 header: string;
42 body: string;
43}
44
45export const INLINE_TERMINAL_CONTEXT_PLACEHOLDER = "\uFFFC";
46
47const TRAILING_TERMINAL_CONTEXT_BLOCK_PATTERN =
48 /\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/;
49
50export function normalizeTerminalContextText(text: string): string {
51 return text.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
52}
53
54export function hasTerminalContextText(context: { text: string }): boolean {
55 return normalizeTerminalContextText(context.text).length > 0;
56}
57
58export function isTerminalContextExpired(context: { text: string }): boolean {
59 return !hasTerminalContextText(context);
60}
61
62export function filterTerminalContextsWithText<T extends { text: string }>(
63 contexts: ReadonlyArray<T>,
64): T[] {
65 return contexts.filter((context) => hasTerminalContextText(context));
66}
67
68function previewTerminalContextText(text: string): string {
69 const normalized = normalizeTerminalContextText(text);
70 if (normalized.length === 0) {
71 return "";
72 }
73 const lines = normalized.split("\n");
74 const visibleLines = lines.slice(0, 3);
75 if (lines.length > 3) {
76 visibleLines.push("...");
77 }
78 const preview = visibleLines.join("\n");
79 return preview.length > 180 ? `${preview.slice(0, 177)}...` : preview;
80}
81
82export function normalizeTerminalContextSelection(
83 selection: TerminalContextSelection,
84): TerminalContextSelection | null {
85 const text = normalizeTerminalContextText(selection.text);
86 const terminalId = selection.terminalId.trim();
87 const terminalLabel = selection.terminalLabel.trim();
88 if (text.length === 0 || terminalId.length === 0 || terminalLabel.length === 0) {
89 return null;
90 }
91 const lineStart = Math.max(1, Math.floor(selection.lineStart));
92 const lineEnd = Math.max(lineStart, Math.floor(selection.lineEnd));
93 return {
94 terminalId,
95 terminalLabel,
96 lineStart,
97 lineEnd,
98 text,
99 };
100}
101
102export function formatTerminalContextRange(selection: {
103 lineStart: number;
104 lineEnd: number;
105}): string {
106 return selection.lineStart === selection.lineEnd
107 ? `line ${selection.lineStart}`
108 : `lines ${selection.lineStart}-${selection.lineEnd}`;
109}
110
111export function formatTerminalContextLabel(selection: {
112 terminalLabel: string;
113 lineStart: number;
114 lineEnd: number;
115}): string {
116 return `${selection.terminalLabel} ${formatTerminalContextRange(selection)}`;
117}
118
119export function formatInlineTerminalContextLabel(selection: {
120 terminalLabel: string;
121 lineStart: number;
122 lineEnd: number;
123}): string {
124 const terminalLabel = selection.terminalLabel.trim().toLowerCase().replace(/\s+/g, "-");
125 const range =
126 selection.lineStart === selection.lineEnd
127 ? `${selection.lineStart}`
128 : `${selection.lineStart}-${selection.lineEnd}`;
129 return `@${terminalLabel}:${range}`;
130}
131
132export function buildTerminalContextPreviewTitle(
133 contexts: ReadonlyArray<TerminalContextSelection>,
134): string | null {
135 if (contexts.length === 0) {
136 return null;
137 }
138 const previewParts: string[] = [];
139 for (const context of contexts) {
140 const normalized = normalizeTerminalContextSelection(context);
141 if (!normalized) continue;
142 const preview = previewTerminalContextText(normalized.text);
143 previewParts.push(
144 preview.length > 0
145 ? `${formatTerminalContextLabel(normalized)}\n${preview}`
146 : formatTerminalContextLabel(normalized),
147 );
148 }
149 const previews = previewParts.join("\n\n");
150 return previews.length > 0 ? previews : null;
151}
152
153function buildTerminalContextBodyLines(selection: TerminalContextSelection): string[] {
154 return normalizeTerminalContextText(selection.text)
155 .split("\n")
156 .map((line, index) => ` ${selection.lineStart + index} | ${line}`);
157}
158
159export function buildTerminalContextBlock(
160 contexts: ReadonlyArray<TerminalContextSelection>,
161): string {
162 const normalizedContexts: TerminalContextSelection[] = [];
163 for (const context of contexts) {
164 const normalized = normalizeTerminalContextSelection(context);
165 if (normalized !== null) {
166 normalizedContexts.push(normalized);
167 }
168 }
169 if (normalizedContexts.length === 0) {
170 return "";
171 }
172 const lines: string[] = [];
173 for (let index = 0; index < normalizedContexts.length; index += 1) {
174 const context = normalizedContexts[index]!;
175 lines.push(`- ${formatTerminalContextLabel(context)}:`);
176 lines.push(...buildTerminalContextBodyLines(context));
177 if (index < normalizedContexts.length - 1) {
178 lines.push("");
179 }
180 }
181 return ["<terminal_context>", ...lines, "</terminal_context>"].join("\n");
182}
183
184export function materializeInlineTerminalContextPrompt(
185 prompt: string,
186 contexts: ReadonlyArray<{
187 terminalLabel: string;
188 lineStart: number;
189 lineEnd: number;
190 }>,
191): string {
192 let nextContextIndex = 0;
193 let result = "";
194
195 for (const char of prompt) {
196 if (char !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
197 result += char;
198 continue;
199 }
200 const context = contexts[nextContextIndex] ?? null;
201 nextContextIndex += 1;
202 if (!context) {
203 continue;
204 }
205 result += formatInlineTerminalContextLabel(context);
206 }
207
208 return result;
209}
210
211export function appendTerminalContextsToPrompt(
212 prompt: string,
213 contexts: ReadonlyArray<TerminalContextSelection>,
214): string {
215 const trimmedPrompt = materializeInlineTerminalContextPrompt(prompt, contexts).trim();
216 const contextBlock = buildTerminalContextBlock(contexts);
217 if (contextBlock.length === 0) {
218 return trimmedPrompt;
219 }
220 return trimmedPrompt.length > 0 ? `${trimmedPrompt}\n\n${contextBlock}` : contextBlock;
221}
222
223export function extractTrailingTerminalContexts(prompt: string): ExtractedTerminalContexts {
224 const match = TRAILING_TERMINAL_CONTEXT_BLOCK_PATTERN.exec(prompt);
225 if (!match) {
226 return {
227 promptText: prompt,
228 contextCount: 0,
229 previewTitle: null,
230 contexts: [],
231 };
232 }
233 const promptText = prompt.slice(0, match.index).replace(/\n+$/, "");
234 const parsedContexts = parseTerminalContextEntries(match[1] ?? "");
235 return {
236 promptText,
237 contextCount: parsedContexts.length,
238 previewTitle:
239 parsedContexts.length > 0
240 ? parsedContexts
241 .map(({ header, body }) => (body.length > 0 ? `${header}\n${body}` : header))
242 .join("\n\n")
243 : null,
244 contexts: parsedContexts,
245 };
246}
247
248export function deriveDisplayedUserMessageState(prompt: string): DisplayedUserMessageState {
249 // Order matters: send-time appends `<terminal_context>` first, then
250 // `<element_context>` last. Strip element first so the (now-trailing)
251 // terminal block can be matched by `extractTrailingTerminalContexts`.
252 const extractedElement = extractTrailingElementContexts(prompt);
253 const extractedTerminal = extractTrailingTerminalContexts(extractedElement.promptText);
254 return {
255 visibleText: extractedTerminal.promptText,
256 copyText: prompt,
257 contextCount: extractedTerminal.contextCount,
258 previewTitle: extractedTerminal.previewTitle,
259 contexts: extractedTerminal.contexts,
260 elementContexts: extractedElement.contexts,
261 };
262}
263
264function parseTerminalContextEntries(block: string): ParsedTerminalContextEntry[] {
265 const entries: ParsedTerminalContextEntry[] = [];
266 let current: { header: string; bodyLines: string[] } | null = null;
267
268 const commitCurrent = () => {
269 if (!current) {
270 return;
271 }
272 entries.push({
273 header: current.header,
274 body: current.bodyLines.join("\n").trimEnd(),
275 });
276 current = null;
277 };
278
279 for (const rawLine of block.split("\n")) {
280 const headerMatch = /^- (.+):$/.exec(rawLine);
281 if (headerMatch) {
282 commitCurrent();
283 current = {
284 header: headerMatch[1]!,
285 bodyLines: [],
286 };
287 continue;
288 }
289 if (!current) {
290 continue;
291 }
292 if (rawLine.startsWith(" ")) {
293 current.bodyLines.push(rawLine.slice(2));
294 continue;
295 }
296 if (rawLine.length === 0) {
297 current.bodyLines.push("");
298 }
299 }
300
301 commitCurrent();
302 return entries;
303}
304
305export function countInlineTerminalContextPlaceholders(prompt: string): number {
306 let count = 0;
307 for (const char of prompt) {
308 if (char === INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
309 count += 1;
310 }
311 }
312 return count;
313}
314
315export function ensureInlineTerminalContextPlaceholders(
316 prompt: string,
317 terminalContextCount: number,
318): string {
319 const missingCount = terminalContextCount - countInlineTerminalContextPlaceholders(prompt);
320 if (missingCount <= 0) {
321 return prompt;
322 }
323 return `${INLINE_TERMINAL_CONTEXT_PLACEHOLDER.repeat(missingCount)}${prompt}`;
324}
325
326function isInlineTerminalContextBoundaryWhitespace(char: string | undefined): boolean {
327 return char === undefined || char === " " || char === "\n" || char === "\t" || char === "\r";
328}
329
330export function insertInlineTerminalContextPlaceholder(
331 prompt: string,
332 cursorInput: number,
333): { prompt: string; cursor: number; contextIndex: number } {
334 const cursor = Math.max(0, Math.min(prompt.length, Math.floor(cursorInput)));
335 const needsLeadingSpace = !isInlineTerminalContextBoundaryWhitespace(prompt[cursor - 1]);
336 const replacement = `${needsLeadingSpace ? " " : ""}${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} `;
337 const rangeEnd = prompt[cursor] === " " ? cursor + 1 : cursor;
338 return {
339 prompt: `${prompt.slice(0, cursor)}${replacement}${prompt.slice(rangeEnd)}`,
340 cursor: cursor + replacement.length,
341 contextIndex: countInlineTerminalContextPlaceholders(prompt.slice(0, cursor)),
342 };
343}
344
345export function stripInlineTerminalContextPlaceholders(prompt: string): string {
346 return prompt.replaceAll(INLINE_TERMINAL_CONTEXT_PLACEHOLDER, "");
347}
348
349export function removeInlineTerminalContextPlaceholder(
350 prompt: string,
351 contextIndex: number,
352): { prompt: string; cursor: number } {
353 if (contextIndex < 0) {
354 return { prompt, cursor: prompt.length };
355 }
356
357 let placeholderIndex = 0;
358 for (let index = 0; index < prompt.length; index += 1) {
359 if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
360 continue;
361 }
362 if (placeholderIndex === contextIndex) {
363 return {
364 prompt: prompt.slice(0, index) + prompt.slice(index + 1),
365 cursor: index,
366 };
367 }
368 placeholderIndex += 1;
369 }
370
371 return { prompt, cursor: prompt.length };
372}