SLOPSHOPPER

prompt-sharpen

/prompt-sharpen:upgrade <prompt> opens a pane that asks a few clarifying questions with recommended answers, then rewrites the prompt clearer and more complete…

panetoastmodel
A shopper browsing a rack in a slop shop
README

prompt-sharpen

/prompt-sharpen:upgrade <prompt> opens a pane that walks your prompt through three steps: Questions, Rewrite, Review.

Questions

Asks up to three multiple-choice questions about what the prompt leaves open. Each has its recommended answer already picked: change it, type your own with Other, or Skip.

Questions step

Rewrite

Rewrites the prompt clearer and more complete with the same intent, keeping every detail of the original. It adds only what came from your answers, the conversation, or structure and output format.

  • An answer you left on its recommended option is written as an assumption.
  • Anything still unknown stays a [placeholder].
  • A pasted image shows up as [Image #N]; the rewrite keeps it as written and never guesses what it shows.

Review

Shows the sharpened prompt first, then what was added, with your original as a single line below.

Review step

ActionWhat it does
Run itSends it (with a warning and Run anyway while a [placeholder] is left). Hidden, with Send original, while the prompt has an [Image #N]: the image is not sent, so use Edit and attach it again
EditPuts it in the prompt to change first
CopyCopies it
Send originalSends what you typed
Cancel / EscPuts your original back in the prompt

Notes

  • It asks the session's own model over this conversation, or without it in a new or cleared one.
  • Where the pane cannot open, your prompt goes back in the prompt untouched.

Install

/plugin install prompt-sharpen --marketplace thitiwats/claude-mods

Develop

claude plugin validate plugins/prompt-sharpen
claude plugin test plugins/prompt-sharpen

Grade the questions and rewrites with a real model and a judge model (about $1 a run on Opus; results go to eval/results-<model>.json):

bun plugins/prompt-sharpen/eval/run.ts [--model opus] [--judge opus] [--case <name>]
Source 2 files
hooks/register.tsx 438 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { Answer, Ask, Question, Rewrite, Upgrade } from '../types'
5
6const PANE = 'prompt-sharpen'
7// Declared in commands/upgrade.md, not registered at session.start: desktop reads its command menu with hooks disabled.
8const COMMAND = 'prompt-sharpen:upgrade'
9const USAGE = `Usage: /${COMMAND} <prompt>`
10
11const MAX_QUESTIONS = 3
12const MAX_OPTIONS = 4
13
14const upgrade = atom({ plugin: 'prompt-sharpen', key: 'upgrade' } as const, null as Upgrade | null)
15
16const IDLE = { status: 'idle' } as const
17const LOADING = { status: 'loading' } as const
18
19// Translated jargon reads oddly to developers writing in Thai and other languages, who keep it in English.
20const LANGUAGE =
21  'Write in the language the prompt is written in, the way a developer who speaks it writes: keep technical terms in English ' +
22  '(code identifiers, file names, commands, tools, libraries, and jargon such as commit, pull request, deploy, refactor, endpoint), never translated or transliterated.'
23
24const questionsPrompt = (original: string) =>
25  [
26    'The user wants to send the prompt below to you, and asked to improve it first.',
27    'Ask at most 3 multiple-choice clarifying questions about what the prompt leaves open that would most change the result.',
28    'Ask one only when the user\'s intent could go two ways that lead to clearly different results, and neither the prompt nor this conversation settles it.',
29    'Never ask about what you could find by reading the code or files, edge cases or implementation details you would sensibly decide yourself, or work the prompt does not mention (tests, docs, error handling).',
30    'When the prompt already says what to do and where, ask none and reply {"questions":[]}: that is the expected answer for a clear prompt.',
31    'Give each question 2 to 4 short options. Put first the option you judge most likely matches what the user means,',
32    'given this conversation: it is shown to them as the recommended one.',
33    `Questions and options: ${LANGUAGE}`,
34    'Reply with JSON only, no markdown: {"questions":[{"question":"...","options":["...","..."]}]}',
35    '',
36    '<prompt>',
37    original,
38    '</prompt>',
39  ].join('\n')
40
41const rewritePrompt = (original: string, answered: string) =>
42  [
43    'Rewrite the user\'s prompt below into a clearer, more complete prompt for you, with the same intent.',
44    'Keep every detail, constraint, name, path, quote, and code snippet of the original; never drop or weaken one.',
45    'Add only what comes from the user\'s answers, from this conversation, or structure and output format.',
46    'Never add work the user did not ask for (tests, docs, secrets, extra checks) or implementation choices (resources, libraries, outputs); if one seems worth suggesting, write it as an assumption.',
47    'Answers marked "unconfirmed" are your own guesses, which the user did not pick: write each as an assumption the user can change, not as a requirement.',
48    'Never invent facts: write anything still unknown as a [placeholder].',
49    'Keep each [Image #N] reference exactly as written, in a place that still reads naturally: it stands for a picture you cannot see, so never describe it or guess what it shows.',
50    LANGUAGE,
51    'Keep it under 300 words, or 1.5 times the original\'s length when that is longer; shorter is fine when the task is simple.',
52    'Also list each detail the rewrite states that the original did not, including those inside examples and steps, a few words each, in the same language.',
53    'Reply with JSON only, no markdown: {"prompt":"...","added":["..."]}',
54    '',
55    '<prompt>',
56    original,
57    '</prompt>',
58    ...(answered ? ['', '<answers>', answered, '</answers>'] : []),
59  ].join('\n')
60
61// Models wrap JSON in a fence or a sentence now and then; read the outermost object.
62const parseJson = (text: string): unknown => {
63  const start = text.indexOf('{')
64  const end = text.lastIndexOf('}')
65  if (start < 0 || end < start) return undefined
66  try {
67    return JSON.parse(text.slice(start, end + 1))
68  } catch {
69    return undefined
70  }
71}
72
73const isText = (value: unknown): value is string => typeof value === 'string' && value.trim() !== ''
74
75const asQuestions = (text: string): Question[] | undefined => {
76  const list = (parseJson(text) as { questions?: unknown } | undefined)?.questions
77  if (!Array.isArray(list)) return undefined
78  return list
79    .map(q => ({ text: (q as { question?: unknown }).question, options: (q as { options?: unknown }).options }))
80    .filter((q): q is { text: string; options: unknown[] } => isText(q.text) && Array.isArray(q.options))
81    .map(q => ({ text: q.text.trim(), options: q.options.filter(isText).map(o => o.trim()).slice(0, MAX_OPTIONS) }))
82    .filter(q => q.options.length > 0)
83    .slice(0, MAX_QUESTIONS)
84}
85
86const asRewrite = (text: string): Rewrite | undefined => {
87  const reply = parseJson(text) as { prompt?: unknown; added?: unknown } | undefined
88  if (!isText(reply?.prompt)) return undefined
89  return { text: reply.prompt.trim(), added: Array.isArray(reply.added) ? reply.added.filter(isText) : [] }
90}
91
92const answerText = (q: Question, a: Answer | undefined) =>
93  a?.kind === 'option' ? q.options[a.index] : a?.kind === 'other' && a.text.trim() ? a.text.trim() : undefined
94
95const formatAnswers = (questions: Question[], answers: Answer[]) =>
96  questions
97    .map((q, i) => ({ a: answerText(q, answers[i]), guess: answers[i]?.kind === 'option' && answers[i].isGuess, q }))
98    .filter(({ a }) => a !== undefined)
99    .map(({ q, a, guess }) => `Q: ${q.text}\nA: ${a}${guess ? ' (unconfirmed)' : ''}`)
100    .join('\n')
101
102const words = (text: string) => text.split(/\s+/).filter(Boolean).length
103
104const isThai = (text: string) => /[\u0E00-\u0E7F]/.test(text)
105
106const placeholderWarning = (count: number, original: string) =>
107  isThai(original)
108    ? `! ยังเหลือ ${count} [placeholder] ที่ต้องเติม: กด Edit ก่อน หรือ Run anyway`
109    : `! Still has ${count} [placeholder] to fill: use Edit first, or Run anyway`
110
111// The picture itself is not sent along: a plugin's prompt carries text only.
112const IMAGE_REF = /\[Image #\d+\]/g
113
114const imageWarning = (count: number, original: string) =>
115  isThai(original)
116    ? `! มี ${count} รูปในพรอมต์: รูปจะไม่ถูกส่งไปด้วย กด Edit แล้วแนบรูปใหม่ก่อนส่ง`
117    : `! Has ${count} image in the prompt: it is not sent along, use Edit and attach it again before sending`
118
119// The fork sees this conversation; a new or cleared one has nothing to fork, so ask the same model without it.
120const ask = async ($: EngineInterface, prompt: string) => {
121  const forked = await $.model.fork({ prompt })
122  if (forked.isAnswered || forked.reason !== 'nothing-to-fork') return forked
123  return $.model.complete({ model: await $.session.model(), prompt })
124}
125
126// Writes a step's result only while its run is still the one in the pane.
127const settle = ($: EngineInterface, id: number, change: (u: Upgrade) => Upgrade) =>
128  update($, upgrade, u => (u?.id === id ? change(u) : u))
129
130// Reads the answers as they stand now, not as a drawing captured them.
131const rewrite = async ($: EngineInterface, id: number) => {
132  let u: Upgrade | undefined
133  await settle($, id, x => ((u = x), { ...x, rewrite: LOADING }))
134  if (!u) return
135  const questions = u.questions.status === 'ready' ? u.questions.value : []
136  const reply = await ask($, rewritePrompt(u.original, formatAnswers(questions, u.answers)))
137  const value = reply.isAnswered ? asRewrite(reply.text) : undefined
138  const result: Ask<Rewrite> = value
139    ? { status: 'ready', value }
140    : { status: 'failed', reason: reply.isAnswered ? 'unreadable reply' : reply.reason }
141  await settle($, u.id, x => ({ ...x, rewrite: result }))
142}
143
144const askQuestions = async ($: EngineInterface, u: Upgrade) => {
145  await settle($, u.id, x => ({ ...x, questions: LOADING }))
146  const reply = await ask($, questionsPrompt(u.original))
147  const value = reply.isAnswered ? asQuestions(reply.text) : undefined
148  if (!value) {
149    const reason = reply.isAnswered ? 'unreadable reply' : reply.reason
150    await settle($, u.id, x => ({ ...x, questions: { status: 'failed', reason } }))
151    return
152  }
153  // Each question starts on its recommended option, so accepting them all is one press.
154  const ready: Upgrade = { ...u, questions: { status: 'ready', value }, answers: value.map(() => ({ kind: 'option', index: 0, isGuess: true })) }
155  await settle($, u.id, () => ready)
156  if (value.length === 0) await rewrite($, u.id)
157}
158
159// Clears the run before closing, so the close hook knows the pane was not dismissed.
160const finish = async ($: EngineInterface) => {
161  await update($, upgrade, () => null)
162  await $.ui.close({ id: PANE })
163}
164
165export const register: Register = on => {
166  on('command.run', { command: COMMAND }, async ($, e) => {
167    const original = e.args.trim()
168    if (!original) return { text: USAGE }
169
170    const previous = await read($, upgrade)
171    const u: Upgrade = { id: (previous?.id ?? 0) + 1, original, questions: IDLE, answers: [], rewrite: IDLE }
172    await update($, upgrade, () => u)
173    const opened = await $.ui.open({ id: PANE, title: 'Prompt upgrade', focus: true, closeOnEscape: true })
174    if (!opened.isPlaced) {
175      await finish($)
176      await $.prompt.fill({ text: original })
177      $.ui.toast(`Prompt upgrade skipped: ${opened.reason}`)
178      return {}
179    }
180    await askQuestions($, u)
181    return {}
182  })
183
184  // Esc or the close mark leaves the original prompt where the user can still send it.
185  on('ui.close', { id: PANE }, async ($, e, next) => {
186    const u = await read($, upgrade)
187    if (u) {
188      await update($, upgrade, () => null)
189      await $.prompt.fill({ text: u.original })
190    }
191    return next(e)
192  })
193
194  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
195    const rest = await next(e)
196    const u = await read($, upgrade)
197    if (!u) return rest
198
199    const elements = $.ui.resolve(e)
200    const { Box, Button, Text } = elements
201    // Mobile draws no text field, so it offers no typed answer.
202    const Input = 'Input' in elements ? elements.Input : undefined
203    const step = u.rewrite.status === 'ready' ? 2 : u.rewrite.status !== 'idle' ? 1 : 0
204    const STEPS = ['Questions', 'Rewrite', 'Review']
205
206    const stats = u.rewrite.status === 'ready' ? `${words(u.original)} → ${words(u.rewrite.value.text)} words · ${u.rewrite.value.added.length} added` : ''
207
208    const steps = (
209      <Box columnGap={1} flexWrap="wrap" justifyContent="space-between">
210        <Box columnGap={1}>
211          {STEPS.map((name, i) => (
212            <Text key={name} color={i < step ? 'success' : i === step ? 'warning' : undefined} dimColor={i > step} bold={i === step}>
213              {name}
214              {i < STEPS.length - 1 ? ' ›' : ''}
215            </Text>
216          ))}
217        </Box>
218        <Text dimColor>{stats}</Text>
219      </Box>
220    )
221
222    // One dim line instead of a box: the user just typed it.
223    const original = (
224      <Text wrap="truncate-end">
225        <Text dimColor>{u.rewrite.status === 'ready' ? 'Original  ' : 'Prompt  '}</Text>
226        {u.original.replace(/\s+/g, ' ')}
227      </Text>
228    )
229
230    const box = (title: string, text: string) => (
231      <Box flexDirection="column" borderStyle="round" borderColor="warning" paddingX={1}>
232        <Text bold color="warning">
233          {title}
234        </Text>
235        <Text>{text}</Text>
236      </Box>
237    )
238
239    const cancel = (
240      <Button
241        key="cancel"
242        plain
243        dimColor
244        label="Cancel"
245        onPress={async () => {
246          await finish($)
247          await $.prompt.fill({ text: u.original })
248        }}
249      />
250    )
251    const sendOriginal = (
252      <Button
253        key="original"
254        plain
255        dimColor
256        label="Send original"
257        onPress={async () => {
258          await finish($)
259          await $.prompt.submit({ text: u.original, asUser: true })
260        }}
261      />
262    )
263
264    const failure = (reason: string, retry: () => Promise<void>) => (
265      <Box flexDirection="column" rowGap={1}>
266        {original}
267        <Text color="error">✗ Could not upgrade the prompt: {reason}</Text>
268        <Box columnGap={1}>
269          <Button key="retry" variant="primary" label="Retry" onPress={retry} />
270          {sendOriginal}
271          {cancel}
272        </Box>
273      </Box>
274    )
275
276    let body: RenderChildren
277    if (u.questions.status === 'failed') {
278      body = failure(u.questions.reason, () => askQuestions($, u))
279    } else if (u.rewrite.status === 'failed') {
280      body = failure(u.rewrite.reason, () => rewrite($, u.id))
281    } else if (u.rewrite.status === 'ready') {
282      const { text, added } = u.rewrite.value
283      const images = text.match(IMAGE_REF) ?? []
284      const placeholders = (text.match(/\[[^\]\n]+\]/g) ?? []).filter(m => !/^\[Image #\d+\]$/.test(m))
285      body = (
286        <Box flexDirection="column" rowGap={1}>
287          {box('Upgraded prompt', text)}
288          {added.length > 0 && (
289            <Box flexDirection="column">
290              <Text dimColor bold>
291                Added
292              </Text>
293              {added.map((detail, i) => (
294                <Text key={`added-${i}`}>
295                  {'  '}
296                  <Text color="success">+ </Text>
297                  {detail}
298                </Text>
299              ))}
300            </Box>
301          )}
302          {placeholders.length > 0 && (
303            <Text color="warning">{placeholderWarning(placeholders.length, u.original)}</Text>
304          )}
305          {images.length > 0 && <Text color="warning">{imageWarning(images.length, u.original)}</Text>}
306          {original}
307          <Box columnGap={1} flexWrap="wrap">
308            {images.length === 0 && (
309              <Button
310                key="run"
311                variant={placeholders.length > 0 ? undefined : 'primary'}
312                label={placeholders.length > 0 ? '▶ Run anyway' : '▶ Run it'}
313                onPress={async () => {
314                  await finish($)
315                  await $.prompt.submit({ text, asUser: true })
316                }}
317              />
318            )}
319            <Button
320              key="edit"
321              variant={placeholders.length > 0 || images.length > 0 ? 'primary' : undefined}
322              label="Edit"
323              onPress={async () => {
324                await finish($)
325                await $.prompt.fill({ text })
326              }}
327            />
328            <Button
329              key="copy"
330              label="Copy"
331              onPress={async press => {
332                const copied = await $.ui.copy({ text, surface: press.surface })
333                $.ui.toast(copied.isCopied ? 'Copied' : `Could not copy: ${copied.reason}`)
334              }}
335            />
336            {images.length === 0 && sendOriginal}
337            {cancel}
338          </Box>
339        </Box>
340      )
341    } else if (u.rewrite.status === 'loading') {
342      body = (
343        <Box flexDirection="column" rowGap={1}>
344          {original}
345          <Text bold>
346            <Text color="warning">◆</Text> Writing your upgraded prompt… <Text dimColor>(a few seconds)</Text>
347          </Text>
348          <Box>{cancel}</Box>
349        </Box>
350      )
351    } else if (u.questions.status === 'ready') {
352      const questions = u.questions.value
353      const pick = (i: number, answer: Answer) =>
354        update($, upgrade, x => (x?.id === u.id ? { ...x, answers: x.answers.map((a, j) => (j === i ? answer : a)) } : x))
355      body = (
356        <Box flexDirection="column" rowGap={1}>
357          {original}
358          <Text dimColor bold>
359            Answer a few questions <Text dimColor>· recommended is picked; change any, or skip</Text>
360          </Text>
361          {questions.map((q, i) => {
362            const a = u.answers[i]
363            return (
364              <Box key={`q${i}`} flexDirection="column">
365                <Text bold>
366                  <Text color="warning">{i + 1}</Text> {q.text}
367                </Text>
368                <Box flexDirection="column" paddingLeft={2}>
369                  {q.options.map((option, j) => (
370                    <Box key={`o${j}`} columnGap={1} flexWrap="wrap">
371                      <Button
372                        key={`q${i}-${j}`}
373                        plain
374                        label={`${a?.kind === 'option' && a.index === j ? '◉' : '○'} ${option}`}
375                        onPress={() => pick(i, { kind: 'option', index: j })}
376                      />
377                      {j === 0 && <Text dimColor>recommended</Text>}
378                    </Box>
379                  ))}
380                  {Input && (
381                    <Button
382                      key={`q${i}-other`}
383                      plain
384                      label={`${a?.kind === 'other' ? '◉' : '○'} Other…`}
385                      onPress={() => pick(i, { kind: 'other', text: a?.kind === 'other' ? a.text : '' })}
386                    />
387                  )}
388                  <Button
389                    key={`q${i}-skip`}
390                    plain
391                    dimColor
392                    label={`${a?.kind === 'skip' ? '◉' : '○'} Skip`}
393                    onPress={() => pick(i, { kind: 'skip' })}
394                  />
395                </Box>
396                {Input && a?.kind === 'other' && (
397                  <Box paddingLeft={2}>
398                    <Input
399                      key={`q${i}-text`}
400                      placeholder="Type your answer"
401                      value={a.text}
402                      submitLabel="keep"
403                      onInput={text => pick(i, { kind: 'other', text })}
404                      onSubmit={text => pick(i, { kind: 'other', text })}
405                    />
406                  </Box>
407                )}
408              </Box>
409            )
410          })}
411          <Box columnGap={1}>
412            <Button key="upgrade" variant="primary" label="Upgrade now" onPress={() => rewrite($, u.id)} />
413            {cancel}
414          </Box>
415        </Box>
416      )
417    } else {
418      body = (
419        <Box flexDirection="column" rowGap={1}>
420          {original}
421          <Text dimColor>Reading your prompt…</Text>
422          <Box>{cancel}</Box>
423        </Box>
424      )
425    }
426
427    return (
428      <Box flexDirection="column">
429        {rest}
430        <Box flexDirection="column" rowGap={1}>
431          {steps}
432          {body}
433        </Box>
434      </Box>
435    )
436  })
437}
438
types/index.d.ts 33 lines
1/** A model call the pane waits on: idle, running, its value, or why it failed. */
2export type Ask<T> =
3  | { status: 'idle' }
4  | { status: 'loading' }
5  | { status: 'ready'; value: T }
6  | { status: 'failed'; reason: string }
7
8/** A clarifying question; its first option is the recommended option. */
9export type Question = { text: string; options: string[] }
10
11/** The user's answer to one clarifying question: an option by index (`isGuess` while it is still the recommended one nobody picked), their own text, or skipped. */
12export type Answer = { kind: 'option'; index: number; isGuess?: boolean } | { kind: 'other'; text: string } | { kind: 'skip' }
13
14/** The upgraded prompt and the added details it states that the original prompt did not. */
15export type Rewrite = { text: string; added: string[] }
16
17/** One run of /prompt-sharpen, from the original prompt to the upgraded one; `id` tells a stale reply from the current run. */
18export type Upgrade = {
19  id: number
20  original: string
21  questions: Ask<Question[]>
22  answers: Answer[]
23  rewrite: Ask<Rewrite>
24}
25
26declare module 'claude-code' {
27  interface PluginState {
28    'prompt-sharpen': {
29      upgrade: Upgrade | null
30    }
31  }
32}
33