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

composerPromptHistory.ts

242 lines8.8 KB

1import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
2import {
3 EnvironmentContextRecord,
4 type OrchestrationMessageContext,
5 ThreadContextRecord,
6} from "@t3tools/contracts";
7import {
8 ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
9 collectComposerContextReferences,
10 replaceComposerContextReferences,
11} from "@t3tools/shared/composerContextReferences";
12import { restoreTrailingTokenSpace } from "@t3tools/shared/composerInlineTokens";
13import { Schema } from "effect";
14import { collectComposerPromptInlineTokens } from "../../composer-editor-mentions";
15import { PLAN_IMPLEMENTATION_PROMPT_PREFIX } from "../../proposedPlan";
16​
17const CLAUDE_ULTRATHINK_PREFIX = "Ultrathink:\n";
18const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b[^>]*>[\s\S]*?<\/review_comment>/g;
19const TRAILING_LEGACY_CONTEXT =
20 /\n*<(terminal_context|element_context|preview_annotation)>\n([\s\S]*?)\n<\/\1>\s*$/;
21​
22const isThreadContextRecord = Schema.is(ThreadContextRecord);
23const isEnvironmentContextRecord = Schema.is(EnvironmentContextRecord);
24​
25type ComposerPromptHistoryMessage = Parameters<typeof resolveUserMessagePresentation>[0] & {
26 readonly id: string;
27 readonly context?: OrchestrationMessageContext | undefined;
28};
29​
30/** Thread and machine mentions; the draft holds these records, so recall can restore their chips. */
31export interface ComposerPromptHistoryMentions {
32 readonly threadContexts: ReadonlyArray<ThreadContextRecord>;
33 readonly environmentContexts: ReadonlyArray<EnvironmentContextRecord>;
35​
36const NO_MENTIONS: ComposerPromptHistoryMentions = { threadContexts: [], environmentContexts: [] };
37​
38interface ComposerPromptHistoryEntry {
39 readonly id: string;
40 readonly prompt: string;
41 readonly mentions: ComposerPromptHistoryMentions;
43​
44export interface ComposerPromptHistory {
45 readonly entries: ReadonlyArray<ComposerPromptHistoryEntry>;
46 readonly earlier: {
47 readonly cursor: string;
48 readonly load: () => Promise<void>;
49 } | null;
51​
52export interface ComposerPromptHistoryPosition {
53 readonly entryId: string;
54 readonly recalled: string;
56​
57function findActive(
58 entries: ReadonlyArray<ComposerPromptHistoryEntry>,
59 position: ComposerPromptHistoryPosition,
60): number {
61 const byId = entries.findIndex((entry) => entry.id === position.entryId);
62 if (byId >= 0) return byId;
63 return entries.findLastIndex((entry) => entry.prompt === position.recalled);
65​
66interface ComposerPromptHistoryStep {
67 readonly position: ComposerPromptHistoryPosition | null;
68 readonly prompt: string;
69 readonly mentions: ComposerPromptHistoryMentions;
71​
72function stripTrailingReviewComments(prompt: string): string {
73 let cut = prompt.length;
74 for (const match of [...prompt.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)].toReversed()) {
75 const blockEnd = match.index + match[0].length;
76 if (prompt.slice(blockEnd, cut).trim().length > 0) break;
77 cut = match.index;
78 }
79 return cut === prompt.length ? prompt : prompt.slice(0, cut).trimEnd();
81​
82function escapeRegExp(value: string): string {
83 return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
85​
86function stripInlineTerminalLabels(prompt: string, headers: ReadonlyArray<string>): string {
87 let result = prompt;
88 for (const header of headers) {
89 const match = /^(.+?) lines? (\d+(?:-\d+)?)$/.exec(header);
90 if (!match) continue;
91 const label = `@${match[1]!.trim().toLowerCase().replace(/\s+/g, "-")}:${match[2]}`;
92 const labelPattern = new RegExp(`(?<![\\w@.-])${escapeRegExp(label)}(?![\\d-])`);
93 const index = result.search(labelPattern);
94 if (index < 0) continue;
95 let end = index + label.length;
96 let start = index;
97 if (result[end] === " ") end += 1;
98 else if (result[start - 1] === " ") start -= 1;
99 result = result.slice(0, start) + result.slice(end);
100 }
101 return result;
103​
104export function recallableComposerPrompt(
105 messageText: string,
106 keptContextIds: ReadonlySet<string> = new Set(),
107): string {
108 let prompt = messageText.trim();
109 if (prompt.startsWith(CLAUDE_ULTRATHINK_PREFIX)) {
110 prompt = prompt.slice(CLAUDE_ULTRATHINK_PREFIX.length);
111 }
112​
113 while (prompt.length > 0) {
114 const withoutReviewComments = stripTrailingReviewComments(prompt);
115 if (withoutReviewComments !== prompt) {
116 prompt = withoutReviewComments;
117 continue;
118 }
119 const legacy = TRAILING_LEGACY_CONTEXT.exec(prompt);
120 if (legacy) {
121 if (
122 legacy[1] === "preview_annotation" &&
123 /^<preview_annotation>\s*$/m.test(legacy[2]!) &&
124 !/^(?:Id|Page|Comment|Targets): /m.test(legacy[2]!)
125 )
126 break;
127 const headers = Array.from(legacy[2]!.matchAll(/^- (.+):$/gm), (match) => match[1]!);
128 if (legacy[1] !== "preview_annotation" && headers.length === 0) break;
129 prompt = prompt.slice(0, legacy.index).trimEnd();
130 if (legacy[1] === "terminal_context") prompt = stripInlineTerminalLabels(prompt, headers);
131 continue;
132 }
133 break;
134 }
135​
136 // Chips without a record the draft can hold would render as unavailable.
137 for (const reference of collectComposerContextReferences(prompt).toReversed()) {
138 if (keptContextIds.has(reference.contextId)) continue;
139 let { start, end } = reference;
140 if (prompt[end] === " ") end += 1;
141 else if (prompt[start - 1] === " ") start -= 1;
142 prompt = prompt.slice(0, start) + prompt.slice(end);
143 }
144​
145 const trimmed = prompt.trim();
146 if (
147 trimmed === ATTACHMENT_ONLY_BOOTSTRAP_PROMPT ||
148 trimmed.startsWith(PLAN_IMPLEMENTATION_PROMPT_PREFIX)
149 ) {
150 return "";
151 }
152 return trimmed;
154​
155/**
156 * A sent message's text as the composer can hold it, with the mention records its chips need.
157 * `attachmentChips` maps the context ids of attachments put back in the draft to their new chips.
158 */
159export function recallComposerMessage(
160 message: Pick<ComposerPromptHistoryMessage, "text" | "context">,
161 attachmentChips: ReadonlyMap<string, string> = new Map(),
162): Pick<ComposerPromptHistoryEntry, "prompt" | "mentions"> {
163 const records = message.context?.records ?? [];
164 const threadRecords = records.filter(isThreadContextRecord);
165 const environmentRecords = records.filter(isEnvironmentContextRecord);
166 const prompt = restoreTrailingTokenSpace(
167 replaceComposerContextReferences(
168 recallableComposerPrompt(
169 message.text,
170 new Set([
171 ...[...threadRecords, ...environmentRecords].map((record) => record.contextId),
172 ...attachmentChips.keys(),
173 ]),
174 ),
175 (occurrence) => attachmentChips.get(occurrence.contextId) ?? occurrence.source,
176 ),
177 collectComposerPromptInlineTokens,
178 );
179 // A record whose chip is gone from the text would put the chip back when written to the draft.
180 const referenced = new Set<string>(
181 collectComposerContextReferences(prompt).map((reference) => reference.contextId),
182 );
183 return {
184 prompt,
185 mentions: {
186 threadContexts: threadRecords.filter((record) => referenced.has(record.contextId)),
187 environmentContexts: environmentRecords.filter((record) => referenced.has(record.contextId)),
188 },
189 };
191​
192export function buildComposerPromptHistoryEntries(
193 messages: ReadonlyArray<ComposerPromptHistoryMessage>,
194): ComposerPromptHistoryEntry[] {
195 const entries: ComposerPromptHistoryEntry[] = [];
196 for (const message of messages) {
197 if (message.role !== "user") continue;
198 // Automations and other agents send user-role messages; recall only what the user typed.
199 if (resolveUserMessagePresentation(message).attribution !== null) continue;
200 const { prompt, mentions } = recallComposerMessage(message);
201 if (prompt.length === 0) continue;
202 const entry = { id: message.id, prompt, mentions };
203 const previous = entries[entries.length - 1];
204 if (previous && previous.prompt === prompt) {
205 entries[entries.length - 1] = entry;
206 continue;
207 }
208 entries.push(entry);
209 }
210 return entries;
212​
213function recall(entry: ComposerPromptHistoryEntry): ComposerPromptHistoryStep {
214 return {
215 position: { entryId: entry.id, recalled: entry.prompt },
216 prompt: entry.prompt,
217 mentions: entry.mentions,
218 };
220​
221export function stepComposerPromptHistory(input: {
222 readonly direction: "backward" | "forward";
223 readonly entries: ReadonlyArray<ComposerPromptHistoryEntry>;
224 readonly position: ComposerPromptHistoryPosition | null;
225 readonly currentPrompt: string;
226}): ComposerPromptHistoryStep | null {
227 const { entries, position, currentPrompt } = input;
228 const activeIndex =
229 position && position.recalled === currentPrompt ? findActive(entries, position) : -1;
230​
231 if (input.direction === "backward") {
232 if (activeIndex < 0 && currentPrompt.length > 0) return null;
233 const entry = entries[activeIndex < 0 ? entries.length - 1 : activeIndex - 1];
234 if (!entry) return null;
235 return recall(entry);
236 }
237​
238 if (activeIndex < 0) return null;
239 const entry = entries[activeIndex + 1];
240 if (!entry) return { position: null, prompt: "", mentions: NO_MENTIONS };
241 return recall(entry);