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

terminalContext.ts

359 lines10.4 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 previewParts: string[] = [];
131 for (const context of contexts) {
132 const normalized = normalizeTerminalContextSelection(context);
133 if (!normalized) continue;
134 const preview = previewTerminalContextText(normalized.text);
135 previewParts.push(
136 preview.length > 0
137 ? `${formatTerminalContextLabel(normalized)}\n${preview}`
138 : formatTerminalContextLabel(normalized),
139 );
140 }
141 const previews = previewParts.join("\n\n");
142 return previews.length > 0 ? previews : null;
144​
145function buildTerminalContextBodyLines(selection: TerminalContextSelection): string[] {
146 return normalizeTerminalContextText(selection.text)
147 .split("\n")
148 .map((line, index) => ` ${selection.lineStart + index} | ${line}`);
150​
151export function buildTerminalContextBlock(
152 contexts: ReadonlyArray<TerminalContextSelection>,
153): string {
154 const normalizedContexts: TerminalContextSelection[] = [];
155 for (const context of contexts) {
156 const normalized = normalizeTerminalContextSelection(context);
157 if (normalized !== null) {
158 normalizedContexts.push(normalized);
159 }
160 }
161 if (normalizedContexts.length === 0) {
162 return "";
163 }
164 const lines: string[] = [];
165 for (let index = 0; index < normalizedContexts.length; index += 1) {
166 const context = normalizedContexts[index]!;
167 lines.push(`- ${formatTerminalContextLabel(context)}:`);
168 lines.push(...buildTerminalContextBodyLines(context));
169 if (index < normalizedContexts.length - 1) {
170 lines.push("");
171 }
172 }
173 return ["<terminal_context>", ...lines, "</terminal_context>"].join("\n");
175​
176export function materializeInlineTerminalContextPrompt(
177 prompt: string,
178 contexts: ReadonlyArray<{
179 terminalLabel: string;
180 lineStart: number;
181 lineEnd: number;
182 }>,
183): string {
184 let nextContextIndex = 0;
185 let result = "";
186​
187 for (const char of prompt) {
188 if (char !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
189 result += char;
190 continue;
191 }
192 const context = contexts[nextContextIndex] ?? null;
193 nextContextIndex += 1;
194 if (!context) {
195 continue;
196 }
197 result += formatInlineTerminalContextLabel(context);
198 }
199​
200 return result;
202​
203export function appendTerminalContextsToPrompt(
204 prompt: string,
205 contexts: ReadonlyArray<TerminalContextSelection>,
206): string {
207 const trimmedPrompt = materializeInlineTerminalContextPrompt(prompt, contexts).trim();
208 const contextBlock = buildTerminalContextBlock(contexts);
209 if (contextBlock.length === 0) {
210 return trimmedPrompt;
211 }
212 return trimmedPrompt.length > 0 ? `${trimmedPrompt}\n\n${contextBlock}` : contextBlock;
214​
215export function extractTrailingTerminalContexts(prompt: string): ExtractedTerminalContexts {
216 const match = TRAILING_TERMINAL_CONTEXT_BLOCK_PATTERN.exec(prompt);
217 if (!match) {
218 return {
219 promptText: prompt,
220 contextCount: 0,
221 previewTitle: null,
222 contexts: [],
223 };
224 }
225 const promptText = prompt.slice(0, match.index).replace(/\n+$/, "");
226 const parsedContexts = parseTerminalContextEntries(match[1] ?? "");
227 return {
228 promptText,
229 contextCount: parsedContexts.length,
230 previewTitle:
231 parsedContexts.length > 0
232 ? parsedContexts
233 .map(({ header, body }) => (body.length > 0 ? `${header}\n${body}` : header))
234 .join("\n\n")
235 : null,
236 contexts: parsedContexts,
237 };
239​
240export function deriveDisplayedUserMessageState(prompt: string): DisplayedUserMessageState {
241 const extractedContexts = extractTrailingTerminalContexts(prompt);
242 return {
243 visibleText: extractedContexts.promptText,
244 copyText: prompt,
245 contextCount: extractedContexts.contextCount,
246 previewTitle: extractedContexts.previewTitle,
247 contexts: extractedContexts.contexts,
248 };
250​
251function parseTerminalContextEntries(block: string): ParsedTerminalContextEntry[] {
252 const entries: ParsedTerminalContextEntry[] = [];
253 let current: { header: string; bodyLines: string[] } | null = null;
254​
255 const commitCurrent = () => {
256 if (!current) {
257 return;
258 }
259 entries.push({
260 header: current.header,
261 body: current.bodyLines.join("\n").trimEnd(),
262 });
263 current = null;
264 };
265​
266 for (const rawLine of block.split("\n")) {
267 const headerMatch = /^- (.+):$/.exec(rawLine);
268 if (headerMatch) {
269 commitCurrent();
270 current = {
271 header: headerMatch[1]!,
272 bodyLines: [],
273 };
274 continue;
275 }
276 if (!current) {
277 continue;
278 }
279 if (rawLine.startsWith(" ")) {
280 current.bodyLines.push(rawLine.slice(2));
281 continue;
282 }
283 if (rawLine.length === 0) {
284 current.bodyLines.push("");
285 }
286 }
287​
288 commitCurrent();
289 return entries;
291​
292export function countInlineTerminalContextPlaceholders(prompt: string): number {
293 let count = 0;
294 for (const char of prompt) {
295 if (char === INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
296 count += 1;
297 }
298 }
299 return count;
301​
302export function ensureInlineTerminalContextPlaceholders(
303 prompt: string,
304 terminalContextCount: number,
305): string {
306 const missingCount = terminalContextCount - countInlineTerminalContextPlaceholders(prompt);
307 if (missingCount <= 0) {
308 return prompt;
309 }
310 return `${INLINE_TERMINAL_CONTEXT_PLACEHOLDER.repeat(missingCount)}${prompt}`;
312​
313function isInlineTerminalContextBoundaryWhitespace(char: string | undefined): boolean {
314 return char === undefined || char === " " || char === "\n" || char === "\t" || char === "\r";
316​
317export function insertInlineTerminalContextPlaceholder(
318 prompt: string,
319 cursorInput: number,
320): { prompt: string; cursor: number; contextIndex: number } {
321 const cursor = Math.max(0, Math.min(prompt.length, Math.floor(cursorInput)));
322 const needsLeadingSpace = !isInlineTerminalContextBoundaryWhitespace(prompt[cursor - 1]);
323 const replacement = `${needsLeadingSpace ? " " : ""}${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} `;
324 const rangeEnd = prompt[cursor] === " " ? cursor + 1 : cursor;
325 return {
326 prompt: `${prompt.slice(0, cursor)}${replacement}${prompt.slice(rangeEnd)}`,
327 cursor: cursor + replacement.length,
328 contextIndex: countInlineTerminalContextPlaceholders(prompt.slice(0, cursor)),
329 };
331​
332export function stripInlineTerminalContextPlaceholders(prompt: string): string {
333 return prompt.replaceAll(INLINE_TERMINAL_CONTEXT_PLACEHOLDER, "");
335​
336export function removeInlineTerminalContextPlaceholder(
337 prompt: string,
338 contextIndex: number,
339): { prompt: string; cursor: number } {
340 if (contextIndex < 0) {
341 return { prompt, cursor: prompt.length };
342 }
343​
344 let placeholderIndex = 0;
345 for (let index = 0; index < prompt.length; index += 1) {
346 if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
347 continue;
348 }
349 if (placeholderIndex === contextIndex) {
350 return {
351 prompt: prompt.slice(0, index) + prompt.slice(index + 1),
352 cursor: index,
353 };
354 }
355 placeholderIndex += 1;
356 }
357​
358 return { prompt, cursor: prompt.length };