Rewrites the draft in the prompt box into a better prompt for the active project: aimed at the outcome, held to an expert standard and checked by more than the…

A Claude Code mod that turns a rough prompt into one that gets a better result.
Type a prompt, then click the orange Enhance prompt button above the prompt box. Review the result and send it yourself. Restore original puts your text back.
In a terminal, the buttons take clicks only in fullscreen mode: run /tui fullscreen once. Without it, use /enhance <prompt> and /prompt-enhancer:create-project-context.
You can also type /enhance <prompt> and press Enter. Nothing goes to Claude: the result goes in the prompt box.

In a Claude Code terminal session, run:
/plugin install prompt-enhancer --marketplace https://github.com/Abdoul-sudo/prompt-enhancer.git
Answer y, then pick the user scope. The mod loads in every session, the desktop app included.
The mod reads:
project-context.md, if you have one.Then it rewrites your draft the way an expert would:
Inspired by Felix Rieseberg's How to be more ambitious.
Add a project-context.md file to your project: a short description of the project and its features. The mod reads it to write better prompts.
/prompt-enhancer:create-project-context./prompt-enhancer:project-context.
The mod uses the sonnet model at medium effort. Each click counts on your Claude Code account.
To change this, edit MODEL and EFFORT at the top of hooks/register.tsx. Then start a new session. An update deletes your edits. To keep them, fork the repository.
Run these two commands in your shell:
claude plugin marketplace update prompt-enhancer
claude plugin update prompt-enhancer@prompt-enhancer
Then start a new session.
To update on its own: run /plugin in a terminal session. Open Marketplaces, pick prompt-enhancer, then pick Enable auto-update.
The Claude desktop app never updates plugins on its own. Run the two commands above from time to time.
hooks/register.tsx 449 lines1import { atom, read, update } from "claude-code";
2import type { EngineInterface, Register } from "claude-code";
3
4const hasDraft = atom(
5 { plugin: "prompt-enhancer", key: "hasDraft" } as const,
6 null,
7);
8const isBusy = atom(
9 { plugin: "prompt-enhancer", key: "isBusy" } as const,
10 false,
11);
12const original = atom(
13 { plugin: "prompt-enhancer", key: "original" } as const,
14 null,
15);
16const hasProjectContext = atom(
17 { plugin: "prompt-enhancer", key: "hasProjectContext" } as const,
18 null,
19);
20const contextRequest = atom(
21 { plugin: "prompt-enhancer", key: "contextRequest" } as const,
22 null,
23);
24
25const MAX_MESSAGE_CHARS = 2000;
26/** One exchange is the user's message and the agent's reply. */
27const RECENT_EXCHANGES = 8;
28/** The project description the mod reads; its `create-project-context` and `project-context` skills write it. */
29const PROJECT_CONTEXT_FILE = "project-context.md";
30const LIVE_AGENT: ReadonlySet<string> = new Set(["pending", "running", "waiting"]);
31/** The mod's own skill as a slash command: the button runs it as if the person typed it. */
32const PROJECT_CONTEXT_COMMAND = "prompt-enhancer:create-project-context";
33const MAX_CONTEXT_FILE_CHARS = 20000;
34/** Alias the engine resolves to the newest Sonnet, as `--model sonnet` does. */
35const MODEL = "sonnet";
36/** Tested: as fast as low on short drafts, with shorter and cleaner rewrites. */
37const EFFORT = "medium";
38const ORANGE = "#F97316";
39const ORANGE_HOVER = "#FB923C";
40const BLUE = "#60A5FA";
41const BLUE_HOVER = "#93C5FD";
42const PERSON_ORIGINS: ReadonlySet<string> = new Set([
43 "composer",
44 "bridge",
45 "sdk",
46]);
47/** `/enhance <prompt>` as typed, or `/prompt-enhancer:enhance <prompt>`, the command commands/enhance.md lists. */
48const ENHANCE_PATTERN = /^\/(?:prompt-enhancer:)?enhance(?:\s+([\s\S]*))?$/;
49
50/** The draft after `/enhance`, or undefined when `text` is not that command. */
51export function enhanceArgs(text: string): string | undefined {
52 const match = ENHANCE_PATTERN.exec(text.trim());
53 return match === null ? undefined : (match[1] ?? "");
54}
55
56/**
57 * Turns a model id into the name people use: `claude-opus-5-5` into "Claude Opus 5.5".
58 * Anything that is not a `claude-` id, such as an alias, comes back as given.
59 */
60export function modelName(id: string): string {
61 const match = /^claude-([a-z]+)-(\d+(?:-\d+)*)/.exec(id);
62 if (match === null) return id;
63 const [, family = "", version = ""] = match;
64 return `Claude ${family.charAt(0).toUpperCase()}${family.slice(1)} ${version.replace(/-/g, ".")}`;
65}
66
67/** The draft's first words, quoted next to the language rule so the conversation's language does not win. */
68function draftOpening(draft: string): string {
69 return draft.trim().split(/\s+/).slice(0, 12).join(" ");
70}
71
72/**
73 * The instruction sent after the project's context; the draft is data inside it.
74 * `targetModel` is the model the session runs, the one that will read the prompt.
75 * The method is Felix Rieseberg's "How to be more ambitious": aim at the outcome,
76 * work to the standard of the field's best, let an outside judge decide, and bring
77 * in another field only where it fits. It raises the result, never the size of the job.
78 */
79export function enhanceRequest(draft: string, targetModel: string): string {
80 return `<draft_prompt>
81${draft}
82</draft_prompt>
83
84Rewrite the user's draft above into a better prompt for ${modelName(targetModel)}, an AI agent working in the user's project through Claude Code. The agent can explore, run and change the project, and it follows its own project instructions. Your job is to improve the prompt, not to do the task or answer it.
85
86<principles>
87Improve the outcome, not the instructions. Turn the draft into a clearer, more precise and more effective request. Understand what the user actually wants to achieve, raise the quality of the expected result, and keep their intent, scope and permissions. The user pressed Enhance, so always add real value, even when the draft is already clear.
88
89Better, not bigger. Understand the goal behind the task, raise the standard of the result to what the best expert in the field would expect, and bring in perspectives from other fields when they would make the result better. Add that expertise without widening the scope, adding unrelated work or making the prompt more complex than it needs to be.
90
91Focus on the outcome, not the process. Say what the problem is, what result the user wants and what matters about it. Leave the investigation, technical decisions, implementation and verification strategy to the agent. Don't anticipate its reasoning with lists of possible causes, hypothetical scenarios, technical approaches or steps; include such details only when the user's request contains them or when they change the expected result.
92
93Keep the nature of the request. A draft that asks why, how, what or whether is a question, even when it points at a bug: the prompt asks the agent to find out and explain, and to change nothing, because the user decides what to change once they have the answer. An investigation stays an investigation, and a request for changes clearly says to make them. When the user asks for a problem to be fixed, ask for the underlying cause to be fixed, not the symptom. For creative work, describe the intended experience and the quality bar, and leave room for exploration and original solutions.
94
95Use context intelligently. Bring in what the conversation and the project context make clear when it adds real precision, such as the feature, screen or decision in question, and keep the decisions and constraints already settled. Invent no files, commands, technical details, causes or facts. Add no hypothetical limitation, uncertainty or fallback ("if the feature doesn't exist, tell me") unless the conversation or the project context shows it applies: it pulls the agent away from the real problem. When a word in the draft is vague and the context doesn't explain it, keep it open and let the agent find what it refers to, rather than guessing a meaning. Leave out what the agent can find better on its own.
96
97Define what success looks like. Make the expected result clear and, where it helps, say how success will be recognized. Prefer outcomes and evidence over a prescribed testing procedure, and impose no tool, test, metric or deliverable the user didn't ask for.
98
99Be selective. Every addition should improve the agent's understanding or the quality of its result. Leave out explanations, speculative diagnoses, exhaustive checklists, repetition and generic advice. The goal is not the most detailed prompt but the most effective one.
100</principles>
101
102<output>
103Write the improved prompt in the first person, as natural, clearly separated paragraphs, without fixed headings or templates. Fit the structure, length and depth to the task: a simple request stays short, a complex one gets the detail it needs. Use headings or lists only when they make it clearer.
104
105Keep the code, paths, commands, identifiers, error messages and quotes the user wrote exactly as written, and improve the prose around them freely.
106
107Write the prompt in the same language as the draft, which begins: "${draftOpening(draft)}". The user picks the language of each message on purpose, so the language of the conversation or of the project context says nothing about this one.
108
109Return only the improved prompt inside <prompt></prompt> tags, with no analysis, commentary or explanation.
110</output>`;
111}
112
113/**
114 * Takes the rewritten prompt out of the model's reply; undefined when nothing usable came back.
115 * A <plan> block, if the model writes one, is its own notes and never reaches the prompt box.
116 */
117export function extractPrompt(reply: string): string | undefined {
118 const withoutPlan = reply.replace(/<plan>[\s\S]*?<\/plan>/g, "");
119 // The last <prompt> block; one cut short by the token cap runs to the end of the reply.
120 const tagged = [
121 ...withoutPlan.matchAll(/<prompt>([\s\S]*?)(?:<\/prompt>|$)/g),
122 ].at(-1)?.[1];
123 const text = (
124 tagged ?? (withoutPlan.includes("<plan>") ? "" : withoutPlan)
125 ).trim();
126 return text === "" ? undefined : text;
127}
128
129function clip(text: string, max: number): string {
130 return text.length > max ? `${text.slice(0, max)}\n[...cut]` : text;
131}
132
133/**
134 * The latest exchanges of the conversation, the user's messages and the agent's
135 * replies alike. User rows that are machine text (task notices, reminders) start
136 * with a tag and are left out.
137 */
138export function recentMessages<M extends { role: string; text: string }>(
139 messages: readonly M[],
140): M[] {
141 return messages
142 .filter(
143 (m) =>
144 m.text.trim() !== "" &&
145 !(m.role === "user" && m.text.trimStart().startsWith("<")),
146 )
147 .slice(-2 * RECENT_EXCHANGES);
148}
149
150/** What the enhancer knows of the project: where it runs, its project-context.md and the latest messages. */
151export type ProjectContext = {
152 cwd: string;
153 contextFile?: { path: string; text: string };
154 messages: readonly { role: string; text: string }[];
155};
156
157/** The system prompt: the enhancer's job, then the project's context. */
158export function enhancerSystem(context: ProjectContext): string {
159 const parts: string[] = [`Working directory: ${context.cwd}`];
160 // project-context.md describes the project itself (what it is, its features, its parts), so it is sent whole.
161 if (
162 context.contextFile !== undefined &&
163 context.contextFile.text.trim() !== ""
164 ) {
165 const { path, text } = context.contextFile;
166 parts.push(
167 `<project_context path="${path}">\n${clip(text, MAX_CONTEXT_FILE_CHARS)}\n</project_context>`,
168 );
169 }
170 const recent = recentMessages(context.messages);
171 if (recent.length > 0) {
172 const lines = recent.map(
173 (m) => `<${m.role}>\n${clip(m.text, MAX_MESSAGE_CHARS)}\n</${m.role}>`,
174 );
175 parts.push(
176 `The conversation so far (latest messages, for context only; the prompt keeps the draft's language, not theirs):\n${lines.join("\n")}`,
177 );
178 }
179 return `You are a prompt enhancer. You turn a developer's draft into the prompt they send to their AI coding agent in this project. You write that prompt; you never do the task or answer the draft. The project's context:\n\n${parts.join("\n\n")}`;
180}
181
182/**
183 * The project's context, read live: project-context.md and the end of the conversation.
184 * CLAUDE.md, skills and tools are left out: the agent that runs the prompt already has them.
185 */
186async function projectContext($: EngineInterface): Promise<ProjectContext> {
187 const path = await projectContextPath($);
188 const text = await $.fs.read(path).catch(() => "");
189 const messages = await $.session.messages().catch(() => []);
190 return {
191 cwd: await $.session.cwd(),
192 contextFile: { path, text },
193 messages: Array.isArray(messages) ? messages : [],
194 };
195}
196
197/** Rewrites the draft with one Sonnet call at medium effort, fed the project's context. */
198async function rewrite(
199 $: EngineInterface,
200 draft: string,
201): Promise<{ text: string } | { reason: string }> {
202 const reply = await $.model.complete({
203 model: MODEL,
204 effort: EFFORT,
205 system: enhancerSystem(await projectContext($)),
206 prompt: enhanceRequest(draft, await $.session.model()),
207 maxTokens: 16000,
208 timeoutMs: 120000,
209 });
210 if (!reply.isAnswered) return { reason: reply.reason };
211 const text = extractPrompt(reply.text);
212 return text === undefined ? { reason: "empty-reply" } : { text };
213}
214
215/**
216 * Enhances `draft`, or the prompt box's draft when none is given, and puts the
217 * result in the box without sending it. Answers a line for the caller to show.
218 */
219async function enhance($: EngineInterface, draft?: string): Promise<string> {
220 if (await read($, isBusy)) return "Already enhancing.";
221 const source = draft ?? (await $.prompt.read()).text;
222 if (source.trim() === "") return "Type a prompt first, then enhance it.";
223 await update($, isBusy, () => true);
224 try {
225 const result = await rewrite($, source);
226 if ("reason" in result)
227 return `Could not enhance the prompt (${result.reason}).`;
228 const box = await $.prompt.read();
229 const isOverwritingEdits =
230 draft === undefined ? box.text !== source : box.text.trim() !== "";
231 if (isOverwritingEdits)
232 return "The prompt box changed while enhancing. Your text was kept.";
233 const filled = await $.prompt.fill({ text: result.text });
234 if (!filled.isFilled) {
235 const copied = await $.ui.copy({ text: result.text });
236 return copied.isCopied
237 ? "The prompt box is busy. The enhanced prompt is on the clipboard."
238 : "The prompt box is busy. Try again.";
239 }
240 await update($, original, () => source);
241 await update($, hasDraft, () => true);
242 return "Prompt enhanced. Review it, then send.";
243 } finally {
244 await update($, isBusy, () => false);
245 }
246}
247
248async function restore($: EngineInterface): Promise<void> {
249 const text = await read($, original);
250 if (text === null) return;
251 const filled = await $.prompt.fill({ text });
252 if (!filled.isFilled) {
253 $.ui.toast("The prompt box is busy. Try again.");
254 return;
255 }
256 await update($, original, () => null);
257}
258
259/**
260 * Where the project's project-context.md lives: the folder the session started in,
261 * never a parent folder, so a file from another project is never read.
262 */
263async function projectContextPath($: EngineInterface): Promise<string> {
264 return `${await $.session.root()}/${PROJECT_CONTEXT_FILE}`;
265}
266
267/** Whether the project has a project-context.md, so the band offers to create one only when it is missing. */
268async function refreshProjectContext($: EngineInterface): Promise<void> {
269 // A check that fails says nothing about the file: the button shows only when the file is known to be missing.
270 const exists = await $.fs
271 .exists(await projectContextPath($))
272 .catch(() => null);
273 await update($, hasProjectContext, () => exists);
274}
275
276/** Asks Claude to write project-context.md with the mod's skill, as a turn the user watches. */
277async function createProjectContext($: EngineInterface): Promise<void> {
278 // One request at a time: the button hides until the turn that answers it ends.
279 if ((await read($, contextRequest)) !== null) return;
280 await update($, contextRequest, () => "queued");
281 // The skill holds the rules; the button only runs it. The command waits for the session to be idle.
282 void $.command.run({ command: PROJECT_CONTEXT_COMMAND }).catch(async (error: unknown) => {
283 await update($, contextRequest, () => null);
284 $.ui.toast(`Could not run /${PROJECT_CONTEXT_COMMAND} (${String(error)}).`);
285 });
286}
287
288export const register: Register = (on) => {
289 let knownDraft: boolean | null = null;
290
291 on("session.start", async ($, e, next) => {
292 await update($, isBusy, () => false);
293 await update($, contextRequest, () => null);
294 await refreshProjectContext($);
295 return next(e);
296 });
297
298 // Tracks only whether the box is empty, so the band shows when there is something to enhance.
299 on("prompt.edit", async ($, e, next) => {
300 const box = await next(e);
301 const hasText = box.text.trim() !== "";
302 if (hasText !== knownDraft) {
303 knownDraft = hasText;
304 await update($, hasDraft, () => hasText);
305 }
306 return box;
307 }).catch(($, e, next) => next(e));
308
309 // Only a prompt the person sends empties their box; task notices, schedules and peers leave it as it is.
310 on("prompt.submit", async ($, e, next) => {
311 if (!PERSON_ORIGINS.has(e.origin.kind)) return next(e);
312 // `/enhance <prompt>` typed in full, which no command answers: rewritten into the box, never sent.
313 const draft = enhanceArgs(e.text);
314 if (draft !== undefined) return { drop: await enhance($, draft) };
315 knownDraft = false;
316 await update($, hasDraft, () => false);
317 await update($, original, () => null);
318 return next(e);
319 });
320
321 // commands/enhance.md lists /prompt-enhancer:enhance, even before the session exists; the mod answers it, never the model.
322 on("command.run", { command: "prompt-enhancer:enhance" }, async ($, e) => ({
323 text: await enhance($, e.args),
324 }));
325
326 // The queued command starts as the next main-loop turn. Each main-loop turn also checks the file again.
327 on("turn.start", async ($, e, next) => {
328 if (e.agentId === undefined) {
329 if ((await read($, contextRequest)) === "queued")
330 await update($, contextRequest, () => "running");
331 await refreshProjectContext($).catch(() => undefined);
332 }
333 return next(e);
334 });
335
336 // The desktop app prepares a session before the person picks its folder, so session.start may have
337 // checked another folder; the app attaching to the session is the first sign of the real one.
338 on("session.attach", async ($, e, next) => {
339 await refreshProjectContext($).catch(() => undefined);
340 return next(e);
341 });
342
343 // A turn may have created or removed project-context.md. The request outlives the turn that ran the
344 // command while its subagents still work, since a later turn picks up their results.
345 on("turn.complete", async ($, e, next) => {
346 if (e.agentId === undefined) {
347 await refreshProjectContext($).catch(() => undefined);
348 if ((await read($, contextRequest)) === "running") {
349 const agents = await $.agent.list().catch(() => []);
350 const isWorking = agents.some((agent) => LIVE_AGENT.has(agent.status));
351 if ((await read($, hasProjectContext)) || !isWorking)
352 await update($, contextRequest, () => null);
353 }
354 }
355 return next(e);
356 });
357
358 on("ui.message", { element: "create-context" }, async ($, e, next) => {
359 if (e.data === "press") await createProjectContext($);
360 return next(e);
361 });
362
363 // The orange Client button posts 'press' when clicked or when Enter reaches it.
364 on("ui.message", { element: "enhance" }, async ($, e, next) => {
365 if (e.data === "press") $.ui.toast(await enhance($));
366 return next(e);
367 });
368
369 on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
370 if (e.props.hasSurvey) return next(e);
371 const busy = await read($, isBusy);
372 const draft = await read($, hasDraft);
373 const before = await read($, original);
374 const canEnhance = !busy && draft !== false;
375 // The last check may have looked at another folder (see session.attach): look again before offering.
376 const canCreateContext =
377 !busy &&
378 (await read($, contextRequest)) === null &&
379 (await read($, hasProjectContext)) === false &&
380 (await $.fs.exists(await projectContextPath($)).catch(() => true)) === false;
381 if (!busy && !canEnhance && before === null && !canCreateContext)
382 return next(e);
383 const elements = $.ui.resolve(e);
384 const { Box, Button, Text } = elements;
385 const Client = "Client" in elements ? elements.Client : undefined;
386 const below = await next(e);
387 return (
388 <Box flexDirection="column">
389 <Box flexDirection="row" justifyContent="flex-end" width="100%" gap={1}>
390 {canCreateContext &&
391 (Client !== undefined ? (
392 <Client
393 key="create-context"
394 module="./color_button.tsx"
395 props={{
396 label: "Create project context",
397 color: BLUE,
398 hoverColor: BLUE_HOVER,
399 }}
400 />
401 ) : (
402 <Button
403 key="create-context"
404 onPress={() => createProjectContext($)}
405 >
406 <Text color={BLUE} bold>
407 Create project context
408 </Text>
409 </Button>
410 ))}
411 {busy && <Text color={ORANGE}>Enhancing prompt…</Text>}
412 {canEnhance &&
413 (Client !== undefined ? (
414 <Client
415 key="enhance"
416 module="./color_button.tsx"
417 props={{
418 label: "Enhance prompt",
419 color: ORANGE,
420 hoverColor: ORANGE_HOVER,
421 }}
422 />
423 ) : (
424 <Button
425 key="enhance"
426 hotkey="e"
427 onPress={async () => $.ui.toast(await enhance($))}
428 >
429 <Text color={ORANGE} bold>
430 Enhance prompt
431 </Text>
432 </Button>
433 ))}
434 {!busy && before !== null && (
435 <Button
436 key="restore"
437 label="↶ Restore original"
438 hotkey="r"
439 dimColor
440 onPress={() => restore($)}
441 />
442 )}
443 </Box>
444 {below}
445 </Box>
446 );
447 });
448};
449hooks/color_button.tsx 32 lines1import type { ClientModule } from 'claude-code'
2
3type Props = { label: string; color: string; hoverColor: string }
4type State = { isHovered: boolean }
5
6/**
7 * A clickable label on a colored background. The desktop draws every `Button`
8 * as its own native control and ignores colors inside it; a `Client` region is
9 * drawn with the plugin's own colors, so the press is posted to the hooks module.
10 */
11const ColorButton: ClientModule<Props, State> = (props, surface) => {
12 const { Box, Text } = surface.elements
13 const isHovered = surface.state?.isHovered ?? false
14 const isInside = (x: number, y: number) => x >= 0 && y >= 0 && x < surface.columns && y < surface.rows
15 surface.onPointer(e => {
16 if (e.type === 'enter' || e.type === 'leave') surface.setState({ isHovered: e.type === 'enter' })
17 if (e.type === 'up' && e.button === 'left' && isInside(e.x, e.y)) surface.post('press')
18 })
19 surface.onKey(e => {
20 if (e.key === 'return' || e.key === ' ') surface.post('press')
21 })
22 return (
23 <Box backgroundColor={isHovered ? props.hoverColor : props.color} paddingX={2}>
24 <Text color="#000000" bold>
25 {props.label}
26 </Text>
27 </Box>
28 )
29}
30
31export default ColorButton
32types/index.d.ts 19 lines1/** The draft before the last rewrite, while it can be restored. */
2export type OriginalDraft = string | null
3
4declare module 'claude-code' {
5 interface PluginState {
6 'prompt-enhancer': {
7 /** Whether the prompt box holds text; null until the first edit is seen. */
8 hasDraft: boolean | null
9 /** True while a rewrite runs. */
10 isBusy: boolean
11 original: OriginalDraft
12 /** Whether the project has a project-context.md; null until checked. */
13 hasProjectContext: boolean | null
14 /** The pending Create project context request: 'queued', then 'running' until the file exists or no agent still works; null when none. */
15 contextRequest: string | null
16 }
17 }
18}
19