Lets clear prompts through untouched and rewrites rough ones into the prompt box for you to check before sending.

Rough prompt in. Clear prompt in your box. You press Enter.

sharpprompt is a Claude Code mod that looks at each prompt you type before it goes out, and lets most of them through untouched. When one is rough (vague, missing what you want back, leaning on "that thing above"), it rewrites it with the conversation in view and puts the rewrite in your prompt box. You press Enter, edit it, or take your own text back; it never sends anything for you.
On ordinary prompts it makes no measurable difference. We ran 30 everyday cases on Fable 5.1 and Sonnet 5.5, the prompt as typed against the rewrite, and neither the checks nor a blind judge found one.
It helps when the prompt leaves out something only you know. That can be a requirement you never wrote down, like the separator another team's import wants, or a vague pointer back into a long conversation ("that thing above"). On 30 cases built that way, passing checks went from 13 to 25 on Sonnet 5.5 and from 12 to 25 on Fable 5.1. All of the gain came from those two kinds; on the third kind in that set, the session's last failed test, the model did as well without the rewrite. On 10 later cases, written by a model that never saw the rewrite instructions, the rewrite passed 7 and 6 of 10, the prompt as typed 1 and 2.
The cost: each prompt that gets past the gate goes to Haiku for a clear-or-rough label (about a second), and a rough one is rewritten by a fork of your session's model (about three seconds, reading the conversation from the prompt cache).
If you type short commands, or already spell out what you want, you will get little from it.
From a real session. The conversation had just covered hooks/gate.ts, and this was typed:
that question thing u mentioned, is it gonna break when replies end with a code block or smth, look into it
The prompt was held back, and the box filled with:
Will `endsWithQuestion()` in hooks/gate.ts break when Claude's reply ends with a code block or something similar?
Look into it and tell me which endings it gets wrong, with an example for each. Don't change anything yet.
Above the box:
sharpprompt rewrote: that question thing u mentioned, is it gonna break when replies end wi...
Enter sends it, or edit it in the box. [ back to mine ]
"u mentioned" became the function and file the conversation was about.
ctrl+x r (once bound, see Install), r after ctrl+x tab, or a click on [ back to mine ] puts your own text back; the band then says so, and that text goes out as you send it, edited or not, with no second rewrite.

Recorded with vhs on Claude Code 2.1.295.

# lines, prompts under 40 characters, pastes over 20,000, anything you did not type (task notifications, other sessions, plugins), and your answer to a question Claude just asked. It takes about 17 microseconds per prompt on a desktop CPU (mean of 100,000 calls; see tests/gate.bench.test.ts).While the prompt is held, a line under the box says sharpprompt: checking or sharpprompt: rewriting, and goes when the wait ends. Esc ends the wait and puts your draft back in the box, unsent. When the rewrite carries a path, file name, URL, commit hash or number of two digits or more that you did not type, the band names it (not in your draft: ...), so a stale one taken from earlier in the conversation is caught before it goes out.
Anything that fails sends your prompt as typed.
Inside Claude Code:
/plugin marketplace add ondrhn/sharpprompt
/plugin install sharpprompt@ondrhn
Or from a clone:
git clone https://github.com/ondrhn/sharpprompt ~/sharpprompt
claude --plugin-dir ~/sharpprompt
To load the clone in every session, add the folder to CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json.
To take your own text back with ctrl+x r straight from the prompt box, with no ctrl+x tab first, add this to ~/.claude/keybindings.json (merge it into the file if you have one):
{
"$schema": "https://www.schemastore.org/claude-code-keybindings.json",
"bindings": [
{ "context": "Chat", "bindings": { "ctrl+x r": "app:cycleDiffBase" } }
]
}
A plugin cannot bind keys of its own: its buttons answer the chord of one of Claude Code's actions. app:cycleDiffBase only does anything in the diff sidebar, so from the prompt box its chord reaches the band. While the diff sidebar is open, ctrl+x r cycles the diff base there instead. ctrl+r is not used because it is Claude Code's history search.
/sharpprompt, or /sharp for short:
status | on or off, the mode, what happened to the last prompt | |||
on, off | for this session | |||
| `mode fill\ | replace\ | context\ | off` | for this session; the default is set in /config |
undo | puts your last original back in the box | |||
stats | what sharpprompt has done so far (see Measurements) | |||
try <prompt> | shows the rewrite without sending anything |
Ask before sending and Session facts in /config turn the 0.2 helpers off. The Rewrite language setting in /config keeps the rewrite in the language you wrote in (same, the default) or always writes it in English (en), for when you type in another language and want Claude to get a clear English prompt.
Usage log: for each prompt that goes to the rewriter, sharpprompt keeps your draft, the rewrite, any questions and your answers, the text it put in the box, what you did with it (sent as is, edited, took yours back, typed something else) and the length of the turn that followed. The last 300 stay in the plugin's store on your machine and nothing sends them anywhere. /sharp stats says how many there are; node scripts/export_log.mjs copies them into a JSONL file under docs/measurements/usage/, and node scripts/usage_report.mjs <file> turns that into a markdown summary. Usage log in /config turns it off.
Modes: fill (default) puts the rewrite in the box. replace sends the rewrite and shows your original above the box with a way back. context sends your prompt as typed and gives Claude the rewrite beside it as a note.

