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