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

terminalContext.ts

337 lines10.0 KB

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;
12​
13export interface TerminalContextDraft extends TerminalContextSelection {
14 id: string;
15 threadId: ThreadId;
16 createdAt: string;
18​
19export interface ExtractedTerminalContexts {
20 promptText: string;
21 contextCount: number;
22 previewTitle: string | null;
23 contexts: ParsedTerminalContextEntry[];
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[];
39​
40export interface ParsedTerminalContextEntry {
41 header: string;
42 body: string;
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, "");
53​
54export function hasTerminalContextText(context: { text: string }): boolean {
55 return normalizeTerminalContextText(context.text).length > 0;
57​
58export function isTerminalContextExpired(context: { text: string }): boolean {
59 return !hasTerminalContextText(context);
61​
62export function filterTerminalContextsWithText<T extends { text: string }>(
63 contexts: ReadonlyArray<T>,
64): T[] {
65 return contexts.filter((context) => hasTerminalContextText(context));
67​
68export function normalizeTerminalContextSelection(
69 selection: TerminalContextSelection,
70): TerminalContextSelection | null {
71 const text = normalizeTerminalContextText(selection.text);
72 const terminalId = selection.terminalId.trim();
73 const terminalLabel = selection.terminalLabel.trim();
74 if (text.length === 0 || terminalId.length === 0 || terminalLabel.length === 0) {
75 return null;
76 }
77 const lineStart = Math.max(1, Math.floor(selection.lineStart));
78 const lineEnd = Math.max(lineStart, Math.floor(selection.lineEnd));
79 return {
80 terminalId,
81 terminalLabel,
82 lineStart,
83 lineEnd,
84 text,
85 };
87​
88export function formatTerminalContextRange(selection: {
89 lineStart: number;
90 lineEnd: number;
91}): string {
92 return selection.lineStart === selection.lineEnd
93 ? `line ${selection.lineStart}`
94 : `lines ${selection.lineStart}-${selection.lineEnd}`;
96​
97export function formatTerminalContextLabel(selection: {
98 terminalLabel: string;
99 lineStart: number;
100 lineEnd: number;
101}): string {
102 return `${selection.terminalLabel} ${formatTerminalContextRange(selection)}`;
104​
105export function formatInlineTerminalContextLabel(selection: {
106 terminalLabel: string;
107 lineStart: number;
108 lineEnd: number;
109}): string {
110 const terminalLabel = selection.terminalLabel.trim().toLowerCase().replace(/\s+/g, "-");
111 const range =
112 selection.lineStart === selection.lineEnd
113 ? `${selection.lineStart}`
114 : `${selection.lineStart}-${selection.lineEnd}`;
115 return `@${terminalLabel}:${range}`;
117​
118function buildTerminalContextBodyLines(selection: TerminalContextSelection): string[] {
119 return normalizeTerminalContextText(selection.text)
120 .split("\n")
121 .map((line, index) => ` ${selection.lineStart + index} | ${line}`);
123​
124export function buildTerminalContextBlock(
125 contexts: ReadonlyArray<TerminalContextSelection>,
126): string {
127 const normalizedContexts: TerminalContextSelection[] = [];
128 for (const context of contexts) {
129 const normalized = normalizeTerminalContextSelection(context);
130 if (normalized !== null) {
131 normalizedContexts.push(normalized);
132 }
133 }
134 if (normalizedContexts.length === 0) {
135 return "";
136 }
137 const lines: string[] = [];
138 for (let index = 0; index < normalizedContexts.length; index += 1) {
139 const context = normalizedContexts[index]!;
140 lines.push(`- ${formatTerminalContextLabel(context)}:`);
141 lines.push(...buildTerminalContextBodyLines(context));
142 if (index < normalizedContexts.length - 1) {
143 lines.push("");
144 }
145 }
146 return ["<terminal_context>", ...lines, "</terminal_context>"].join("\n");
148​
149export function materializeInlineTerminalContextPrompt(
150 prompt: string,
151 contexts: ReadonlyArray<{
152 terminalLabel: string;
153 lineStart: number;
154 lineEnd: number;
155 }>,
156): string {
157 let nextContextIndex = 0;
158 let result = "";
159​
160 for (const char of prompt) {
161 if (char !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
162 result += char;
163 continue;
164 }
165 const context = contexts[nextContextIndex] ?? null;
166 nextContextIndex += 1;
167 if (!context) {
168 continue;
169 }
170 result += formatInlineTerminalContextLabel(context);
171 }
172​
173 return result;
175​
176export function appendTerminalContextsToPrompt(
177 prompt: string,
178 contexts: ReadonlyArray<TerminalContextSelection>,
179): string {
180 const trimmedPrompt = materializeInlineTerminalContextPrompt(prompt, contexts).trim();
181 const contextBlock = buildTerminalContextBlock(contexts);
182 if (contextBlock.length === 0) {
183 return trimmedPrompt;
184 }
185 return trimmedPrompt.length > 0 ? `${trimmedPrompt}\n\n${contextBlock}` : contextBlock;
187​
188export function extractTrailingTerminalContexts(prompt: string): ExtractedTerminalContexts {
189 const match = TRAILING_TERMINAL_CONTEXT_BLOCK_PATTERN.exec(prompt);
190 if (!match) {
191 return {
192 promptText: prompt,
193 contextCount: 0,
194 previewTitle: null,
195 contexts: [],
196 };
197 }
198 const promptText = prompt.slice(0, match.index).replace(/\n+$/, "");
199 const parsedContexts = parseTerminalContextEntries(match[1] ?? "");
200 return {
201 promptText,
202 contextCount: parsedContexts.length,
203 previewTitle:
204 parsedContexts.length > 0
205 ? parsedContexts
206 .map(({ header, body }) => (body.length > 0 ? `${header}\n${body}` : header))
207 .join("\n\n")
208 : null,
209 contexts: parsedContexts,
210 };
212​
213export function deriveDisplayedUserMessageState(prompt: string): DisplayedUserMessageState {
214 // Order matters: send-time appends `<terminal_context>` first, then
215 // `<element_context>` last. Strip element first so the (now-trailing)
216 // terminal block can be matched by `extractTrailingTerminalContexts`.
217 const extractedElement = extractTrailingElementContexts(prompt);
218 const extractedTerminal = extractTrailingTerminalContexts(extractedElement.promptText);
219 return {
220 visibleText: extractedTerminal.promptText,
221 copyText: prompt,
222 contextCount: extractedTerminal.contextCount,
223 previewTitle: extractedTerminal.previewTitle,
224 contexts: extractedTerminal.contexts,
225 elementContexts: extractedElement.contexts,
226 };
228​
229function parseTerminalContextEntries(block: string): ParsedTerminalContextEntry[] {
230 const entries: ParsedTerminalContextEntry[] = [];
231 let current: { header: string; bodyLines: string[] } | null = null;
232​
233 const commitCurrent = () => {
234 if (!current) {
235 return;
236 }
237 entries.push({
238 header: current.header,
239 body: current.bodyLines.join("\n").trimEnd(),
240 });
241 current = null;
242 };
243​
244 for (const rawLine of block.split("\n")) {
245 const headerMatch = /^- (.+):$/.exec(rawLine);
246 if (headerMatch) {
247 commitCurrent();
248 current = {
249 header: headerMatch[1]!,
250 bodyLines: [],
251 };
252 continue;
253 }
254 if (!current) {
255 continue;
256 }
257 if (rawLine.startsWith(" ")) {
258 current.bodyLines.push(rawLine.slice(2));
259 continue;
260 }
261 if (rawLine.length === 0) {
262 current.bodyLines.push("");
263 }
264 }
265​
266 commitCurrent();
267 return entries;
269​
270export function countInlineTerminalContextPlaceholders(prompt: string): number {
271 let count = 0;
272 for (const char of prompt) {
273 if (char === INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
274 count += 1;
275 }
276 }
277 return count;
279​
280export function ensureInlineTerminalContextPlaceholders(
281 prompt: string,
282 terminalContextCount: number,
283): string {
284 const missingCount = terminalContextCount - countInlineTerminalContextPlaceholders(prompt);
285 if (missingCount <= 0) {
286 return prompt;
287 }
288 return `${INLINE_TERMINAL_CONTEXT_PLACEHOLDER.repeat(missingCount)}${prompt}`;
290​
291function isInlineTerminalContextBoundaryWhitespace(char: string | undefined): boolean {
292 return char === undefined || char === " " || char === "\n" || char === "\t" || char === "\r";
294​
295export function insertInlineTerminalContextPlaceholder(
296 prompt: string,
297 cursorInput: number,
298): { prompt: string; cursor: number; contextIndex: number } {
299 const cursor = Math.max(0, Math.min(prompt.length, Math.floor(cursorInput)));
300 const needsLeadingSpace = !isInlineTerminalContextBoundaryWhitespace(prompt[cursor - 1]);
301 const replacement = `${needsLeadingSpace ? " " : ""}${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} `;
302 const rangeEnd = prompt[cursor] === " " ? cursor + 1 : cursor;
303 return {
304 prompt: `${prompt.slice(0, cursor)}${replacement}${prompt.slice(rangeEnd)}`,
305 cursor: cursor + replacement.length,
306 contextIndex: countInlineTerminalContextPlaceholders(prompt.slice(0, cursor)),
307 };
309​
310export function stripInlineTerminalContextPlaceholders(prompt: string): string {
311 return prompt.replaceAll(INLINE_TERMINAL_CONTEXT_PLACEHOLDER, "");
313​
314export function removeInlineTerminalContextPlaceholder(
315 prompt: string,
316 contextIndex: number,
317): { prompt: string; cursor: number } {
318 if (contextIndex < 0) {
319 return { prompt, cursor: prompt.length };
320 }
321​
322 let placeholderIndex = 0;
323 for (let index = 0; index < prompt.length; index += 1) {
324 if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
325 continue;
326 }
327 if (placeholderIndex === contextIndex) {
328 return {
329 prompt: prompt.slice(0, index) + prompt.slice(index + 1),
330 cursor: index,
331 };
332 }
333 placeholderIndex += 1;
334 }
335​
336 return { prompt, cursor: prompt.length };