Open History to see the last commit
1import {
2 INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
3 type TerminalContextDraft,
4} from "./lib/terminalContext";
5
6export type ComposerPromptSegment =
7 | {
8 type: "text";
9 text: string;
10 }
11 | {
12 type: "mention";
13 path: string;
14 }
15 | {
16 type: "terminal-context";
17 context: TerminalContextDraft | null;
18 };
19
20const MENTION_TOKEN_REGEX = /(^|\s)@([^\s@]+)(?=\s)/g;
21
22function pushTextSegment(segments: ComposerPromptSegment[], text: string): void {
23 if (!text) return;
24 const last = segments[segments.length - 1];
25 if (last && last.type === "text") {
26 last.text += text;
27 return;
28 }
29 segments.push({ type: "text", text });
30}
31
32function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegment[] {
33 const segments: ComposerPromptSegment[] = [];
34 if (!text) {
35 return segments;
36 }
37
38 let cursor = 0;
39 for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
40 const fullMatch = match[0];
41 const prefix = match[1] ?? "";
42 const path = match[2] ?? "";
43 const matchIndex = match.index ?? 0;
44 const mentionStart = matchIndex + prefix.length;
45 const mentionEnd = mentionStart + fullMatch.length - prefix.length;
46
47 if (mentionStart > cursor) {
48 pushTextSegment(segments, text.slice(cursor, mentionStart));
49 }
50
51 if (path.length > 0) {
52 segments.push({ type: "mention", path });
53 } else {
54 pushTextSegment(segments, text.slice(mentionStart, mentionEnd));
55 }
56
57 cursor = mentionEnd;
58 }
59
60 if (cursor < text.length) {
61 pushTextSegment(segments, text.slice(cursor));
62 }
63
64 return segments;
65}
66
67export function splitPromptIntoComposerSegments(
68 prompt: string,
69 terminalContexts: ReadonlyArray<TerminalContextDraft> = [],
70): ComposerPromptSegment[] {
71 if (!prompt) {
72 return [];
73 }
74
75 const segments: ComposerPromptSegment[] = [];
76 let textCursor = 0;
77 let terminalContextIndex = 0;
78
79 for (let index = 0; index < prompt.length; index += 1) {
80 if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
81 continue;
82 }
83
84 if (index > textCursor) {
85 segments.push(...splitPromptTextIntoComposerSegments(prompt.slice(textCursor, index)));
86 }
87 segments.push({
88 type: "terminal-context",
89 context: terminalContexts[terminalContextIndex] ?? null,
90 });
91 terminalContextIndex += 1;
92 textCursor = index + 1;
93 }
94
95 if (textCursor < prompt.length) {
96 segments.push(...splitPromptTextIntoComposerSegments(prompt.slice(textCursor)));
97 }
98
99 return segments;
100}