claude plugin validate --strict . on this repository:
Validating marketplace manifest: .claude-plugin/marketplace.json
Validating plugin: .claude-plugin/plugin.json
❯ types ./types/index.d.ts declares on $: nothing (no EngineInterface member)
❯ types ./types/index.d.ts declares state: sharpprompt.pending, sharpprompt.isOff, sharpprompt.mode, sharpprompt.lastDecision
Validating hooks: hooks/hooks.json
❯ ./register.tsx hooks: session.start, command.run{command=sharpprompt}, command.run{command=sharp}, prompt.submit, tool.call, turn.complete, ui.render{component=AbovePrompt}
❯ ./register.tsx answers its own command: command.run{command=sharpprompt}
❯ ./register.tsx answers its own command: command.run{command=sharp}
❯ ./register.tsx gating hook with .catch: prompt.submit
❯ ./register.tsx gating hook with .catch: tool.call
❯ ./register.tsx calls: $.clock.after (via deliver), $.clock.now, $.clock.sleep (via race), $.command.register, $.model.classify (via classify), $.model.complete (via rewrite), $.model.fork (via rewrite), $.prompt.fill (via deliver, restoreOriginal), $.prompt.read (via deliver), $.session.messages (via lastReply, recent, rewriteOptions), $.session.model, $.session.surface, $.state.get, $.state.set, $.store.get (via bump, exemplarsOf, push, readList, readLog, runCommand), $.store.set (via bump, deliver, push, settlePending, writeLog), $.ui.ask (via askUser), $.ui.resolve
❯ ./register.tsx state writes: sharpprompt.isOff, sharpprompt.lastDecision, sharpprompt.mode, sharpprompt.pending
❯ ./register.tsx state reads: sharpprompt.isOff, sharpprompt.lastDecision, sharpprompt.mode, sharpprompt.pending
✔ Validation passed
That is the whole list: the model, the prompt box, the question dialog, the session's messages and model, its own state and store (the usage log included), the clock, its two commands and the band above the box. A prompt rewriter sees everything you type, so you should be able to check that it cannot send it anywhere.
The rewriter gets a short rule set chosen by your session's model family:
Each rule is in docs/rules with a link to the Anthropic page it comes from. Two are ours rather than Anthropic's and say so: no role lines ("You are an expert..."), and a length limit (twice your prompt or 60 words, whichever is more, at most 180). docs/shapes has what a good prompt of each kind carries (fix, investigate, build, refactor, research, review, write, ask), with one example each.
/sharp stats shows the tokens per rough prompt. The Helper model setting picks only the classifier and the fallback used before the conversation has a first reply./sharp stats counts these.claude -p, the SDK) have no box to fill, so fill acts as context there. Mods do not run in a Desktop session that uses WSL.ctrl+x r (with the binding above) or ctrl+x tab then r puts it in the box, Enter sends it. sharpprompt does not send it for you because a prompt a plugin sends shows under the plugin's name in the transcript and skips @file expansion. The band's buttons answer to their keys once the band has focus: ctrl+x tab, or a click.| version | date | prompts | gate (mean) | classifier p50 | rewrite p50 | timeouts |
|---|---|---|---|---|---|---|
| 0.1.0 | 8 Oct 2026 | 19 typed, 8 rewritten | 17 us | 1.0 s (n=9) | 3.1 s (n=6) | 0 |
Benchmark, 30 cases, the prompt as typed against the rewrite: no measurable difference on Fable 5.1 (26 paired cases, report) or on Sonnet 5.5 (30 paired cases, report). A blind judge found none either. With Turkish drafts rewritten into English (Sonnet 5.5), task success and judge scores stayed the same while output tokens and time went down, mostly because the answers came back in English (report). On a second corpus of 30 cases built so the model lacks something only the user knows (an unstated requirement, a vague pointer back into a long conversation, the session's last test run), the rewrite, with its questions answered by a model that knows what the user meant, raised passing checks from 13 to 25 on Sonnet 5.5 and from 12 to 25 on Fable 5.1, all of it in the first two kinds of case (Sonnet, Fable). On ten new hidden-spec cases, written by a model that never saw the rewrite instructions, the rewritten prompt passed 7 of 10 checks on Sonnet 5.5 and 6 on Fable 5.1, against 1 and 2 for the prompt as typed (report).
Token overhead over two days of the author's own use (9 to 11 Oct 2026, 63 prompts typed, 25 rewritten and 15 more timed out, their forks still billed): the plugin's calls came to 11.9 million tokens against 155.9 million for the sessions themselves, 7.6% more, and at API list prices 8.60 USD against 73.94, 11.6% more. 96% of the rewrite input was read from the prompt cache, and the plugin's output was 2% of the sessions' (report, node scripts/token_overhead.mjs to measure your own).
Each version gets a file in docs/measurements with the method and the raw table, and a row here. The rewrites in the benchmark were written by Haiku; the plugin forks the session model. /sharp stats keeps the same numbers for your own sessions, on your machine only, and compares turns that started from your text with turns that started from a rewrite.
Tests: 106 in tests/, run with claude plugin test ., and 4 for the scripts, run with node --test scripts/usage.node-test.mjs. Both run on every push and pull request (test workflow).
No. In the default mode the rewrite waits in your box until you press Enter. Only replace mode, which you turn on yourself, sends the rewrite in place of your text.
Most prompts pass: short ones, commands, answers to Claude's questions, and anything the classifier calls clear. /sharp status says which reason applied to the last one.
One classifier call on the helper model for each prompt that passes the gate, and for a rough prompt one fork on your session's model. In the 0.1.0 measurements that fork used about 2,500 input tokens outside the cache, 64,000 read from the cache and 230 output tokens. Over two days of longer sessions it averaged about 296,000 tokens per rewrite, nearly all cache reads, and added 11.6% to the sessions' API price. /sharp stats shows your own numbers.
Start the prompt with raw:. The prefix is removed and the rest goes out as typed. /sharp off turns it off for the session.
Any language your session's model reads. The classifier and the rewriter are models, so there is no word list to match, and by default the rewrite comes back in the language you typed. Set Rewrite language to en to get an English prompt from a draft in another language. Numbers, paths and file names are checked in any script (çalışma.py, 2,5), and an edit of a suggestion is recognised in Cyrillic, Chinese or Japanese as well as in Latin letters. The rules the rewriter follows are written in English. What has been measured: the benchmarks are in English plus one Turkish set, and 232 of the author's 238 logged prompts were Turkish. Other languages are untested.
The hooks run, but VS Code has no box for the mod to fill and no band, so the rewrite goes to Claude as a note beside your prompt (context mode) and your prompt goes out as typed.
Types come from the Claude Code build you run. Open an interactive session with the plugin once (claude --plugin-dir .) and the engine writes them to .claude-plugin/types/ (git-ignored); tsconfig.json extends the one written there. After a Claude Code update, open it again.
Rules and shapes live in docs/; node scripts/build-bank.mjs compiles them into hooks/bank.ts, because a mod cannot read files at run time. --check fails when the two drift.
Checks: claude plugin validate --strict ., claude plugin test ., tsc -p ., node scripts/build-bank.mjs --check, and for the export, report and token overhead scripts node --test scripts/usage.node-test.mjs. CI runs all of them but tsc, on Claude Code 2.1.296; none needs a login. tsc runs locally only, because the types it checks against are written when the plugin loads in a signed-in session.
Benchmark: node --experimental-strip-types --no-warnings --import ./scripts/ts-resolve.mjs scripts/bench.mjs --help; the corpus and how to run it are in docs/bench.
MIT. See LICENSE.
hooks/register.tsx 708 lines1import type { EngineInterface, ModelUsage, Next, PromptSubmitInput, PromptSubmitResult, Register } from 'claude-code'
2import type { SharppromptDecision, SharppromptMode, SharppromptPending, SharppromptRewrite, SharppromptVerdict } from '../types'
3import { contextNote, describe, DROP_NOTE, HELP, isEditOf, parseCommand } from './flow'
4import { sessionFacts } from './facts'
5import { endsWithQuestion, gate, isTyped, RAW_PREFIX } from './gate'
6import { clip, logLine, MAX_LOG, newRecord, patchLog, type LogRecord } from './log'
7import { applyAnswers, askInput, recommended, splitReply, type Question } from './questions'
8import { countKey, lastRewriteLine, MAX_RECORDS, summary, tokens, wordCount, type ClassifyRecord, type Counts, type DecisionRecord, type LateRecord, type RewriteRecord, type TurnRecord } from './stats'
9import { addedLine, clean, completePrompt, familyOf, forkPrompt, isLong, wordLimit, type Exemplar, type Recent, type RewriteOptions } from './rewrite'
10
11// The engine checks that $ never leaves this file, so everything that calls
12// it lives here and gate.ts stays pure.
13
14const isOff = { plugin: 'sharpprompt', key: 'isOff' } as const
15const lastDecision = { plugin: 'sharpprompt', key: 'lastDecision' } as const
16const pending = { plugin: 'sharpprompt', key: 'pending' } as const
17const modeOverride = { plugin: 'sharpprompt', key: 'mode' } as const
18
19// The turn now running and how its prompt got there; tool calls counted on
20// the main thread. Module state: a reload mid-turn loses one turn's record.
21let outgoing: TurnRecord['prompt'] | null = null
22let toolCalls = 0
23// The usage-log record of the prompt that started the running turn.
24let turnLog: string | null = null
25
26type Options = Readonly<Record<string, unknown>>
27
28export const CLASSIFY_MS = 2_500
29
30// The labels the classifier picks from; the wording is what it judges by.
31const CLEAR = 'clear and specific'
32const ROUGH = 'rough: vague or missing what to deliver'
33// 10 s, not 5: from 12 to 23 Oct 2026, 32 of 79 rewrites of drafts of 20
34// words or less timed out at 5 s. The forks that lost finished in 7.5 s
35// (median), 9.9 s at p90; the time follows the conversation, not the draft.
36export const REWRITE_MS = 10_000
37
38// Long drafts get longer: over 20 words, 100 ms more per word, up to 25 s.
39// 15 of 40 rough prompts timed out in two days of use (9 to 11 Oct 2026),
40// median 32 words, while the rewrites that came back were 3 to 31 words.
41// Tidying six of those long drafts on Opus 5.5 took 2.5 s (60 words) to
42// 10.9 s (90) and 21.2 s (253).
43export const REWRITE_MAX_MS = 25_000
44export function rewriteMs(draft: string): number {
45 return Math.min(REWRITE_MS + 100 * Math.max(0, wordCount(draft) - 20), REWRITE_MAX_MS)
46}
47
48// The engine heads the line with the plugin's name, so no prefix here. Esc
49// while it shows ends the wait and puts the draft back in the box, unsent
50// (tmux, 2.1.296).
51export const STATUS_CHECKING = 'checking (Esc: yours back in the box)'
52export const STATUS_REWRITING = 'rewriting (Esc: yours back in the box)'
53
54// Tokens a fork spent after it lost its race: it finished in the background
55// and was billed anyway. Read out by the stats in a later step.
56export const late = { forks: 0, ms: [] as number[], usage: { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } }
57
58function addLate(u: ModelUsage, ms: number) {
59 late.forks++
60 late.ms.push(ms)
61 late.usage.input_tokens += u.input_tokens
62 late.usage.output_tokens += u.output_tokens
63 late.usage.cache_read_input_tokens += u.cache_read_input_tokens
64 late.usage.cache_creation_input_tokens += u.cache_creation_input_tokens
65}
66
67// A plugin binds no chords of its own: a Button answers the chord of an
68// engine action. This one's handler lives only in the diff sidebar, so from
69// the prompt the chord reaches the band. Bound in ~/.claude/keybindings.json,
70// context Chat, "ctrl+x r" (README, Install); ctrl+r is history search.
71export const BACK_TO_MINE = 'app:cycleDiffBase'
72
73const TIMEOUT: unique symbol = Symbol('timeout')
74
75// fork and classify take no time limit, so we race them against the clock.
76// The loser keeps running: a fork that lost still finishes in the background
77// and is billed (README, Limits).
78async function race<T>($: EngineInterface, work: Promise<T>, ms: number): Promise<T | typeof TIMEOUT> {
79 const stop = new AbortController()
80 // A sleep that fails for its own reasons must not read as a timeout: the
81 // work then runs unraced. The hook budget is no backstop (it stops while a
82 // $ call is in flight), so the completion also carries its own timeoutMs.
83 const timer: Promise<typeof TIMEOUT> = $.clock.sleep(ms, { signal: stop.signal }).then(
84 () => TIMEOUT,
85 () => new Promise<never>(() => {}),
86 )
87 try {
88 return await Promise.race([work, timer])
89 } finally {
90 stop.abort()
91 }
92}
93
94async function classify($: EngineInterface, text: string, model: string): Promise<SharppromptVerdict> {
95 try {
96 const label = await race($, $.model.classify(text, [CLEAR, ROUGH], { model }), CLASSIFY_MS)
97 if (label === TIMEOUT) return 'timeout'
98 if (label === CLEAR) return 'clear'
99 if (label === ROUGH) return 'rough'
100 return 'error'
101 } catch {
102 return 'error'
103 }
104}
105
106async function recent($: EngineInterface): Promise<Recent[]> {
107 const rows = await $.session.messages()
108 return rows
109 .filter(r => r.text.trim() !== '')
110 .slice(-4)
111 .map(r => ({ role: r.role, text: r.text }))
112}
113
114async function exemplarsOf($: EngineInterface): Promise<Exemplar[]> {
115 const v = await $.store.get('exemplars')
116 return Array.isArray(v) ? (v as Exemplar[]) : []
117}
118
119// Fork first: it reads the conversation from the prompt cache. With nothing
120// to fork yet (first turn, after /clear) a plain completion with the last few
121// messages pasted in. Both race the clock; losing means no rewrite.
122async function rewrite($: EngineInterface, draft: string, helper: string, opts: RewriteOptions = {}): Promise<SharppromptRewrite> {
123 const started = await $.clock.now()
124 const family = familyOf(await $.session.model())
125 const examples = await exemplarsOf($)
126 const took = async () => (await $.clock.now()) - started
127
128 const forking = $.model.fork({ prompt: forkPrompt(draft, family, examples, opts) })
129 const limit = rewriteMs(draft)
130 const forked = await race($, forking, limit)
131 if (forked === TIMEOUT) {
132 void forking.then(async r => ('usage' in r ? addLate(r.usage, await took()) : undefined), () => {})
133 return { outcome: 'timeout', via: 'fork', ms: await took() }
134 }
135
136 let reply = forked
137 let via: 'fork' | 'complete' = 'fork'
138 // Esc while we wait cuts the fork: the person took the draft back.
139 if (!reply.isAnswered && reply.reason === 'aborted') return { outcome: 'aborted', via, ms: await took(), usage: reply.usage }
140 if (!reply.isAnswered && reply.reason === 'nothing-to-fork') {
141 via = 'complete'
142 // Raced like the fork and cut by our own signal when it loses, so an
143 // 'aborted' reply means Esc, and a lost completion stops being billed.
144 const stop = new AbortController()
145 const completing = $.model.complete({
146 model: helper,
147 prompt: completePrompt(draft, family, await recent($), examples, opts),
148 // A cut reply comes back answered, with no sign it was cut, so the cap
149 // leaves room for the whole word limit (a tidy is as long as its
150 // draft) plus questions: about 2 tokens a word, 600 at least.
151 maxTokens: Math.max(600, 2 * wordLimit(draft) + 400),
152 effort: 'low',
153 // Only a backstop for a refused sleep; the race below ends it first.
154 timeoutMs: limit + 1_000,
155 }, { signal: stop.signal })
156 const completed = await race($, completing, limit)
157 if (completed === TIMEOUT) {
158 stop.abort()
159 return { outcome: 'timeout', via, ms: await took() }
160 }
161 reply = completed
162 if (!reply.isAnswered && reply.reason === 'aborted') return { outcome: (await took()) >= limit ? 'timeout' : 'aborted', via, ms: await took() }
163 }
164 if (!reply.isAnswered) return { outcome: 'error', via, ms: await took(), detail: reply.reason, usage: reply.usage }
165
166 const { body, questions, dropped } = opts.ask ? splitReply(reply.text) : { body: reply.text, questions: [], dropped: false }
167 // A question we cannot ask leaves its point out of the body.
168 if (dropped) return { outcome: 'error', via, ms: await took(), detail: 'questions', usage: reply.usage, replyChars: reply.text.length }
169 // The asked points and their candidate values live in the options.
170 const c = clean(body, draft, questions.flatMap(q => q.options.map(o => `${o.label} ${o.adds}`)).join('\n'))
171 const ms = await took()
172 // The reply's own length: output tokens well past it went to thinking.
173 const replyChars = reply.text.length
174 if ('rejected' in c) return { outcome: c.rejected, via, ms, usage: reply.usage, replyChars, ...('lost' in c ? { detail: c.lost.join(' ') } : {}) }
175 return { outcome: 'rewritten', via, ms, usage: reply.usage, replyChars, text: c.rewritten, ...(questions.length ? { questions } : {}) }
176}
177
178async function lastReply($: EngineInterface): Promise<string> {
179 const rows = await $.session.messages()
180 for (let i = rows.length - 1; i >= 0; i--) {
181 const row = rows[i]
182 if (row?.role === 'assistant' && row.text.trim() !== '') return row.text
183 }
184 return ''
185}
186
187const helperModel = (options: Options) => (typeof options.optimizerModel === 'string' ? options.optimizerModel : 'haiku')
188// Both v0.2 helpers are on unless the user turned them off.
189async function rewriteOptions($: EngineInterface, options: Options): Promise<RewriteOptions> {
190 const facts = options.sessionFacts === false ? '' : sessionFacts(await $.session.messages())
191 return {
192 language: options.rewriteLanguage === 'en' ? 'en' : 'same',
193 ask: options.askBeforeSend !== false,
194 ...(facts ? { facts } : {}),
195 }
196}
197
198// The engine shows a plugin's questions one dialog at a time ($.ui.ask), so
199// the rewriter asks at most two. null when the person closes either dialog
200// or it cannot be shown: the prompt then goes out as typed.
201async function askUser($: EngineInterface, questions: readonly Question[]): Promise<Record<string, string> | null> {
202 const answers: Record<string, string> = {}
203 try {
204 for (const [i, q] of askInput(questions).questions.entries()) {
205 const header = questions.length > 1 ? `${q.header.slice(0, 8)} ${i + 1}/${questions.length}` : q.header
206 answers[q.question] = await $.ui.ask(q.question, { options: q.options.map(o => o.label), header })
207 }
208 return answers
209 } catch {
210 return null
211 }
212}
213
214async function modeOf($: EngineInterface, options: Options): Promise<SharppromptMode> {
215 const o = (await $.state.get(modeOverride)).value
216 if (o) return o
217 const m = options.mode
218 return m === 'replace' || m === 'context' || m === 'off' ? m : 'fill'
219}
220
221// What sharpprompt would do with this prompt. Anything without a rewritten
222// text means the prompt goes out exactly as typed.
223async function decide($: EngineInterface, e: PromptSubmitInput, options: Options, mode: SharppromptMode): Promise<SharppromptDecision> {
224 const off = mode === 'off' || (await $.state.get(isOff)).value === true
225 const g = gate({
226 text: e.text,
227 origin: e.origin,
228 minChars: typeof options.minChars === 'number' ? options.minChars : 40,
229 isOff: off,
230 })
231 if (g.pass) return { verdict: 'skip', reason: g.reason, text: g.text }
232
233 if (endsWithQuestion(await lastReply($))) return { verdict: 'skip', reason: 'answer', text: e.text }
234
235 // The prompt is held while we wait, and nothing else on screen says why:
236 // a status line under the box does, and goes as soon as the wait ends.
237 try {
238 // A long draft goes straight to tidying: the classifier asks whether a
239 // prompt is vague, and a long one's trouble is repetition.
240 if (isLong(e.text)) {
241 $.ui.status(STATUS_REWRITING)
242 return { verdict: 'long', text: e.text, rewrite: await rewrite($, e.text, helperModel(options), await rewriteOptions($, options)) }
243 }
244 $.ui.status(STATUS_CHECKING)
245 const t0 = await $.clock.now()
246 const verdict = await classify($, e.text, helperModel(options))
247 const classifyMs = (await $.clock.now()) - t0
248 if (verdict !== 'rough') return { verdict, text: e.text, classifyMs }
249 $.ui.status(STATUS_REWRITING)
250 return { verdict, text: e.text, classifyMs, rewrite: await rewrite($, e.text, helperModel(options), await rewriteOptions($, options)) }
251 } finally {
252 $.ui.status(undefined)
253 }
254}
255
256// The usage log (hooks/log.ts). A failed write never stops the prompt.
257const logOn = (options: Options) => options.log !== false
258
259async function readLog($: EngineInterface): Promise<LogRecord[]> {
260 const v = await $.store.get('log')
261 return Array.isArray(v) ? (v as LogRecord[]) : []
262}
263
264async function writeLog($: EngineInterface, list: readonly LogRecord[]) {
265 try {
266 await $.store.set('log', list.slice(-MAX_LOG))
267 } catch {
268 // Over the store's size limit: keep the newer half.
269 await $.store.set('log', list.slice(-MAX_LOG / 2)).catch(() => {})
270 }
271}
272
273async function startLog($: EngineInterface, options: Options, d: SharppromptDecision): Promise<string | null> {
274 if (!logOn(options)) return null
275 try {
276 const now = await $.clock.now()
277 const list = await readLog($)
278 const rec = newRecord(`${now}-${list.length}`, new Date(now).toISOString(), await $.session.model(), d)
279 if (!rec) return null
280 await writeLog($, [...list, rec])
281 return rec.id
282 } catch {
283 return null
284 }
285}
286
287async function updateLog($: EngineInterface, id: string | null | undefined, patch: Partial<LogRecord>) {
288 if (!id) return
289 try {
290 const list = await readLog($)
291 if (list.some(r => r.id === id)) await writeLog($, patchLog(list, id, patch))
292 } catch {}
293}
294
295// A prompt sent while our suggestion is waiting is the user's answer to it,
296// not a new draft. When they edited it first, the edit is kept as an example
297// of how they like their prompts.
298async function settlePending($: EngineInterface, text: string): Promise<'as-is' | 'edited' | null> {
299 const p = (await $.state.get(pending)).value
300 if (!p || p.kind === 'restored') return null
301 await $.state.set(pending, null)
302 // A sent rewrite's band goes with the next prompt.
303 if (p.kind !== 'filled') return null
304 if (text === p.rewritten) {
305 await updateLog($, p.log, { action: 'as-is' })
306 turnLog = p.log ?? null
307 return 'as-is'
308 }
309 if (!isEditOf(p.rewritten, text)) {
310 await updateLog($, p.log, { action: 'abandoned' })
311 return null
312 }
313 const list = await exemplarsOf($)
314 await $.store.set('exemplars', [...list, { original: p.rewritten, sent: text }].slice(-20)).catch(() => {})
315 await updateLog($, p.log, { action: 'edited', sent: clip(text) })
316 turnLog = p.log ?? null
317 return 'edited'
318}
319
320// The counts and records are for /sharp stats only: a store that is full or
321// failing must not cost the user a rewrite already paid for.
322async function bump($: EngineInterface, add: Counts) {
323 try {
324 const v = await $.store.get('counts')
325 const counts: Counts = v && typeof v === 'object' ? { ...(v as Counts) } : {}
326 for (const [k, n] of Object.entries(add)) counts[k] = (counts[k] ?? 0) + n
327 await $.store.set('counts', counts)
328 } catch {}
329}
330
331async function push<T>($: EngineInterface, key: 'rewrites' | 'turns' | 'classified' | 'decisions' | 'late', item: T) {
332 try {
333 const v = await $.store.get(key)
334 const list = Array.isArray(v) ? (v as T[]) : []
335 await $.store.set(key, [...list, item].slice(-MAX_RECORDS))
336 } catch {}
337}
338
339async function readList<T>($: EngineInterface, key: 'rewrites' | 'turns' | 'classified'): Promise<T[]> {
340 const v = await $.store.get(key)
341 return Array.isArray(v) ? (v as T[]) : []
342}
343
344// Times are kept so scripts/token_overhead.mjs can take a window of them.
345async function record($: EngineInterface, d: SharppromptDecision, helper: string) {
346 const at = await $.clock.now()
347 await bump($, { [countKey(d)]: 1 })
348 const seen: DecisionRecord = { at, key: countKey(d) }
349 await push($, 'decisions', seen)
350 if ('classifyMs' in d && d.classifyMs !== undefined) {
351 const item: ClassifyRecord = { verdict: d.verdict, ms: d.classifyMs, words: wordCount(d.text), at, model: helper }
352 await push($, 'classified', item)
353 }
354 if (!('rewrite' in d) || !d.rewrite) return
355 const r = d.rewrite
356 const item: RewriteRecord = {
357 outcome: r.outcome,
358 via: r.via,
359 ms: r.ms,
360 classifyMs: d.classifyMs,
361 usage: tokens(r.usage),
362 ...(r.replyChars === undefined ? {} : { replyChars: r.replyChars }),
363 words: r.text ? [wordCount(d.text), wordCount(r.text)] : [wordCount(d.text)],
364 model: await $.session.model(),
365 at,
366 ...(r.via === 'complete' ? { helper } : {}),
367 }
368 await push($, 'rewrites', item)
369}
370
371// What /sharp undo puts back. Written after pending, so an Enter on the
372// box right after the fill already finds the suggestion. The usage-log
373// record goes with the suggestion's pending, not here.
374async function keepForUndo($: EngineInterface, original: string) {
375 await $.store.set('undo', { original }).catch(() => {})
376}
377
378// VS Code and headless sessions draw no box, no band and no dialog.
379async function isDrawn($: EngineInterface): Promise<boolean> {
380 const surface = await $.session.surface()
381 return surface === 'terminal' || surface === 'desktop'
382}
383
384async function deliver($: EngineInterface, e: PromptSubmitInput, rewritten: string, mode: SharppromptMode, next: Next<'prompt.submit'>, log: string | null = null, asked = ''): Promise<PromptSubmitResult> {
385 // VS Code and headless sessions draw no box and no band: there the rewrite
386 // can only ride along as context.
387 // The dispatch went on without us (Esc, or a plugin above settled the
388 // prompt first): nothing of ours may land in the box or the state now,
389 // and next(e) would send the prompt down the chain a second time.
390 if (next.signal.aborted) return { text: e.text }
391 const how = mode === 'fill' && !(await isDrawn($)) ? 'context' : mode
392
393 if (how === 'context') {
394 await updateLog($, log, { delivered: 'context', boxed: clip(rewritten) })
395 turnLog = log
396 outgoing = 'context'
397 return next({ ...e, context: [...(e.context ?? []), contextNote(rewritten)] })
398 }
399
400 if (how === 'replace') {
401 await $.state.set(pending, { kind: 'replaced', original: e.text, rewritten, ...(log ? { log } : {}), ...(asked ? { asked } : {}) })
402 await keepForUndo($, e.text)
403 await updateLog($, log, { delivered: 'replace', boxed: clip(rewritten) })
404 turnLog = log
405 outgoing = 'rewritten'
406 return next({ ...e, text: rewritten })
407 }
408
409 // The box empties on Enter and stays editable while we wait: whatever the
410 // person typed there since is theirs, and a fill would wipe it. Their
411 // prompt then goes as typed and the new text stays in the box.
412 const typedAhead = ((await $.prompt.read().catch(() => null))?.text ?? '').trim() !== ''
413 if (typedAhead) {
414 await updateLog($, log, { delivered: 'typed' })
415 turnLog = log
416 outgoing = 'typed'
417 return next(e)
418 }
419 const f0 = await $.clock.now()
420 const filled = await $.prompt.fill({ text: rewritten, mode: 'replace' })
421 const fillMs = (await $.clock.now()) - f0
422 if (!filled.isFilled) {
423 await updateLog($, log, { delivered: 'typed' })
424 turnLog = log
425 outgoing = 'typed'
426 return next(e)
427 }
428 await $.state.set(pending, { kind: 'filled', original: e.text, rewritten, ...(log ? { log } : {}), ...(asked ? { asked } : {}) })
429 await keepForUndo($, e.text)
430 await updateLog($, log, { delivered: 'fill', boxed: clip(rewritten), fillMs })
431 // Since Claude Code 2.1.295 a dropped prompt is put back in the box after
432 // our fill, so the box reads rewrite + original. The engine does that before
433 // the next timer tick, so one tick later we set the rewrite again. On 2.1.293
434 // the box already holds the rewrite alone and nothing happens.
435 $.clock.after(0, async () => {
436 const p = (await $.state.get(pending)).value
437 if (!p || p.kind !== 'filled' || p.rewritten !== rewritten) return
438 // Only the engine's own put-back (rewrite, then the original) is undone;
439 // anything else in the box was typed by the person.
440 const box = (await $.prompt.read()).text
441 if (box !== rewritten && box.startsWith(rewritten) && box.includes(e.text.trim())) await $.prompt.fill({ text: rewritten, mode: 'replace' })
442 })
443 return { drop: DROP_NOTE }
444}
445
446// Puts the user's own text back in the box. Sent as it stands or edited, it
447// goes out untouched (prompt.submit checks it against pending); a different
448// prompt is a new one. We never send it for them: a prompt a plugin submits shows in the
449// transcript under the plugin's name and skips @file expansion. pending is
450// written before the fill so an Enter right after it already sees it.
451// A rewrite already sent (replaced) keeps its turn on its record: the
452// original sent after it is a turn of its own.
453async function restoreOriginal($: EngineInterface, p: SharppromptPending): Promise<boolean> {
454 const { log, ...rest } = p
455 await $.state.set(pending, { ...rest, kind: 'restored', ...(log && p.kind !== 'replaced' ? { log } : {}) })
456 if (p.kind !== 'restored') {
457 await bump($, { 'answer:original': 1 })
458 await updateLog($, log, { action: 'original' })
459 }
460 const r = await $.prompt.fill({ text: p.original, mode: 'replace' })
461 if (!r.isFilled) await $.state.set(pending, null)
462 return r.isFilled
463}
464
465// True when this is the user's own text we put back, sent unchanged or
466// edited. They asked for theirs back: on 23 Oct 2026 an original put back
467// with back to mine was added to and sent, and got rewritten all over
468// again. A prompt that is neither an edit of it nor an addition is new.
469async function isRestored($: EngineInterface, text: string): Promise<boolean> {
470 const p = (await $.state.get(pending)).value
471 if (!p || p.kind !== 'restored') return false
472 await $.state.set(pending, null)
473 if (text !== p.original && !isEditOf(p.original, text)) return false
474 turnLog = p.log ?? null
475 return true
476}
477
478async function runCommand($: EngineInterface, args: string, options: Options): Promise<string> {
479 const c = parseCommand(args)
480 switch (c.kind) {
481 case 'status': {
482 const mode = await modeOf($, options)
483 const off = (await $.state.get(isOff)).value === true
484 const last = (await readList<RewriteRecord>($, 'rewrites')).at(-1)
485 return `${off ? 'Off' : 'On'} for this session, mode ${mode}.\nLast prompt: ${describe((await $.state.get(lastDecision)).value ?? null)}\n${lastRewriteLine(last)}`
486 }
487 case 'on':
488 await $.state.set(isOff, false)
489 // Mode off from the settings needs an override; one from /sharp mode off
490 // is lifted, so a configured replace or context mode comes back.
491 if ((await modeOf($, options)) === 'off') await $.state.set(modeOverride, options.mode === 'off' ? 'fill' : null)
492 return 'On for this session.'
493 case 'off':
494 await $.state.set(isOff, true)
495 return 'Off for this session. Prompts go out as typed.'
496 case 'mode':
497 await $.state.set(modeOverride, c.mode)
498 return `Mode is ${c.mode} for this session.`
499 case 'undo': {
500 const u = await $.store.get('undo')
501 const saved = u && typeof u === 'object' ? (u as { original?: unknown }) : {}
502 const old = await $.store.get('lastOriginal')
503 const original = typeof saved.original === 'string' ? saved.original : old
504 if (typeof original !== 'string') return 'Nothing to undo.'
505 // While its band is up this is the band's own button. After that the
506 // rewrite was answered: the original comes back, but its record and
507 // counts are not touched again.
508 const w = (await $.state.get(pending)).value
509 const p: SharppromptPending = w && w.original === original ? w : { kind: 'restored', original, rewritten: '' }
510 const ok = await restoreOriginal($, p)
511 return ok ? 'Your original is back in the prompt box; edited or not, it goes out as you send it.' : `Could not reach the prompt box. Your original was:\n${original}`
512 }
513 case 'stats': {
514 const v = await $.store.get('counts')
515 const counts = v && typeof v === 'object' ? (v as Counts) : {}
516 return `${summary(counts, await readList<RewriteRecord>($, 'rewrites'), await readList<TurnRecord>($, 'turns'), await readList<ClassifyRecord>($, 'classified'))}\n${logLine(logOn(options), (await readLog($)).length)}`
517 }
518 case 'try': {
519 const verdict = await classify($, c.text, helperModel(options))
520 const r = await rewrite($, c.text, helperModel(options), await rewriteOptions($, options))
521 const asks = r.questions?.length ? `\n\nWould ask:\n${r.questions.map(q => `- ${q.question} ${q.options.map(o => o.label).join(' / ')}`).join('\n')}` : ''
522 return `classify: ${verdict}\nrewrite: ${r.outcome} via ${r.via} in ${r.ms} ms${r.text ? `\n\n${r.text}` : ''}${asks}`
523 }
524 case 'help':
525 return `${c.error ? `${c.error}\n` : ''}${HELP}`
526 }
527}
528
529async function submit($: EngineInterface, e: PromptSubmitInput, next: Next<'prompt.submit'>, options: Options): Promise<PromptSubmitResult> {
530 const typedByUser = isTyped(e.origin)
531 // A slash command typed meanwhile leaves the text in the box as it was.
532 // The engine says which prompt runs one: a path such as /etc/hosts is text.
533 if (typedByUser && !e.command) {
534 // raw: in front of our suggestion or of the person's own text changes
535 // nothing; it is taken off before the comparison and before it goes out.
536 const sent = e.text.replace(RAW_PREFIX, '')
537 if (await isRestored($, sent)) {
538 const d: SharppromptDecision = { verdict: 'skip', reason: 'back-to-mine', text: sent }
539 await $.state.set(lastDecision, d)
540 await record($, d, helperModel(options))
541 outgoing = 'typed'
542 return next(sent === e.text ? e : { ...e, text: sent })
543 }
544 const answered = await settlePending($, sent)
545 if (answered) {
546 await $.state.set(lastDecision, { verdict: 'skip', reason: 'suggested', text: sent })
547 await bump($, { [`answer:${answered}`]: 1 })
548 outgoing = answered === 'as-is' ? 'rewritten' : 'edited'
549 return next(sent === e.text ? e : { ...e, text: sent })
550 }
551 }
552 const mode = await modeOf($, options)
553 const d = await decide($, e, options, mode)
554 await $.state.set(lastDecision, d)
555 if (typedByUser) await record($, d, helperModel(options))
556 const log = typedByUser ? await startLog($, options, d) : null
557 // Esc put the draft back in the box: sent as it stands, it is the
558 // person's own and goes out as they send it, with no second wait.
559 // Esc while the classifier runs rejects it, and it reads as an error.
560 const escaped = ('rewrite' in d && d.rewrite?.outcome === 'aborted') || (d.verdict === 'error' && next.signal.aborted)
561 if (escaped) {
562 if (typedByUser) await $.state.set(pending, { kind: 'restored', original: e.text, rewritten: '', ...(log ? { log } : {}) })
563 return next(e)
564 }
565 // The dispatch went on without us while we waited: next(e) would send the
566 // prompt down the chain a second time.
567 if (next.signal.aborted) return { text: e.text }
568 let rewritten = 'rewrite' in d ? d.rewrite?.text : undefined
569 let how = mode
570 let asked = ''
571 const questions = ('rewrite' in d ? d.rewrite?.questions : undefined) ?? []
572 if (rewritten && questions.length) {
573 if (await isDrawn($)) {
574 const answers = await askUser($, questions)
575 if (next.signal.aborted) return { text: e.text }
576 if (!answers) {
577 await bump($, { 'ask:dismissed': 1 })
578 await updateLog($, log, { answers: 'dismissed', delivered: 'typed' })
579 turnLog = log
580 if (typedByUser) outgoing = 'typed'
581 return next(e)
582 }
583 await bump($, { 'ask:answered': 1 })
584 await updateLog($, log, { answers })
585 rewritten = applyAnswers(rewritten, questions, answers)
586 // What the person saw and chose: the labels or their own words. The
587 // option sentences behind them were the model's, and stay checked.
588 asked = Object.values(answers).join(' ')
589 } else {
590 // Nobody to ask: the recommended answers are guesses, so they ride
591 // along as context and never replace what the user typed.
592 rewritten = recommended(rewritten, questions)
593 how = 'context'
594 }
595 }
596 if (rewritten) return deliver($, e, rewritten, how, next, log, asked)
597 await updateLog($, log, { delivered: 'typed' })
598 turnLog = log
599 if (typedByUser) outgoing = 'typed'
600 return next(d.text !== e.text ? { ...e, text: d.text } : e)
601}
602
603// Whatever happens in here, the prompt goes out. A thrown error lands in
604// .catch, which sends it untouched.
605export const register: Register = (on, options) => {
606 on('session.start', async ($, e, next) => {
607 await $.command.register({ name: 'sharpprompt', description: 'Prompt rewriting: status, on, off, mode, undo, stats, try', argumentHint: '[status|on|off|mode|undo|stats|try]' })
608 await $.command.register({ name: 'sharp', description: 'Short for /sharpprompt', argumentHint: '[status|on|off|mode|undo|stats|try]' })
609 return next(e)
610 })
611
612 on('command.run', { command: 'sharpprompt' }, async ($, e) => ({ text: await runCommand($, e.args, options) }))
613 on('command.run', { command: 'sharp' }, async ($, e) => ({ text: await runCommand($, e.args, options) }))
614
615 // A prompt typed over a running turn, or delivered into it (a task
616 // notification), carries its turnId: that turn's tool count and record
617 // are left as they are, and it is not counted as a turn of its own.
618 on('prompt.submit', async ($, e, next) => {
619 if (e.turnId === undefined) {
620 outgoing = null
621 toolCalls = 0
622 turnLog = null
623 return submit($, e, next, options)
624 }
625 const kept = { outgoing, turnLog }
626 try {
627 return await submit($, e, next, options)
628 } finally {
629 outgoing = kept.outgoing
630 turnLog = kept.turnLog
631 }
632 }).catch(($, e, next) => next(e))
633
634 on('tool.call', ($, e, next) => {
635 // $.ui.ask runs as an AskUserQuestion call made by us: no tool call of the turn.
636 if (!e.agentId && next.origin.plugin !== 'sharpprompt') toolCalls++
637 return next(e)
638 }).catch(($, e, next) => next(e))
639
640 // One record per turn a typed prompt started, for /sharp stats. Subagent
641 // turns and turns nobody typed are left out.
642 on('turn.complete', async ($, e, next) => {
643 if (!e.agentId && outgoing) {
644 const turn: TurnRecord = {
645 prompt: outgoing,
646 durationMs: e.durationMs,
647 tools: toolCalls,
648 asked: endsWithQuestion(e.answer),
649 usage: tokens(e.usage),
650 aborted: e.isAborted,
651 }
652 outgoing = null
653 await push($, 'turns', turn)
654 await updateLog($, turnLog, { turn: { durationMs: turn.durationMs, tools: turn.tools, asked: turn.asked, aborted: turn.aborted } })
655 turnLog = null
656 }
657 if (late.forks > 0) {
658 // Taken and reset before any await: a fork that lands meanwhile goes to
659 // the next flush instead of being wiped by this one.
660 const { forks, ms, usage } = late
661 late.forks = 0
662 late.ms = []
663 late.usage = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
664 const add = { 'late:forks': forks, 'late:input': usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens, 'late:output': usage.output_tokens }
665 const at = await $.clock.now().catch(() => Date.now())
666 const model = await $.session.model().catch(() => 'unknown')
667 const item: LateRecord = { at, forks, ms, model, usage: tokens(usage) }
668 await bump($, add)
669 await push($, 'late', item)
670 }
671 return next(e)
672 }).catch(($, e, next) => next(e))
673
674 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
675 const p = (await $.state.get(pending)).value
676 if (!p || e.props.hasSurvey) return next(e)
677 const { Box, Button, Text } = $.ui.resolve(e)
678 // Says what is in the box now, so no one takes it for the suggestion.
679 if (p.kind === 'restored') return <Text dimColor>sharpprompt: your own prompt is back in the box; edited or not, it goes out as you send it.</Text>
680 const was = p.original.length > 70 ? `${p.original.slice(0, 70)}...` : p.original
681 // What the person picked in the dialog is theirs, not news.
682 const extra = addedLine(`${p.original} ${p.asked ?? ''}`, p.rewritten)
683 const note = extra ? <Text color="warning">{extra}</Text> : null
684 if (p.kind === 'replaced') {
685 return (
686 <Box flexDirection="column">
687 <Text dimColor>sharpprompt sent a rewrite of: {was}</Text>
688 {note}
689 <Box>
690 <Button key="undo" hotkey="u" label="put my original in the box" onPress={() => restoreOriginal($, p)} />
691 <Button key="dismiss" hotkey="x" label="ok" role="dismiss" onPress={() => $.state.set(pending, null)} />
692 </Box>
693 </Box>
694 )
695 }
696 return (
697 <Box flexDirection="column">
698 <Text dimColor>sharpprompt rewrote: {was}</Text>
699 {note}
700 <Box>
701 <Text dimColor>Enter sends it, or edit it in the box. </Text>
702 <Button key="raw" hotkey="r" action={BACK_TO_MINE} label="back to mine" onPress={() => restoreOriginal($, p)} />
703 </Box>
704 </Box>
705 )
706 })
707}
708hooks/flow.ts 123 lines1import type { SharppromptDecision, SharppromptMode } from '../types'
2import { wordCount as words } from './stats'
3
4// Pure helpers for delivery and the slash command.
5
6export const MODES: readonly SharppromptMode[] = ['fill', 'replace', 'context', 'off']
7
8// Words of any script, not just ASCII: split on \W, two Russian texts had
9// no words at all and counted as the same. Marks (\p{M}) stay in the word,
10// or Hindi falls apart into single consonants. Chinese, Japanese, Korean,
11// Thai, Lao, Khmer and Myanmar put no spaces between words, or (Korean)
12// glue endings to them: there pairs of characters stand in for words, and a
13// Latin name glued to them (修复getUserProfile函数) stays one word.
14// Script_Extensions, so the long-vowel mark ー stays in its katakana word.
15const PAIRED = String.raw`\p{scx=Han}\p{scx=Hiragana}\p{scx=Katakana}\p{scx=Hangul}\p{scx=Thai}\p{scx=Lao}\p{scx=Khmer}\p{scx=Myanmar}`
16const CJK_RUN = new RegExp(`[${PAIRED}]+|[^${PAIRED}]+`, 'gu')
17const IS_CJK = new RegExp(`^[${PAIRED}]`, 'u')
18function bag(s: string): Set<string> {
19 const out = new Set<string>()
20 for (const w of s.toLowerCase().split(/[^\p{L}\p{M}\p{N}_]+/u)) {
21 for (const run of w.match(CJK_RUN) ?? []) {
22 const chars = [...run]
23 if (!IS_CJK.test(run) || chars.length < 2) {
24 out.add(run)
25 continue
26 }
27 for (let i = 0; i < chars.length - 1; i++) out.add(chars[i]! + chars[i + 1]!)
28 }
29 }
30 return out
31}
32
33// Word overlap of two texts, 0 to 1. Above EDIT_OVERLAP a prompt sent while
34// our suggestion sits in the box counts as the suggestion, edited.
35export function overlap(a: string, b: string): number {
36 const x = bag(a)
37 const y = bag(b)
38 // Nothing to compare (emoji only, say) is no evidence of an edit.
39 if (x.size === 0 && y.size === 0) return 0
40 let both = 0
41 for (const w of x) if (y.has(w)) both++
42 return both / (x.size + y.size - both)
43}
44
45export const EDIT_OVERLAP = 0.4
46
47// Share of a's words still in b, 0 to 1: one-sided, so adding to a text
48// keeps it at 1 however much is added.
49export function kept(a: string, b: string): number {
50 const x = bag(a)
51 if (x.size === 0) return 0
52 const y = bag(b)
53 let both = 0
54 for (const w of x) if (y.has(w)) both++
55 return both / x.size
56}
57
58// Nearly all of a text still there: it was added to, not replaced. Kept
59// alone is not enough below this, as small words count too and a new
60// prompt on the same subject keeps most of them.
61export const KEPT_ADDED = 0.9
62
63// b is a, edited or added to: word overlap for an edit, or nearly all of a
64// kept for an addition, which overlap alone took for a new prompt (23 Oct
65// 2026: the person's own text put back with back to mine, added to and sent,
66// got rewritten all over again).
67export const isEditOf = (a: string, b: string) => overlap(a, b) >= EDIT_OVERLAP || kept(a, b) >= KEPT_ADDED
68
69export function contextNote(rewritten: string): string {
70 return `The sharpprompt plugin read the user's request above as the following. Use it only where it matches what the user wrote:\n${rewritten}`
71}
72
73export const DROP_NOTE = 'sharpprompt put a clearer version in the box. Enter sends it, ctrl+x tab then r puts yours back.'
74
75export type Command =
76 | { kind: 'status' }
77 | { kind: 'on' }
78 | { kind: 'off' }
79 | { kind: 'mode'; mode: SharppromptMode }
80 | { kind: 'undo' }
81 | { kind: 'stats' }
82 | { kind: 'try'; text: string }
83 | { kind: 'help'; error?: string }
84
85export function parseCommand(args: string): Command {
86 const [word = '', ...rest] = args.trim().split(/\s+/)
87 const tail = args.trim().slice(word.length).trim()
88 switch (word.toLowerCase()) {
89 case '':
90 case 'status':
91 return { kind: 'status' }
92 case 'on':
93 return { kind: 'on' }
94 case 'off':
95 return { kind: 'off' }
96 case 'undo':
97 return { kind: 'undo' }
98 case 'stats':
99 return { kind: 'stats' }
100 case 'try':
101 return tail ? { kind: 'try', text: tail } : { kind: 'help', error: 'try needs a prompt to try' }
102 case 'mode': {
103 const m = rest[0] as SharppromptMode | undefined
104 return m && MODES.includes(m) ? { kind: 'mode', mode: m } : { kind: 'help', error: `mode is one of ${MODES.join(', ')}` }
105 }
106 default:
107 return { kind: 'help', error: `unknown: ${word}` }
108 }
109}
110
111export const HELP = `/sharpprompt (or /sharp) status | on | off | mode fill|replace|context|off | undo | stats | try <prompt>
112Start a prompt with raw: to send it untouched.`
113
114export function describe(d: SharppromptDecision | null): string {
115 if (!d) return 'no prompt seen yet'
116 if (d.verdict === 'skip') return `passed untouched (${d.reason})`
117 const classify = d.classifyMs === undefined ? '' : ` in ${d.classifyMs} ms`
118 if (!('rewrite' in d) || !d.rewrite) return `classified ${d.verdict}${classify}, sent as typed`
119 const r = d.rewrite
120 const size = r.text ? `, ${words(d.text)} -> ${words(r.text)} words` : `, ${words(d.text)} words`
121 return `${d.verdict === 'long' ? 'long, tidied' : `classified ${d.verdict}`}${classify}, rewrite ${r.outcome} via ${r.via} in ${r.ms} ms${size}`
122}
123hooks/facts.ts 59 lines1import type { SessionMessage } from 'claude-code'
2
3// What this session has touched, read from the transcript alone (no disk):
4// files read or changed, the last command that failed, and the gist of
5// Claude's last reply. Kept under about 300 tokens.
6
7const FILE_TOOLS: Record<string, 'read' | 'changed'> = { Read: 'read', Edit: 'changed', Write: 'changed', MultiEdit: 'changed', NotebookEdit: 'changed' }
8const MAX_CHARS = 1200
9
10const tail = (s: string, n: number) => (s.length > n ? `...${s.slice(-n)}` : s)
11const head = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}...` : s)
12
13// The last eight, cut from the front to fit their share of MAX_CHARS, so a
14// long list loses its oldest files, not its newest.
15const LIST_CHARS = 400
16function recent(paths: readonly string[]): string {
17 const list = paths.slice(-8)
18 while (list.length > 1 && list.join(', ').length > LIST_CHARS) list.shift()
19 return list.join(', ')
20}
21
22export function sessionFacts(rows: readonly SessionMessage[]): string {
23 const read = new Set<string>()
24 const changed = new Set<string>()
25 let failed: { command: string; output: string } | null = null
26 let lastReply = ''
27
28 for (const row of rows) {
29 if (row.role === 'assistant' && row.text.trim()) lastReply = row.text.trim()
30 for (const use of row.toolUses ?? []) {
31 const kind = FILE_TOOLS[use.tool]
32 const path = typeof use.input?.file_path === 'string' ? use.input.file_path : typeof use.input?.notebook_path === 'string' ? use.input.notebook_path : null
33 // Deleted first so a file touched again moves to the end, and the
34 // last eight kept are the most recent. A changed file read again is
35 // still a changed file, now a recent one.
36 if (kind && path) {
37 const set = kind === 'changed' || changed.has(path) ? changed : read
38 set.delete(path)
39 set.add(path)
40 }
41 if (use.tool === 'Bash' && typeof use.input?.command === 'string') {
42 const out = use.text ?? ''
43 // "0 failed" is a pass; "2 failed", FAIL, a traceback or an error line is not.
44 const bad = use.isError === true || /\b(FAIL|FAILED|Traceback)\b|Error\b|\b[1-9]\d* failed\b/.test(out)
45 failed = bad ? { command: use.input.command, output: out } : null
46 }
47 }
48 }
49 for (const p of changed) read.delete(p)
50
51 const lines: string[] = []
52 if (changed.size) lines.push(`Files changed this session: ${recent([...changed])}`)
53 if (read.size) lines.push(`Files read this session: ${recent([...read])}`)
54 if (failed) lines.push(`Last command failed: ${head(failed.command, 120)}\nIts output ended with:\n${tail(failed.output.trim(), 400)}`)
55 if (lastReply) lines.push(`Claude's last reply began: ${head(lastReply.replace(/\s+/g, ' '), 240)}`)
56 const text = lines.join('\n')
57 return text.length > MAX_CHARS ? head(text, MAX_CHARS) : text
58}
59hooks/gate.ts 60 lines1import type { PromptOrigin } from 'claude-code'
2import type { SharppromptSkip } from '../types'
3
4// The cheap part of the decision: no model, no awaits. Anything this lets
5// through still has to be called rough by the classifier before we touch it.
6
7export type GateInput = {
8 text: string
9 origin: PromptOrigin
10 minChars: number
11 isOff: boolean
12}
13
14export type GateDecision =
15 | { pass: true; reason: SharppromptSkip; text: string }
16 | { pass: false }
17
18export const MAX_CHARS = 20_000
19
20export const RAW_PREFIX = /^raw:\s?/i
21const HARNESS_TAG = /<(task-notification|system-reminder|command-[a-z-]+|local-command-[a-z-]+)[\s>]/
22
23// Only what a person typed (or sent from their phone) is ours to look at.
24const TYPED: ReadonlySet<PromptOrigin['kind']> = new Set(['composer', 'bridge'])
25
26export const isTyped = (origin: PromptOrigin) => TYPED.has(origin.kind)
27
28export function gate(input: GateInput): GateDecision {
29 const { text, origin, minChars, isOff } = input
30 const pass = (reason: SharppromptSkip, out = text): GateDecision => ({ pass: true, reason, text: out })
31
32 if (!TYPED.has(origin.kind)) return pass('not-typed')
33 if (RAW_PREFIX.test(text)) return pass('raw', text.replace(RAW_PREFIX, ''))
34 if (isOff) return pass('off')
35
36 const trimmed = text.trim()
37 if (trimmed.startsWith('/')) return pass('command')
38 if (trimmed.startsWith('#')) return pass('heading')
39 if (trimmed.length < minChars) return pass('too-short')
40 if (trimmed.length > MAX_CHARS) return pass('too-long')
41 if (HARNESS_TAG.test(trimmed)) return pass('harness-tag')
42
43 return { pass: false }
44}
45
46// When Claude's last reply ended on a question, the next prompt is almost
47// always the answer to it, and rewriting an answer only gets in the way.
48// A code block at the very end ("Want me to run it?" then the command) is
49// skipped, so the question before it counts and a "?" inside it does not.
50export function endsWithQuestion(reply: string): boolean {
51 let text = reply.trimEnd()
52 while (text.endsWith('```')) {
53 const open = text.lastIndexOf('```', text.length - 4)
54 if (open < 0) break
55 text = text.slice(0, open).trimEnd()
56 }
57 const tail = text.replace(/[*_`)\]"'”’»\s]+$/u, '')
58 return tail.endsWith('?') || tail.endsWith('?')
59}
60hooks/log.ts 78 lines1import type { SharppromptDecision, SharppromptQuestion } from '../types'
2import type { TurnRecord } from './stats'
3
4// The usage log: for every prompt that went to the rewriter, the texts and
5// what the user did with the result. It lives in $.store on the user's
6// machine, nothing sends it anywhere, and scripts/export_log.mjs copies it
7// out when the user asks. userConfig `log: false` turns it off.
8
9export type LogAction =
10 // Sent the rewrite unchanged, sent it after editing, put their own text
11 // back, or typed something else while it waited.
12 'as-is' | 'edited' | 'original' | 'abandoned'
13
14export type LogRecord = {
15 id: string
16 at: string
17 model?: string
18 draft: string
19 verdict: string
20 classifyMs?: number
21 outcome: string
22 via: 'fork' | 'complete'
23 ms: number
24 // Characters in the model's reply before cleaning.
25 replyChars?: number
26 rewrite?: string
27 questions?: { question: string; options: string[] }[]
28 // The labels picked, or 'dismissed' when a dialog was closed.
29 answers?: Record<string, string> | 'dismissed'
30 // How the result went out: in the box (fill), sent for the user (replace),
31 // as context, or not at all (typed: the draft went as it was).
32 delivered?: 'fill' | 'replace' | 'context' | 'typed'
33 // The text put in the box or sent, after the answers were added.
34 boxed?: string
35 // How long putting it in the box took.
36 fillMs?: number
37 action?: LogAction
38 // What the user sent instead, when they edited it.
39 sent?: string
40 // The turn the prompt started, as /sharp stats keeps it.
41 turn?: Omit<TurnRecord, 'prompt' | 'usage'>
42}
43
44export const MAX_LOG = 300
45
46// The store holds 4 MiB of JSON in all; one very long paste must not crowd
47// out the rest.
48export const MAX_TEXT = 2_000
49export const clip = (t: string) => (t.length > MAX_TEXT ? `${t.slice(0, MAX_TEXT)}...` : t)
50
51export function newRecord(id: string, at: string, model: string | undefined, d: SharppromptDecision): LogRecord | null {
52 if (!('rewrite' in d) || !d.rewrite) return null
53 const r = d.rewrite
54 return {
55 id,
56 at,
57 ...(model ? { model } : {}),
58 draft: clip(d.text),
59 verdict: d.verdict,
60 ...(d.classifyMs === undefined ? {} : { classifyMs: d.classifyMs }),
61 outcome: r.outcome,
62 via: r.via,
63 ms: r.ms,
64 ...(r.replyChars === undefined ? {} : { replyChars: r.replyChars }),
65 ...(r.text ? { rewrite: clip(r.text) } : {}),
66 ...(r.questions?.length ? { questions: r.questions.map((q: SharppromptQuestion) => ({ question: q.question, options: q.options.map(o => o.label) })) } : {}),
67 }
68}
69
70// Applies a change to one record; a record that fell off the end is left alone.
71export function patchLog(list: readonly LogRecord[], id: string, patch: Partial<LogRecord>): LogRecord[] {
72 return list.map(r => (r.id === id ? { ...r, ...patch } : r))
73}
74
75export function logLine(on: boolean, n: number): string {
76 return on ? `Log: ${n} records, on this machine only (scripts/export_log.mjs copies them out).` : 'Log: off.'
77}
78hooks/questions.ts 84 lines1// The questions a rewrite may come back with, and how answers turn into
2// sentences of the prompt. No $ here.
3
4export type QuestionOption = { label: string; adds: string }
5export type Question = { question: string; header: string; options: QuestionOption[] }
6
7// Each question is its own dialog, so two at most.
8export const MAX_QUESTIONS = 2
9export const MAX_ADDS = 200
10
11// The rewriter writes its rewrite, then optionally a QUESTIONS: line with a
12// JSON array. The rewriter leaves an asked point out of the rewrite, so a
13// question we cannot ask (malformed, too many, too few usable options)
14// leaves a rewrite with a hole in it: dropped is then true and the rewrite
15// is turned down.
16export function splitReply(reply: string): { body: string; questions: Question[]; dropped: boolean } {
17 const at = reply.search(/\n\s*QUESTIONS:\s*/)
18 if (at < 0) return { body: reply, questions: [], dropped: false }
19 const body = reply.slice(0, at)
20 const json = reply.slice(at).replace(/^\s*QUESTIONS:\s*/, '').trim()
21 let raw: unknown
22 try {
23 raw = JSON.parse(json.replace(/^```(?:json)?\s*|\s*```$/g, ''))
24 } catch {
25 return { body, questions: [], dropped: true }
26 }
27 if (!Array.isArray(raw)) return { body, questions: [], dropped: true }
28 const questions: Question[] = []
29 let dropped = raw.length > MAX_QUESTIONS
30 for (const q of raw) {
31 if (questions.length === MAX_QUESTIONS) break
32 if (!q || typeof q.question !== 'string' || !Array.isArray(q.options)) {
33 dropped = true
34 continue
35 }
36 const options = q.options
37 .filter((o: unknown): o is QuestionOption => !!o && typeof (o as QuestionOption).label === 'string' && typeof (o as QuestionOption).adds === 'string')
38 .slice(0, 4)
39 .map((o: QuestionOption) => ({ label: o.label.trim().slice(0, 60), adds: o.adds.trim() }))
40 // An answer adds one sentence; a longer one would blow past the
41 // rewrite's word limit after the length check has run. Dropping just
42 // that option could move "(recommended)" onto another, so the question goes.
43 if (options.length < 2 || options.some((o: QuestionOption) => o.adds.length > MAX_ADDS)) {
44 dropped = true
45 continue
46 }
47 const header = typeof q.header === 'string' && q.header.trim() ? q.header.trim().slice(0, 12) : 'Question'
48 questions.push({ question: q.question.trim(), header, options })
49 }
50 return { body, questions, dropped }
51}
52
53// The AskUserQuestion input: the first option is the rewriter's
54// recommendation and says so.
55export function askInput(questions: readonly Question[]) {
56 return {
57 questions: questions.map(q => ({
58 question: q.question,
59 header: q.header,
60 multiSelect: false,
61 options: q.options.map((o, i) => ({ label: i === 0 ? `${o.label} (recommended)` : o.label, description: o.adds })),
62 })),
63 }
64}
65
66// Answers keyed by question text, as AskUserQuestion returns them. A picked
67// option adds its sentence; anything else typed under "Other" is added as
68// the user wrote it. An unanswered question adds the recommended option.
69export function applyAnswers(rewrite: string, questions: readonly Question[], answers: Readonly<Record<string, unknown>>): string {
70 const lines = questions.map(q => {
71 const a = typeof answers[q.question] === 'string' ? (answers[q.question] as string).trim() : ''
72 const picked = q.options.find((o, i) => a === o.label || a === `${o.label} (recommended)` || (i === 0 && a === ''))
73 if (picked) return picked.adds
74 return `${q.header}: ${a}.`
75 })
76 return [rewrite.trim(), ...lines].join(' ')
77}
78
79// With no one to ask (VS Code, headless), each question takes its
80// recommended option.
81export function recommended(rewrite: string, questions: readonly Question[]): string {
82 return applyAnswers(rewrite, questions, {})
83}
84hooks/stats.ts 126 lines1import type { SharppromptDecision, SharppromptRewrite } from '../types'
2
3// What we keep per turn and how /sharp stats sums it up. Everything stays in
4// $.store on the user's machine.
5
6export type Tokens = { input: number; output: number; cacheRead: number; cacheWrite: number }
7
8export type TurnRecord = {
9 // How the prompt that started the turn got there.
10 prompt: 'typed' | 'rewritten' | 'edited' | 'context'
11 durationMs: number
12 tools: number
13 // Claude's final text ended on a question: it needed more from the user.
14 asked: boolean
15 usage?: Tokens
16 aborted: boolean
17}
18
19export type RewriteRecord = {
20 outcome: string
21 via: 'fork' | 'complete'
22 ms: number
23 classifyMs?: number
24 usage?: Tokens
25 // Words in the draft and in the rewrite, when there was one.
26 words?: [number, number?]
27 // The session model the fork ran on.
28 model?: string
29 // When it happened (ms since the epoch), and the helper model when the
30 // rewrite was the fallback completion rather than a fork.
31 at?: number
32 helper?: string
33 // Characters in the reply before cleaning; output tokens far past a
34 // quarter of this went to thinking.
35 replyChars?: number
36}
37
38// Every classified prompt, so short-but-rough patterns show once n grows.
39// The engine's classify returns a label only, no token usage; the words and
40// the helper model let scripts/token_overhead.mjs estimate it.
41export type ClassifyRecord = { verdict: string; ms: number; words: number; at?: number; model?: string }
42
43// Every prompt a person typed and how it went (the counts key), with its time.
44export type DecisionRecord = { at: number; key: string }
45
46// Forks that lost the race and finished anyway, flushed at the end of a turn.
47// ms: how long each late fork took from the start of its rewrite.
48export type LateRecord = { at: number; forks: number; ms?: number[]; model?: string; usage?: Tokens }
49
50export type Counts = Record<string, number>
51
52export const MAX_RECORDS = 500
53
54// Chinese and Japanese write no spaces: a run of their characters counts
55// as one word per two characters, so a long draft there is still long.
56export const wordCount = (t: string) =>
57 t
58 .split(/\s+/)
59 .filter(Boolean)
60 .reduce((n, w) => n + Math.max(1, Math.ceil((w.match(/[\p{scx=Han}\p{scx=Hiragana}\p{scx=Katakana}]/gu)?.length ?? 0) / 2)), 0)
61
62// Every outcome but rewritten, in the order /sharp stats lists them; a new
63// outcome in the type fails to compile until it is here.
64const NOT_REWRITTEN: Record<Exclude<SharppromptRewrite['outcome'], 'rewritten'>, true> = { keep: true, same: true, 'too-long': true, lost: true, empty: true, timeout: true, aborted: true, error: true }
65
66export function lastRewriteLine(r: RewriteRecord | undefined): string {
67 if (!r) return 'Last rewrite: none yet'
68 const w = r.words ? `, ${r.words[0]}${r.words[1] === undefined ? '' : ` -> ${r.words[1]}`} words` : ''
69 const c = r.classifyMs === undefined ? '' : `classify ${r.classifyMs} ms, `
70 return `Last rewrite: ${r.outcome}, ${c}${r.via} ${r.ms} ms${w}`
71}
72
73export function tokens(u: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number } | undefined): Tokens | undefined {
74 if (!u) return undefined
75 return { input: u.input_tokens, output: u.output_tokens, cacheRead: u.cache_read_input_tokens, cacheWrite: u.cache_creation_input_tokens }
76}
77
78// The counter a decision bumps: why it passed, or what the classifier said.
79export function countKey(d: SharppromptDecision): string {
80 if (d.verdict === 'skip') return `skip:${d.reason}`
81 return `verdict:${d.verdict}`
82}
83
84export function pct(values: readonly number[], p: number): number | undefined {
85 if (values.length === 0) return undefined
86 const sorted = [...values].sort((a, b) => a - b)
87 return sorted[Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length))]
88}
89
90const avg = (xs: readonly number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : undefined)
91const fmt = (x: number | undefined, unit = '') => (x === undefined ? '-' : `${Math.round(x)}${unit}`)
92const spread = (xs: readonly number[]) => (xs.length ? `${fmt(pct(xs, 50))} / ${fmt(pct(xs, 95))} ms (n=${xs.length})` : '-')
93const share = (n: number, of: number) => (of ? `${Math.round((100 * n) / of)}%` : '-')
94
95function turnLine(label: string, turns: readonly TurnRecord[]): string {
96 const done = turns.filter(t => !t.aborted)
97 return `${label}: n=${turns.length}, tools ${fmt(avg(done.map(t => t.tools)))}, ${fmt(avg(done.map(t => t.durationMs / 1000)), ' s')}, Claude asked back ${share(done.filter(t => t.asked).length, done.length)}, output ${fmt(avg(done.map(t => t.usage?.output ?? 0)), ' tok')}`
98}
99
100export function summary(counts: Counts, rewrites: readonly RewriteRecord[], turns: readonly TurnRecord[], classified: readonly ClassifyRecord[] = []): string {
101 const c = (k: string) => counts[k] ?? 0
102 const skips = Object.entries(counts)
103 .filter(([k]) => k.startsWith('skip:'))
104 .sort((a, b) => b[1] - a[1])
105 .map(([k, v]) => `${k.slice(5)} ${v}`)
106 const seen = Object.entries(counts).filter(([k]) => k.startsWith('skip:') || k.startsWith('verdict:')).reduce((a, [, v]) => a + v, 0)
107 const ok = rewrites.filter(r => r.outcome === 'rewritten')
108 const forks = rewrites.filter(r => r.via === 'fork' && r.outcome !== 'timeout')
109 const rough = c('verdict:rough')
110 const spent = rewrites.map(r => r.usage).filter((u): u is Tokens => !!u)
111
112 return [
113 `Prompts seen: ${seen}. Passed by the gate: ${skips.join(', ') || 'none'}.`,
114 `Classified: clear ${c('verdict:clear')}, rough ${rough}, long ${c('verdict:long')}, timeout ${c('verdict:timeout')}, error ${c('verdict:error')}.`,
115 `Rewrites: ${ok.length} made, ${rewrites.length - ok.length} not (${Object.keys(NOT_REWRITTEN).map(o => `${o} ${rewrites.filter(r => r.outcome === o).length}`).join(', ')}).`,
116 `What you did with them: sent as is ${c('answer:as-is')}, edited ${c('answer:edited')}, took yours back ${c('answer:original')}.`,
117 `Wait (p50 / p95): classify ${spread(classified.map(x => x.ms))}, fork ${spread(forks.map(r => r.ms))}, fallback completion ${spread(rewrites.filter(r => r.via === 'complete').map(r => r.ms))}.`,
118 `Cost per rough prompt: ${fmt(avg(spent.map(u => u.input)))} in, ${fmt(avg(spent.map(u => u.cacheRead)))} from cache, ${fmt(avg(spent.map(u => u.output)))} out. Forks that lost the race and finished anyway: ${c('late:forks')}, ${c('late:output')} output tokens, ${c('late:input')} input.`,
119 turnLine('Turns after a typed prompt', turns.filter(t => t.prompt === 'typed')),
120 turnLine('Turns after a rewrite', turns.filter(t => t.prompt !== 'typed')),
121 turns.length < 30 ? 'Too few turns to compare yet; these numbers are not evidence.' : '',
122 ]
123 .filter(Boolean)
124 .join('\n')
125}
126hooks/rewrite.ts 280 lines1import { RULES, SHAPES, type Family } from './bank'
2import { wordCount as words } from './stats'
3
4// Everything about the rewrite that needs no $: which rules apply, the text
5// we send the model, and what we accept back.
6
7export const MAX_WORDS = 180
8export const MIN_ROOM = 60
9// From this many words a draft is tidied, not rewritten: in two days of the
10// author's use the long ones were repetitive rather than vague.
11export const LONG_WORDS = 60
12export const KEEP = 'KEEP'
13
14export type Exemplar = { original: string; sent: string }
15
16// 'same' keeps the user's language; 'en' asks for English whatever the
17// draft is written in (the rewriteLanguage setting).
18export type RewriteOptions = {
19 language?: 'same' | 'en'
20 // May the rewriter ask about gaps before the prompt goes out?
21 ask?: boolean
22 // What the session touched, from the transcript (see facts.ts).
23 facts?: string
24 // How many of the last messages the fallback completion sees (default 4).
25 // The benchmark passes them all, standing in for the fork it cannot use.
26 window?: number
27}
28
29const ASK = `If the draft leaves out a value the work needs that only the user can supply (a separator, a threshold, a count, an order, a currency, a date format, a file or function name), ask for it, at most 2 questions; if two values are missing, ask both. If the draft names such a thing without its value, the value itself is the question. When the draft defers to another team's or tool's expectation (their import, their format, what another system accepts), ask for that expectation itself; it is not in the code. Do not ask what you can read in the conversation or infer from the code, and never ask whether to add tests (the answer is no). Options are candidate values (';', ',', tab; EUR, USD; 3, 5), never ways of supplying the information ('paste a sample', 'I'll list it', 'spec in repo'); if you cannot name candidates, give two plausible values and let the user type the rest. Name at least two different values in the labels, never a single example. If you ask, leave those points out of the rewrite, because the answers will be added after it. Then, after the rewrite, write a line QUESTIONS: followed by a JSON array, each item {"question": "...?", "header": "<12 characters", "options": [{"label": "<1-5 words>", "adds": "<the sentence to add to the prompt if picked>"}]}, 2 to 4 options each, your recommended option first. If nothing needs asking, write no QUESTIONS line. This overrides the rule about taking the most direct reading: a value only the user knows is asked, not assumed.`
30
31const ENGLISH = `Write the rewrite in English, whatever language the draft is in; this overrides the rules about the user's language. Keep file names, function names, commands and quoted text exactly as written. If the draft is not in English, do not reply ${'KEEP'}: translate it while you make it clear.`
32
33export function familyOf(model: string): Family {
34 const m = model.toLowerCase()
35 for (const f of ['fable', 'opus', 'sonnet', 'haiku'] as const) {
36 if (m.includes(f)) return f
37 }
38 return 'common'
39}
40
41export const isLong = (draft: string) => words(draft) >= LONG_WORDS
42
43const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}...` : s)
44
45function rulesFor(family: Family): string {
46 const list = family === 'common' ? RULES.common : [...RULES.common, ...RULES[family]]
47 return list.map(r => `- ${r.text}`).join('\n')
48}
49
50function shapes(): string {
51 return SHAPES.map(s =>
52 [
53 `${s.name}: ${s.summary} A good one carries: ${s.fields}`,
54 ` Before: ${s.before}`,
55 ` After: ${s.after}`,
56 ].join('\n'),
57 ).join('\n')
58}
59
60// The user's own edits of earlier suggestions: what they changed our
61// rewrite into is the best signal of how they like their prompts.
62function exemplars(list: readonly Exemplar[]): string {
63 if (list.length === 0) return ''
64 const items = list
65 .slice(-20)
66 .map(x => `<example>\nSuggested: ${clip(x.original, 400)}\nUser sent instead: ${clip(x.sent, 400)}\n</example>`)
67 .join('\n')
68 return `\nWhen this user edited a suggestion before sending, this is what they changed it to. Match their taste:\n<examples>\n${items}\n</examples>\n`
69}
70
71// How long a rewrite of this draft may be: twice the draft or 60 words,
72// whichever is more, never past 180. The model gets this number, not 180:
73// told 180, it wrote 77 and 125 words for 16 and 14 word drafts. A long
74// draft is tidied, and tidying does not make it longer.
75export function wordLimit(draft: string): number {
76 if (isLong(draft)) return words(draft)
77 return Math.min(Math.max(2 * words(draft), MIN_ROOM), MAX_WORDS)
78}
79
80const TIDY = `The draft is long and was typed in one go: it may say the same thing twice, jump between points, or contradict itself. Tidy it:
81- Keep every request and constraint. Keep every number, file name, path, command, URL and quoted text exactly as written.
82- Say each thing once: merge the repeats.
83- Put the requests in the order they should be done; number them if there are three or more.
84- Where two parts contradict and the conversation does not settle it, keep the later one and add a short line naming the conflict.
85- Add nothing the draft does not say: no new requirements, files, checks or tests.
86- Keep any <pasted_content> block exactly as it is, its tags included.
87- Keep the user's voice and language.`
88
89function tidyInstructions(list: readonly Exemplar[], limit: number, opts: RewriteOptions): string {
90 return `${TIDY}
91${opts.language === 'en' ? `\n${ENGLISH}\n` : ''}${opts.ask ? `\n${ASK}\n` : ''}${exemplars(list)}
92If the draft is already in order and says each thing once, reply with exactly ${KEEP}.
93Give the tidied prompt and nothing else, at most ${limit} words.`
94}
95
96// The things a rewrite must not lose: quoted and code spans, URLs, paths,
97// file names, commit hashes and numbers (list markers aside). On 28 real rewrites from the
98// author's sessions none was flagged.
99// facts: only what goes stale or gets mixed up (URLs, paths, file names,
100// hashes, numbers of two digits or more), for the band's added line; quoted
101// labels and small numbers there were mostly echoes of the conversation.
102export function anchors(draft: string, kind: 'all' | 'facts' = 'all'): string[] {
103 const out = new Set<string>()
104 const take = (re: RegExp, text = draft, g = 0) => {
105 for (const m of text.matchAll(re)) if (m[g]?.trim()) out.add(m[g].trim())
106 }
107 if (kind === 'all') {
108 take(/`([^`\n]+)`/g, draft, 1)
109 // One character is enough: ";" not "," gives ; and , (at two or more,
110 // the words between them were taken instead).
111 take(/"([^"\n]{1,80})"/g, draft, 1)
112 }
113 take(/https?:\/\/\S+[^\s.,;:!?)'"`>\]*]/g)
114 // and/or, w/o, I/O, login/logout are words, not paths: a path starts at
115 // the root, home or here, ends in a slash or a file name, or has two slashes.
116 for (const m of draft.matchAll(/(?<![\p{L}\p{M}\p{N}_./~-])[./~]*\/?(?:[\p{L}\p{M}\p{N}_.~-]+\/)+(?:[\p{L}\p{M}\p{N}_.-]*[\p{L}\p{M}\p{N}_-])?/gu)) {
117 const p = m[0].replace(/^\.(?=[^./])/, '')
118 if (/^[./~]/.test(p) || /\/$/.test(p) || (p.match(/\//g) ?? []).length >= 2 || /\.[\p{L}\p{N}]+$/u.test(p)) out.add(p)
119 }
120 take(/(?<![\p{L}\p{M}\p{N}_-])[\p{L}\p{M}\p{N}_-]+\.(?:py|ts|tsx|js|mjs|json|md|png|jpg|jpeg|txt|sh|yml|yaml|toml|csv|xlsx|html|css|mp4|srt|log)(?![\p{L}\p{M}\p{N}_])/giu)
121 take(/\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/g)
122 // Markers that start lines count as a list from two lines on, whatever
123 // their numbers: "1. ve 2. satırları sil" on one line keeps its 1.
124 const atLineStart = /(^|\n)\s*\d+[-.)]\s/g
125 const lined = dropListMarkers(draft)
126 const unlisted = (draft.match(atLineStart) ?? []).length >= 2 ? lined.replace(atLineStart, '$1') : lined
127 take(kind === 'all' ? /(?<![\w.])\d+(?:[.,]\d+)*(?![\d.,]*\d)/g : /(?<![\w.])\d{2,}(?:[.,]\d+)*(?![\d.,]*\d)/g, unlisted)
128 // A piece of a longer one (test.ts in tests/auth.test.ts) adds nothing.
129 return [...out].filter(a => ![...out].some(b => b !== a && b.includes(a) && hasToken(b, a)))
130}
131
132// List markers are not numbers to keep: 1. 2. (or 1) 2), (1) (2), 1、2、)
133// at a line start or inline. A list is markers of one style counting up
134// from 1, two or more, each item two words or more, and a new 1 starts
135// another list (two lists, or one inside another). So the 30 in "timeout
136// to 30. 2. ...", the 12 in "12. satır", sleep(1), 1.x and "1. ve 2." stay
137// numbers: dropping a real one would let a rewrite change it unseen.
138const MARKER = /(?<=^|[\s:;,!?:;,、。!?])(?:([((])(\d{1,2})([))])|(\d{1,2})(?:[.))](?=\s)|、))/gu
139function dropListMarkers(s: string): string {
140 type Mark = { at: number; end: number; n: number }
141 const open = new Map<string, Mark[]>()
142 const lists: Mark[][] = []
143 for (const m of s.matchAll(MARKER)) {
144 // The style is the marker less its number: "1." and "2." are one list.
145 const style = m[0].replace(/\d+/, '')
146 const mark = { at: m.index ?? 0, end: (m.index ?? 0) + m[0].length, n: Number(m[2] ?? m[4]) }
147 const run = open.get(style)
148 if (run && mark.n === run.length + 1) run.push(mark)
149 else if (mark.n === 1) {
150 const fresh = [mark]
151 open.set(style, fresh)
152 lists.push(fresh)
153 }
154 }
155 const picked = lists
156 .filter(l => l.length >= 2 && l.slice(0, -1).every((m, i) => words(s.slice(m.end, l[i + 1]!.at)) >= 2))
157 .flat()
158 .sort((x, y) => x.at - y.at)
159 let out = ''
160 let from = 0
161 for (const p of picked) {
162 out += s.slice(from, p.at)
163 from = p.end
164 }
165 return out + s.slice(from)
166}
167
168const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
169
170// a stands on its own in text: "31" is in "out/31.mp4", but "2" is not in
171// "120" or "2.5", and "test" is not in "tests". A number only needs other
172// digits kept off it, so "500ms" keeps 500 and "v2" keeps 2.
173export function hasToken(text: string, a: string): boolean {
174 if (!text.includes(a)) return false
175 const edge = (c: string | undefined) => (c === undefined ? '' : /\p{N}/u.test(c) ? 'num' : /[\p{L}\p{M}_]/u.test(c) ? 'word' : '')
176 const guard = { num: ['(?<!\\p{N}|\\p{N}[.,])', '(?!\\p{N}|[.,]\\p{N})'], word: ['(?<![\\p{L}\\p{M}\\p{N}_])', '(?![\\p{L}\\p{M}\\p{N}_])'], '': ['', ''] }
177 const first = edge(a[0])
178 const last = edge(a.at(-1))
179 return new RegExp(guard[first][0] + esc(a) + guard[last][1], 'u').test(text)
180}
181
182// A bare number may change its decimal mark when the rewrite is in
183// English: a decimal comma to a point (2,5 to 2.5), and a thousands point to
184// a comma (10.000 to 10,000; three digits after it, so 3.12 stays a
185// version). Not inside code or quotes, which are kept as written.
186const inSpan = (draft: string, a: string) => [...draft.matchAll(/`[^`\n]+`|"[^"\n]{1,80}"/g)].some(m => hasToken(m[0], a))
187const otherMark = (a: string) => (/^\d+,\d+$/.test(a) ? a.replace(',', '.') : /^\d{1,3}(?:\.\d{3})+$/.test(a) ? a.replaceAll('.', ',') : null)
188
189export const lost = (draft: string, text: string) =>
190 anchors(draft).filter(a => {
191 const alt = inSpan(draft, a) ? null : otherMark(a)
192 return !hasToken(text, a) && !(alt && hasToken(text, alt))
193 })
194
195// The same kinds of thing the rewrite brought in from elsewhere: a path, a
196// hash or a number the user did not type, shown on the band so a stale one
197// is caught before it goes out under their name.
198export const added = (draft: string, text: string) =>
199 anchors(text, 'facts').filter(a => {
200 // The draft's own number with its mark changed (12,5 as 12.5, 10.000 as 10,000).
201 const was = /^\d+\.\d+$/.test(a) ? a.replace('.', ',') : /^\d{1,3}(?:,\d{3})+$/.test(a) ? a.replaceAll(',', '.') : null
202 return !hasToken(draft, a) && !(was && hasToken(draft, was))
203 })
204
205export function addedLine(draft: string, text: string): string | null {
206 const list = added(draft, text)
207 if (list.length === 0) return null
208 const shown = list.slice(0, 5).map(a => (a.length > 40 ? `...${a.slice(-37)}` : a))
209 return `not in your draft: ${shown.join(', ')}${list.length > 5 ? ` and ${list.length - 5} more` : ''}`
210}
211
212function instructions(family: Family, list: readonly Exemplar[], limit: number, opts: RewriteOptions, draft = ''): string {
213 if (isLong(draft)) return tidyInstructions(list, limit, opts)
214 return `Rules:
215${rulesFor(family)}
216${opts.language === 'en' ? `\n${ENGLISH}\n` : ''}${opts.ask ? `\n${ASK}\n` : ''}
217Task shapes, to see what a good prompt of each kind carries. Pick the closest one, or none:
218${shapes()}
219${exemplars(list)}
220If the draft is already clear enough to act on, reply with exactly ${KEEP}.
221Give the rewritten prompt and nothing else, at most ${limit} words.`
222}
223
224// For $.model.fork: the model sees the whole conversation before this, so
225// "the file above" can be resolved without us quoting anything.
226export function forkPrompt(draft: string, family: Family, list: readonly Exemplar[] = [], opts: RewriteOptions = {}): string {
227 return `This message is from the sharpprompt plugin, not the user, and is not a task to carry out. The user has typed the draft below as their next message to you and has not sent it yet. ${isLong(draft) ? 'Tidy it' : 'Rewrite it so it is clear for you to act on in this conversation'}, keeping their intent and voice.
228${factsBlock(opts)}
229<draft>
230${draft}
231</draft>
232
233${instructions(family, list, wordLimit(draft), opts, draft)}`
234}
235
236export type Recent = { role: 'user' | 'assistant'; text: string }
237
238function factsBlock(opts: RewriteOptions): string {
239 return opts.facts ? `\nWhat this session has touched, from its transcript:\n<session_facts>\n${opts.facts}\n</session_facts>\n` : ''
240}
241
242// For $.model.complete when there is nothing to fork yet: no history, so we
243// hand over the last few messages ourselves, cut short.
244export function completePrompt(draft: string, family: Family, recent: readonly Recent[], list: readonly Exemplar[] = [], opts: RewriteOptions = {}): string {
245 const convo = recent
246 .slice(-(opts.window ?? 4))
247 .map(m => `<${m.role}>${clip(m.text, 600)}</${m.role}>`)
248 .join('\n')
249 return `A user of Claude Code has typed the draft below as their next message and has not sent it yet. ${isLong(draft) ? 'Tidy it' : 'Rewrite it so it is clear for Claude to act on'}, keeping their intent and voice.
250${convo ? `\nThe last messages of the conversation, cut short:\n<conversation>\n${convo}\n</conversation>\n` : ''}${factsBlock(opts)}
251<draft>
252${draft}
253</draft>
254
255${instructions(family, list, wordLimit(draft), opts, draft)}`
256}
257
258export type Cleaned = { rewritten: string } | { rejected: 'keep' | 'empty' | 'too-long' | 'same' } | { rejected: 'lost'; lost: string[] }
259
260// What the model sent back, made safe to put in the prompt box: fences and
261// wrapping quotes off, and turned down when it is no rewrite at all.
262// also: text that goes out with the rewrite, such as the sentences the
263// answers to its questions add; an anchor found there is not lost.
264export function clean(reply: string, draft: string, also = ''): Cleaned {
265 let t = reply.trim()
266 t = t.replace(/^```[a-z]*\n([\s\S]*?)\n```$/i, '$1').trim()
267 t = t.replace(/^<draft>\s*([\s\S]*?)\s*<\/draft>$/i, '$1').trim()
268 if (/^["“].*["”]$/s.test(t)) t = t.slice(1, -1).trim()
269 if (t === '') return { rejected: 'empty' }
270 // KEEP in bold or backticks, or with a reason after it, is still KEEP.
271 const head = (t.split('\n')[0] ?? '').replace(/[*_`"'\s]/g, '').replace(/[.!:]$/, '')
272 if (head.toUpperCase() === KEEP) return { rejected: 'keep' }
273 // A little slack so a near miss still reaches the user.
274 if (words(t) > wordLimit(draft) + 15) return { rejected: 'too-long' }
275 if (t === draft.trim()) return { rejected: 'same' }
276 const gone = lost(draft, also ? `${t}\n${also}` : t)
277 if (gone.length) return { rejected: 'lost', lost: gone }
278 return { rewritten: t }
279}
280hooks/bank.ts 171 lines1// Generated by scripts/build-bank.mjs from docs/rules and docs/shapes.
2// Edit those files, not this one.
3
4export type Family = 'common' | 'fable' | 'opus' | 'sonnet' | 'haiku'
5export type Rule = { id: string; text: string }
6export type Shape = { name: string; summary: string; fields: string; context: string; before: string; after: string }
7
8export const RULES: Record<Family, readonly Rule[]> = {
9 "common": [
10 {
11 "id": "keep-intent",
12 "text": "Keep what the user asked for. Do not add tasks, change the goal, or answer the prompt yourself. Resolve references to the conversation (\"the second item above\", \"that file\", \"same as before\") into the concrete names they point to, and invent nothing the conversation does not show: no file names, numbers, deadlines or requirements. Keep the user's own uncertainty (\"I guess\", \"maybe\") where they wrote it, and never add guesses of your own."
13 },
14 {
15 "id": "give-the-reason",
16 "text": "When the conversation or the prompt shows why the user wants this or who it is for, say it in one plain sentence. If the reason is not knowable, leave it out rather than guess."
17 },
18 {
19 "id": "name-the-deliverable",
20 "text": "Make the output explicit: what should exist or be answered when Claude is done, and how the user will tell it is done (tests pass, a file exists, a question answered). Use a check that already exists (the tests, a command) as the done signal; do not add work the user did not ask for, such as new tests. Use a short numbered list only when the order of steps matters."
21 },
22 {
23 "id": "question-stays-a-question",
24 "text": "If the user is asking a question, describing a problem or thinking out loud, the rewrite asks for an assessment and says not to change anything yet. Never turn a question into an order to fix."
25 },
26 {
27 "id": "state-what-is-out",
28 "text": "When the prompt or conversation makes clear what must not be touched, say it in one sentence (files, behaviour, scope). Do not invent restrictions."
29 },
30 {
31 "id": "ideas-mean-ideas",
32 "text": "If the user asks for ideas, options or a plan, the rewrite asks for that and says to wait before building anything."
33 },
34 {
35 "id": "no-reasoning-echo",
36 "text": "Never ask Claude to show, write out or explain its thinking or reasoning, and never add \"think step by step\". Recent models may refuse such requests (the reasoning_extraction category). Asking for a short explanation of the answer is fine."
37 },
38 {
39 "id": "calm-language",
40 "text": "No capital-letter emphasis, no \"CRITICAL\" or \"MUST\", no threats or bribes, no urgency. Current models follow plain instructions and over-apply shouted ones."
41 },
42 {
43 "id": "no-role-filler",
44 "text": "Do not open with a role (\"You are an expert ...\"). The prompt is a user turn inside Claude Code, which already has its system prompt; a role line there only adds length."
45 },
46 {
47 "id": "stay-short",
48 "text": "The rewrite is at most twice the length of the original or 60 words, whichever is more, and never more than 180 words. Write it in the user's language and voice (or in English when the rewriteLanguage setting says en), first person, as if they had typed it carefully. No headings, no XML tags, no preamble."
49 },
50 {
51 "id": "latest-reference",
52 "text": "When a reference in the draft (\"that function\", \"the file\", \"the test\") fits more than one thing in the conversation, take the most recent one and name it, with its file when there is one."
53 }
54 ],
55 "fable": [
56 {
57 "id": "fable-brief-is-enough",
58 "text": "Prefer one short instruction over a list of cases. Fable follows brief instructions well and over-prescriptive prompts can make its output worse."
59 },
60 {
61 "id": "fable-ask-for-updates",
62 "text": "If the task is long and the user wants to follow along, ask for a line before starting and a short recap at the end. Fable 5.1 writes few updates between tool calls unless asked. Do not ask it to keep updates brief."
63 },
64 {
65 "id": "fable-ambiguity",
66 "text": "Where the request can be read two ways and the conversation does not settle it, ask Claude to take the most direct reading and state that assumption, rather than build for both."
67 },
68 {
69 "id": "fable-bug-phrasing",
70 "text": "Turn \"does this compile?\" into \"are there any bugs in this?\". The compile-check phrasing trips safety classifiers more often."
71 }
72 ],
73 "opus": [
74 {
75 "id": "opus-no-verify-step",
76 "text": "Do not add \"verify your work\" or \"add a final verification step\". Opus 5 verifies on its own and extra verification instructions waste tokens."
77 },
78 {
79 "id": "opus-hold-scope",
80 "text": "For a narrow task, say plainly to deliver what was asked at that scope and to mention, not do, anything beyond it. Opus 5 can widen a task on its own."
81 },
82 {
83 "id": "opus-length",
84 "text": "If the user wants a document or reply of a certain size, say so. Opus 5 writes longer replies and documents by default, and effort does not reliably shorten them."
85 }
86 ],
87 "sonnet": [
88 {
89 "id": "sonnet-literal-scope",
90 "text": "Spell out how far an instruction reaches (\"every file under src/, not just this one\"). Sonnet 5 reads prompts literally and does not generalise an instruction from one item to the rest."
91 },
92 {
93 "id": "sonnet-no-extras",
94 "text": "When the user wants only the change itself, say not to add tests, docs or files that were not asked for. Sonnet 5.5 tends to add them."
95 }
96 ],
97 "haiku": [
98 {
99 "id": "haiku-run-a-check",
100 "text": "For a code change that can be run, built or type-checked, ask for a real check (the tests, the type-checker, the build) before calling it done. Haiku 5.5 at low effort sometimes reports a change as done without checking it."
101 }
102 ]
103}
104
105export const SHAPES: readonly Shape[] = [
106 {
107 "name": "fix",
108 "summary": "Something is broken and should work again.",
109 "fields": "what goes wrong and where it shows, what should happen instead, what must stay as it is, how to tell it is fixed.",
110 "context": "the last test run showed test_login_redirect failing after the session refactor in auth/session.py.",
111 "before": "login broken again after your change, fix",
112 "after": "test_login_redirect started failing after the session refactor in auth/session.py. Find out why and fix it so a correct password lands on the dashboard again. Keep the refactor's new structure. Done when test_login_redirect and the rest of the auth tests pass."
113 },
114 {
115 "name": "investigate",
116 "summary": "Find out why something happens, without changing it yet.",
117 "fields": "the observation, where to look, what a useful answer looks like, a clear note that nothing should change yet.",
118 "context": "the user pasted a chart showing nightly job runtime going from 4 to 19 minutes on 2 October.",
119 "before": "why is the nightly thing so slow now",
120 "after": "The nightly job went from about 4 to 19 minutes on 2 October. Find out what changed around then that explains it and tell me the likely cause with the evidence. Don't change any code yet; I want the diagnosis first."
121 },
122 {
123 "name": "build",
124 "summary": "Add something new.",
125 "fields": "what it does for whom, where it lives, inputs and outputs, what is out of scope, how to tell it works.",
126 "context": "the project is a FastAPI service; the user has been discussing exporting reports.",
127 "before": "add csv export for reports",
128 "after": "Add a CSV export for reports so analysts can open them in a spreadsheet: a GET endpoint next to the existing report routes that returns the same rows as the JSON report, one column per field. No new dependencies. Done when the new endpoint returns the same rows as the JSON report for an existing report and the current tests still pass."
129 },
130 {
131 "name": "refactor",
132 "summary": "Change how code is organised without changing what it does.",
133 "fields": "the code in question, the target structure, the reason, the behaviour that must not change, how to check that.",
134 "context": "the conversation showed billing.py at 1,400 lines with tax, invoice and discount logic mixed together.",
135 "before": "split up billing its a mess",
136 "after": "Split billing.py (about 1,400 lines) into separate modules for tax, invoices and discounts, so each can be changed without reading the others. Behaviour must stay exactly the same: no renamed public functions, no logic changes. Done when the existing billing tests pass unchanged."
137 },
138 {
139 "name": "research",
140 "summary": "Learn something from outside the codebase.",
141 "fields": "the question, why it matters here, what sources count, the form of the answer.",
142 "context": "the team is choosing a queue for a Python service and already runs Redis.",
143 "before": "celery vs rq which one",
144 "after": "We need a task queue for our Python service and already run Redis. Compare Celery and RQ for that setup: setup effort, retries and scheduling, monitoring, and how actively each is maintained. Give me a recommendation with the two or three reasons that decide it, and link your sources."
145 },
146 {
147 "name": "review",
148 "summary": "Look over work and report problems.",
149 "fields": "what to review, what kind of problems matter, what to leave alone, the form of the findings.",
150 "context": "the user just finished a branch adding rate limiting to the API gateway.",
151 "before": "review my changes",
152 "after": "Review the rate limiting changes on this branch for bugs: wrong limits, race conditions, requests that slip through, and errors that would reach users. Skip style and naming. List each finding with the file and line and why it is a problem, most serious first. Don't change the code."
153 },
154 {
155 "name": "write",
156 "summary": "Produce prose: docs, a message, a description.",
157 "fields": "who reads it, what they should do or know after, length, tone, what it must include.",
158 "context": "the conversation just merged a migration that renames the users table to accounts.",
159 "before": "write something for the team about the migration",
160 "after": "Write a short Slack message for the backend team about the migration we just merged that renames the users table to accounts. They need to know what breaks in their local setups and the one command to fix it. Five sentences at most, plain tone."
161 },
162 {
163 "name": "ask",
164 "summary": "A question that wants an answer, not a change.",
165 "fields": "the question, the context it is about, how deep the answer should go.",
166 "context": "the conversation has been about a React app using useEffect for data fetching.",
167 "before": "is useeffect fine for this or no",
168 "after": "Is useEffect a reasonable way to fetch the dashboard data in this app, or would a data-fetching library serve better here? Give me a short answer with the main trade-off; don't change anything."
169 }
170]
171types/index.d.ts 67 lines1export type SharppromptMode = 'fill' | 'replace' | 'context' | 'off'
2
3// Why the cheap gate let a prompt through untouched. 'suggested' is a prompt
4// sent while our suggestion was in the box: the user's answer to it.
5export type SharppromptSkip =
6 | 'off'
7 | 'not-typed'
8 | 'raw'
9 | 'command'
10 | 'heading'
11 | 'too-short'
12 | 'too-long'
13 | 'harness-tag'
14 | 'answer'
15 | 'suggested'
16 | 'back-to-mine'
17
18// What the classifier said; 'timeout' and 'error' send the prompt as typed.
19// 'long': past LONG_WORDS, not classified, tidied.
20export type SharppromptVerdict = 'clear' | 'rough' | 'long' | 'timeout' | 'error'
21
22// How a rewrite went. Only 'rewritten' carries text; every other outcome
23// sends the prompt as typed.
24export type SharppromptQuestion = { question: string; header: string; options: { label: string; adds: string }[] }
25
26export type SharppromptRewrite = {
27 outcome: 'rewritten' | 'keep' | 'same' | 'empty' | 'too-long' | 'lost' | 'timeout' | 'aborted' | 'error'
28 via: 'fork' | 'complete'
29 ms: number
30 text?: string
31 detail?: string
32 // Gaps the rewriter wanted to ask about; their answers are added to text.
33 questions?: SharppromptQuestion[]
34 // Characters in the model's reply before cleaning, to set against its output tokens.
35 replyChars?: number
36 usage?: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
37}
38
39export type SharppromptDecision =
40 | { verdict: 'skip'; reason: SharppromptSkip; text: string }
41 | { verdict: SharppromptVerdict; text: string; classifyMs?: number; rewrite?: SharppromptRewrite }
42
43// A rewrite the user has not acted on yet: in the box (filled) or already
44// sent (replaced), shown in the band; or the user's own text put back in the
45// box (restored), which goes out as the person sends it, edited or not.
46export type SharppromptPending = {
47 kind: 'filled' | 'replaced' | 'restored'
48 original: string
49 rewritten: string
50 // The usage-log record of this rewrite, when the log is on.
51 log?: string
52 // The sentences the person's answers added, so the band does not name
53 // their own picks as new.
54 asked?: string
55}
56
57declare module 'claude-code' {
58 interface PluginState {
59 sharpprompt: {
60 pending: SharppromptPending | null
61 isOff: boolean
62 mode: SharppromptMode | null
63 lastDecision: SharppromptDecision | null
64 }
65 }
66}
67