Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

terminalContext.ts

356 lines10.3 KB

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