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

composerPromptHistory.ts

161 lines5.8 KB

1import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
2import {
3 ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
4 collectComposerContextReferences,
5} from "@t3tools/shared/composerContextReferences";
6import { PLAN_IMPLEMENTATION_PROMPT_PREFIX } from "../../proposedPlan";
7​
8const CLAUDE_ULTRATHINK_PREFIX = "Ultrathink:\n";
9const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b[^>]*>[\s\S]*?<\/review_comment>/g;
10const TRAILING_LEGACY_CONTEXT =
11 /\n*<(terminal_context|element_context|preview_annotation)>\n([\s\S]*?)\n<\/\1>\s*$/;
12​
13type ComposerPromptHistoryMessage = Parameters<typeof resolveUserMessagePresentation>[0] & {
14 readonly id: string;
15};
16​
17interface ComposerPromptHistoryEntry {
18 readonly id: string;
19 readonly prompt: string;
21​
22export interface ComposerPromptHistoryPosition {
23 readonly entryId: string;
24 readonly recalled: string;
26​
27function findActive(
28 entries: ReadonlyArray<ComposerPromptHistoryEntry>,
29 position: ComposerPromptHistoryPosition,
30): number {
31 const byId = entries.findIndex((entry) => entry.id === position.entryId);
32 if (byId >= 0) return byId;
33 return entries.findLastIndex((entry) => entry.prompt === position.recalled);
35​
36interface ComposerPromptHistoryStep {
37 readonly position: ComposerPromptHistoryPosition | null;
38 readonly prompt: string;
40​
41function stripTrailingReviewComments(prompt: string): string {
42 let cut = prompt.length;
43 for (const match of [...prompt.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)].toReversed()) {
44 const blockEnd = match.index + match[0].length;
45 if (prompt.slice(blockEnd, cut).trim().length > 0) break;
46 cut = match.index;
47 }
48 return cut === prompt.length ? prompt : prompt.slice(0, cut).trimEnd();
50​
51function escapeRegExp(value: string): string {
52 return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
54​
55function stripInlineTerminalLabels(prompt: string, headers: ReadonlyArray<string>): string {
56 let result = prompt;
57 for (const header of headers) {
58 const match = /^(.+?) lines? (\d+(?:-\d+)?)$/.exec(header);
59 if (!match) continue;
60 const label = `@${match[1]!.trim().toLowerCase().replace(/\s+/g, "-")}:${match[2]}`;
61 const labelPattern = new RegExp(`(?<![\\w@.-])${escapeRegExp(label)}(?![\\d-])`);
62 const index = result.search(labelPattern);
63 if (index < 0) continue;
64 let end = index + label.length;
65 let start = index;
66 if (result[end] === " ") end += 1;
67 else if (result[start - 1] === " ") start -= 1;
68 result = result.slice(0, start) + result.slice(end);
69 }
70 return result;
72​
73export function recallableComposerPrompt(messageText: string): string {
74 let prompt = messageText.trim();
75 if (prompt.startsWith(CLAUDE_ULTRATHINK_PREFIX)) {
76 prompt = prompt.slice(CLAUDE_ULTRATHINK_PREFIX.length);
77 }
78​
79 while (prompt.length > 0) {
80 const withoutReviewComments = stripTrailingReviewComments(prompt);
81 if (withoutReviewComments !== prompt) {
82 prompt = withoutReviewComments;
83 continue;
84 }
85 const legacy = TRAILING_LEGACY_CONTEXT.exec(prompt);
86 if (legacy) {
87 if (
88 legacy[1] === "preview_annotation" &&
89 /^<preview_annotation>\s*$/m.test(legacy[2]!) &&
90 !/^(?:Id|Page|Comment|Targets): /m.test(legacy[2]!)
91 )
92 break;
93 const headers = Array.from(legacy[2]!.matchAll(/^- (.+):$/gm), (match) => match[1]!);
94 if (legacy[1] !== "preview_annotation" && headers.length === 0) break;
95 prompt = prompt.slice(0, legacy.index).trimEnd();
96 if (legacy[1] === "terminal_context") prompt = stripInlineTerminalLabels(prompt, headers);
97 continue;
98 }
99 break;
100 }
101​
102 // Recall strips chips because their backing records are absent.
103 for (const reference of collectComposerContextReferences(prompt).toReversed()) {
104 let { start, end } = reference;
105 if (prompt[end] === " ") end += 1;
106 else if (prompt[start - 1] === " ") start -= 1;
107 prompt = prompt.slice(0, start) + prompt.slice(end);
108 }
109​
110 const trimmed = prompt.trim();
111 if (
112 trimmed === ATTACHMENT_ONLY_BOOTSTRAP_PROMPT ||
113 trimmed.startsWith(PLAN_IMPLEMENTATION_PROMPT_PREFIX)
114 ) {
115 return "";
116 }
117 return trimmed;
119​
120export function buildComposerPromptHistoryEntries(
121 messages: ReadonlyArray<ComposerPromptHistoryMessage>,
122): ComposerPromptHistoryEntry[] {
123 const entries: ComposerPromptHistoryEntry[] = [];
124 for (const message of messages) {
125 if (message.role !== "user") continue;
126 // Automations and other agents send user-role messages; recall only what the user typed.
127 if (resolveUserMessagePresentation(message).attribution !== null) continue;
128 const prompt = recallableComposerPrompt(message.text);
129 if (prompt.length === 0) continue;
130 const previous = entries[entries.length - 1];
131 if (previous && previous.prompt === prompt) {
132 entries[entries.length - 1] = { id: message.id, prompt };
133 continue;
134 }
135 entries.push({ id: message.id, prompt });
136 }
137 return entries;
139​
140export function stepComposerPromptHistory(input: {
141 readonly direction: "backward" | "forward";
142 readonly entries: ReadonlyArray<ComposerPromptHistoryEntry>;
143 readonly position: ComposerPromptHistoryPosition | null;
144 readonly currentPrompt: string;
145}): ComposerPromptHistoryStep | null {
146 const { entries, position, currentPrompt } = input;
147 const activeIndex =
148 position && position.recalled === currentPrompt ? findActive(entries, position) : -1;
149​
150 if (input.direction === "backward") {
151 if (activeIndex < 0 && currentPrompt.length > 0) return null;
152 const entry = entries[activeIndex < 0 ? entries.length - 1 : activeIndex - 1];
153 if (!entry) return null;
154 return { position: { entryId: entry.id, recalled: entry.prompt }, prompt: entry.prompt };
155 }
156​
157 if (activeIndex < 0) return null;
158 const entry = entries[activeIndex + 1];
159 if (!entry) return { position: null, prompt: "" };
160 return { position: { entryId: entry.id, recalled: entry.prompt }, prompt: entry.prompt };