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

TextGenerationPrompts.ts

318 lines12.8 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 attachments?: ReadonlyArray<ChatAttachment> | undefined;
156 additionalInstructions?: string | undefined;
158​
159function buildPromptFromMessage(input: PromptFromMessageInput): string {
160 const attachmentLines = (input.attachments ?? []).map(
161 (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
162 );
163​
164 const promptSections = [
165 input.instruction,
166 input.responseShape,
167 "Rules:",
168 ...input.rules.map((rule) => `- ${rule}`),
169 "",
170 "User message:",
171 limitSection(input.message, 8_000),
172 ...policyInstruction(input.additionalInstructions),
173 ];
174 if (attachmentLines.length > 0) {
175 promptSections.push(
176 "",
177 "Attachment metadata:",
178 limitSection(attachmentLines.join("\n"), 4_000),
179 );
180 }
181​
182 return promptSections.join("\n");
184​
185export function buildBranchNamePrompt(input: BranchNamePromptInput) {
186 const prompt = buildPromptFromMessage({
187 instruction: "You generate concise git branch names.",
188 responseShape: "Return a JSON object with key: branch.",
189 rules: [
190 "Branch should describe the requested work from the user message.",
191 "Keep it short and specific (2-6 words).",
192 "Use plain words only, no issue prefixes and no punctuation-heavy text.",
193 "If images are attached, use them as primary context for visual/UI issues.",
194 ],
195 message: input.message,
196 attachments: input.attachments,
197 additionalInstructions: input.policy?.branchInstructions,
198 });
199 const outputSchema = Schema.Struct({
200 branch: Schema.String,
201 });
202​
203 return { prompt, outputSchema };
205​
206// ---------------------------------------------------------------------------
207// Thread title
208// ---------------------------------------------------------------------------
209​
210export interface ThreadTitlePromptInput {
211 message: string;
212 previousTitle?: string | undefined;
213 attachments?: ReadonlyArray<ChatAttachment> | undefined;
214 policy?: TextGenerationPolicy | undefined;
216​
217// Keep shared editorial rules in these two prompts in sync. Regeneration
218// intentionally adds guidance for thread history and the previous title.
219const INITIAL_THREAD_TITLE_PROMPT = `Generate a title that will help the user recognize this T3 Code thread weeks later.
220Return JSON with exactly one key: title.
221​
222Before answering, silently reduce the request to:
223- Subject: What system, feature, or problem is this really about?
224- Outcome: What does the user ultimately want to understand or change?
225- Incidental instructions: What only describes how the agent should do the work?
226​
227Title the subject and outcome. Discard incidental instructions.
228​
229Editorial rules:
230- 3-8 words, fewer than 40 characters.
231- Use a compact noun phrase or clear action phrase.
232- Capture the umbrella goal when the request lists several symptoms or steps.
233- Name the product change, not the mock, plan, report, branch, or PR used to produce it.
234- Models, subagents, tools, output formats, and monitoring instructions do not belong in the title unless they are themselves the topic.
235- For reviews, name what is being reviewed and the relevant concern. Avoid generic titles such as "Review PR 123" when linked or attached context reveals the subject.
236- For research, name the question domain rather than the requested research process.
237- Do not claim the work is complete.
238- Do not copy and truncate the user's message.
239- Avoid project names already visible in the UI, quotes, labels, filler, and trailing punctuation.
240- Use attached images as primary context for UI issues.
241- When a URL or attachment is the only source of the subject, use available tools to inspect it. If it cannot be resolved, remain accurate rather than guessing.`;
242​
243function regenerateThreadTitlePrompt(previousTitle: string): string {
244 return `Regenerate the title for an existing T3 Code thread so the user can recognize it weeks later.
245The previous title was ${JSON.stringify(previousTitle)}.
246Return JSON with exactly one key: title.
247​
248Determine the title in this order:
2491. Read the USER messages first. Identify the latest explicit durable goal. The original subject remains the subject until the user clearly changes what the thread is about.
2502. Use ASSISTANT messages to resolve vague links, unnamed code, and discovered product nouns. Do not promote one assistant finding into the thread subject unless the user adopts it as a new goal.
2513. Compare that subject with the previous title. Preserve accurate scope words, especially when earlier content is truncated. Replace the previous title when it is generic, artifact-based, a completion update, or contradicted by the thread.
2524. Title the durable subject and desired outcome, not the current workflow state.
253​
254Editorial rules:
255- 3-8 words, fewer than 40 characters.
256- Use a compact noun phrase or clear action phrase.
257- Preserve the umbrella subject when later messages focus on one finding, provider, platform, or implementation detail.
258- A thread progressing through research, planning, implementation, review, CI, merge, and monitoring has usually not changed subjects.
259- Ignore deliverables and operations such as mocks, plans, HTML, branches, PRs, tests, CI, commits, merging, and monitoring unless they are the actual topic.
260- Models, subagents, tools, output formats, and monitoring instructions do not belong in the title unless they are themselves the topic.
261- Treat final operational follow-ups and assistant completion summaries as weak evidence of subject.
262- For reviews, name the reviewed feature or system and its durable concern, not one finding from the review.
263- For research, name the question domain rather than the research process.
264- Do not claim the work is complete.
265- Do not copy and truncate a thread message.
266- Avoid project names already visible in the UI, PR numbers, quotes, labels, filler, and trailing punctuation.
267- Use attached images as primary context for UI issues.
268- When a URL or attachment is the only source of the subject, use available tools to inspect it. If it cannot be resolved, remain accurate rather than guessing.
269- Return a meaningfully improved title, not a cosmetic paraphrase of the previous title.
270​
271Examples of the distinction:
272- A subagent-monitoring review that finds a Codex roster bug remains "Review Subagent Monitoring Risks," not "Codex Roster Bug Review."
273- A vague failing-test request later identified as a lazy thread-feed mismatch becomes "Fix Lazy Thread Feed Test," not "Prevent Mobile Feed Regressions."
274- A QR-sharing overhaul that ends with CI and merge work remains about QR sharing, not the PR lifecycle.`;
276​
277function preserveMessageEnd(message: string): string {
278 const alreadyTruncated = message.startsWith(EARLIER_CONTENT_TRUNCATION_MARKER);
279 const contents = alreadyTruncated
280 ? message.slice(EARLIER_CONTENT_TRUNCATION_MARKER.length)
281 : message;
282 if (!alreadyTruncated && contents.length <= 8_000) {
283 return contents;
284 }
285 return `${EARLIER_CONTENT_TRUNCATION_MARKER}${contents.slice(-8_000)}`;
287​
288function threadTitlePromptSuffix(input: ThreadTitlePromptInput): string {
289 const additionalInstructions = policyInstruction(input.policy?.threadTitleInstructions);
290 const attachmentLines = (input.attachments ?? []).map(
291 (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
292 );
293​
294 let suffix = "";
295 if (additionalInstructions.length > 0) {
296 suffix = `\n${additionalInstructions.join("\n")}`;
297 }
298 if (attachmentLines.length > 0) {
299 suffix += `\n\nAttachment metadata:\n${limitSection(attachmentLines.join("\n"), 4_000)}`;
300 }
301 return suffix;
303​
304export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
305 let prompt: string;
306 if (input.previousTitle === undefined) {
307 const message = limitSection(input.message, 8_000);
308 prompt = `${INITIAL_THREAD_TITLE_PROMPT}\n\nUser message:\n${message}${threadTitlePromptSuffix(input)}`;
309 } else {
310 const message = preserveMessageEnd(input.message);
311 prompt = `${regenerateThreadTitlePrompt(input.previousTitle)}\n\nThread contents:\n${message}${threadTitlePromptSuffix(input)}`;
312 }
313 const outputSchema = Schema.Struct({
314 title: Schema.String,
315 });
316​
317 return { prompt, outputSchema };