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

TextGenerationPrompts.ts

273 lines9.0 KB

1/**
2 * Shared prompt builders for text generation providers.
3 *
4 * Extracts the prompt construction logic that is identical across
5 * Codex, Claude, and any future CLI-based text generation backends.
6 *
7 * @module textGenerationPrompts
8 */
9import * as Schema from "effect/Schema";
10import type { ChatAttachment } from "@t3tools/contracts";
11​
12import { limitSection } from "./TextGenerationUtils.ts";
13import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";
14​
15const EARLIER_CONTENT_TRUNCATION_MARKER = "[Earlier content truncated]\n\n";
16​
17function policyInstruction(instruction: string | undefined): ReadonlyArray<string> {
18 const trimmed = instruction?.trim();
19 return trimmed ? ["", "Additional instructions:", limitSection(trimmed, 4_000)] : [];
21​
22// ---------------------------------------------------------------------------
23// Commit message
24// ---------------------------------------------------------------------------
25​
26export interface CommitMessagePromptInput {
27 branch: string | null;
28 stagedSummary: string;
29 stagedPatch: string;
30 includeBranch?: boolean;
31 policy?: TextGenerationPolicy | undefined;
33​
34export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
35 const wantsBranch = input.includeBranch === true;
36​
37 const prompt = [
38 "You write concise git commit messages.",
39 wantsBranch
40 ? "Return a JSON object with keys: subject, body, branch."
41 : "Return a JSON object with keys: subject, body.",
42 "Rules:",
43 "- subject must be imperative, <= 72 chars, and no trailing period",
44 "- body can be empty string or short bullet points",
45 ...(wantsBranch
46 ? ["- branch must be a short semantic git branch fragment for this change"]
47 : []),
48 "- capture the primary user-visible or developer-visible change",
49 ...policyInstruction(input.policy?.commitInstructions),
50 "",
51 `Branch: ${input.branch ?? "(detached)"}`,
52 "",
53 "Staged files:",
54 limitSection(input.stagedSummary, 6_000),
55 "",
56 "Staged patch:",
57 limitSection(input.stagedPatch, 40_000),
58 ].join("\n");
59​
60 if (wantsBranch) {
61 return {
62 prompt,
63 outputSchema: Schema.Struct({
64 subject: Schema.String,
65 body: Schema.String,
66 branch: Schema.String,
67 }),
68 };
69 }
70​
71 return {
72 prompt,
73 outputSchema: Schema.Struct({
74 subject: Schema.String,
75 body: Schema.String,
76 }),
77 };
79​
80// ---------------------------------------------------------------------------
81// Change request content
82// ---------------------------------------------------------------------------
83​
84export interface PrContentPromptInput {
85 baseBranch: string;
86 headBranch: string;
87 commitSummary: string;
88 diffSummary: string;
89 diffPatch: string;
90 changeRequestTemplate?: string | undefined;
91 policy?: TextGenerationPolicy | undefined;
93​
94export function buildPrContentPrompt(input: PrContentPromptInput) {
95 const changeRequestTemplate = input.changeRequestTemplate?.trim();
96 const bodyRules = changeRequestTemplate
97 ? [
98 "- body must be markdown and follow the repository change request template structure",
99 "- fill in the template sections appropriately for this change",
100 "- drop HTML comments from the template in the generated body",
101 "- keep the template's markdown structure",
102 ]
103 : [
104 "- body must be markdown and include headings '## Summary' and '## Testing'",
105 "- under Summary, provide short bullet points",
106 "- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
107 ];
108 const prompt = [
109 "You write source control change request content.",
110 "Return a JSON object with keys: title, body.",
111 "Rules:",
112 "- title should be concise and specific",
113 ...bodyRules,
114 ...policyInstruction(input.policy?.changeRequestInstructions),
115 ...(changeRequestTemplate
116 ? ["", "Repository change request template:", limitSection(changeRequestTemplate, 8_000)]
117 : []),
118 "",
119 `Base branch: ${input.baseBranch}`,
120 `Head branch: ${input.headBranch}`,
121 "",
122 "Commits:",
123 limitSection(input.commitSummary, 12_000),
124 "",
125 "Diff stat:",
126 limitSection(input.diffSummary, 12_000),
127 "",
128 "Diff patch:",
129 limitSection(input.diffPatch, 40_000),
130 ].join("\n");
131​
132 const outputSchema = Schema.Struct({
133 title: Schema.String,
134 body: Schema.String,
135 });
136​
137 return { prompt, outputSchema };
139​
140// ---------------------------------------------------------------------------
141// Branch name
142// ---------------------------------------------------------------------------
143​
144export interface BranchNamePromptInput {
145 message: string;
146 attachments?: ReadonlyArray<ChatAttachment> | undefined;
147 policy?: TextGenerationPolicy | undefined;
149​
150interface PromptFromMessageInput {
151 instruction: string;
152 responseShape: string;
153 rules: ReadonlyArray<string>;
154 message: string;
155 messageLabel?: string | undefined;
156 preserveMessageEnd?: boolean | undefined;
157 attachments?: ReadonlyArray<ChatAttachment> | undefined;
158 additionalInstructions?: string | undefined;
160​
161function preserveMessageEnd(message: string): string {
162 const alreadyTruncated = message.startsWith(EARLIER_CONTENT_TRUNCATION_MARKER);
163 const contents = alreadyTruncated
164 ? message.slice(EARLIER_CONTENT_TRUNCATION_MARKER.length)
165 : message;
166 if (!alreadyTruncated && contents.length <= 8_000) {
167 return contents;
168 }
169 return `${EARLIER_CONTENT_TRUNCATION_MARKER}${contents.slice(-8_000)}`;
171​
172function buildPromptFromMessage(input: PromptFromMessageInput): string {
173 const attachmentLines = (input.attachments ?? []).map(
174 (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
175 );
176​
177 const promptSections = [
178 input.instruction,
179 input.responseShape,
180 "Rules:",
181 ...input.rules.map((rule) => `- ${rule}`),
182 "",
183 `${input.messageLabel ?? "User message"}:`,
184 input.preserveMessageEnd
185 ? preserveMessageEnd(input.message)
186 : limitSection(input.message, 8_000),
187 ...policyInstruction(input.additionalInstructions),
188 ];
189 if (attachmentLines.length > 0) {
190 promptSections.push(
191 "",
192 "Attachment metadata:",
193 limitSection(attachmentLines.join("\n"), 4_000),
194 );
195 }
196​
197 return promptSections.join("\n");
199​
200export function buildBranchNamePrompt(input: BranchNamePromptInput) {
201 const prompt = buildPromptFromMessage({
202 instruction: "You generate concise git branch names.",
203 responseShape: "Return a JSON object with key: branch.",
204 rules: [
205 "Branch should describe the requested work from the user message.",
206 "Keep it short and specific (2-6 words).",
207 "Use plain words only, no issue prefixes and no punctuation-heavy text.",
208 "If images are attached, use them as primary context for visual/UI issues.",
209 ],
210 message: input.message,
211 attachments: input.attachments,
212 additionalInstructions: input.policy?.branchInstructions,
213 });
214 const outputSchema = Schema.Struct({
215 branch: Schema.String,
216 });
217​
218 return { prompt, outputSchema };
220​
221// ---------------------------------------------------------------------------
222// Thread title
223// ---------------------------------------------------------------------------
224​
225export interface ThreadTitlePromptInput {
226 message: string;
227 previousTitle?: string | undefined;
228 attachments?: ReadonlyArray<ChatAttachment> | undefined;
229 policy?: TextGenerationPolicy | undefined;
231​
232export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
233 const isRegeneration = input.previousTitle !== undefined;
234 const prompt = buildPromptFromMessage({
235 instruction: isRegeneration
236 ? [
237 "You write concise thread titles for coding conversations.",
238 "The user requested a new title based on the contents of this thread.",
239 `The previous title was ${JSON.stringify(input.previousTitle)}.`,
240 "Come up with a new title that better represents the current state of the thread.",
241 ].join("\n")
242 : "You write concise thread titles for coding conversations.",
243 responseShape: "Return a JSON object with key: title.",
244 rules: [
245 isRegeneration
246 ? "Title should summarize the thread's current state, not just its initial request."
247 : "Title should summarize the user's request, not restate it verbatim.",
248 ...(isRegeneration
249 ? [
250 "Capture the thread's intent, not a PR number or other superficial detail.",
251 "Return a different title from the previous title.",
252 ]
253 : []),
254 "Keep it short and specific (3-8 words).",
255 "Avoid quotes, filler, prefixes, and trailing punctuation.",
256 "If images are attached, use them as primary context for visual/UI issues.",
257 ],
258 message: input.message,
259 ...(isRegeneration
260 ? {
261 messageLabel: "Thread contents",
262 preserveMessageEnd: true,
263 }
264 : {}),
265 attachments: input.attachments,
266 additionalInstructions: input.policy?.threadTitleInstructions,
267 });
268 const outputSchema = Schema.Struct({
269 title: Schema.String,
270 });
271​
272 return { prompt, outputSchema };