SLOPSHOPPER

session-namer

Suggests session names after each Claude reply (band above the prompt, /rs to force), following a configurable naming convention.

bandcommandtoastmodeltimer
v0.11.0MITupdated 2026-10-12lucaslenglet/session-namer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-namer
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /rs ⎿ session-namer: No suggestion: could not read Haiku's answer. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

session-namer

A Claude Code mod that suggests a name for your session, following your naming convention.

After each Claude reply, Haiku reads the conversation (your messages and Claude's text replies, no tool output) and suggests 3 names in a band above the prompt:

Session name:
[ feat/claude-mods-mod: implement session namer ] [ 1 Apply ]
[ claude-mods-mod: init spec                     ] [ 2 Apply ]
[ bug-42/claude-mods: fix band render            ] [ 3 Apply ]
[ Reroll ] [ Dismiss ] [ Stop ] ≈$0.0003 (2.6k tokens) · session …

Each name is an editable field: change it if you like, then press Enter in it or its Apply button (or 1-3 in the terminal) to rename the session (/rename). Once a name is applied from the band, automatic suggestions stop for the session, as with Stop: /rs still suggests names on demand, /rs start turns them back on. To type in a field, focus the band (a click, or ctrl+x tab); Esc gives the keys back to the prompt. Once a name is picked or dismissed, the band stays hidden until the topic of the conversation actually changes. Reroll asks for 3 different names; Stop turns the suggestions off for the rest of the session. While names are being written, a spinner turns in the band (⠹ generating names…): on a reroll, on /rs, and after a reply when the band is already up or the session has no name yet.

Install

In a Claude Code terminal session:

/plugin install session-namer --marketplace lucaslenglet/session-namer

Answer y to add the marketplace, pick a scope (user scope = every session), then set the options (or keep the defaults). The mod is active right away.

Usage

Band above the promptClick a name, or ctrl+x tab then 1-3; r rerolls, x dismisses, s stops for this session
/rsAsk for suggestions now (different ones if the band is shown); works even when stopped
/rs stop / /rs startTurn automatic suggestions off / back on for this session
/rs helpHow it works, your current settings and a live preview of the format
/rename …A manual rename is remembered too: no suggestion until the topic changes

Settings

In /config, search for session name:

SettingDefault
Session name format{type:L}-{id}/{project:L}-{kind:L}: {desc:L:w2,5}How names are built
Session name rules for Haiku(empty)Free text that overrides the default rules, e.g. description in French; allowed types: feat, fix, chore
Session name project code(empty: derived from the folder name)Fixed value for {project}
Session name cost displayonShow the Haiku cost in the band and in /rs (/rs help always shows the session total)

Format

Text is kept as typed; each {field} is replaced by a value Haiku finds in the conversation. An empty field disappears together with the separator next to it.

FieldMeaningFilled
{type}kind of work item: bug, us, pr, feat…only if stated
{id}its ticket / PR numberonly if stated, never invented
{project}project code (ClaudeMods → claude-mods, my_cool_web_app → my-cool-web-app)always
{kind}kind of project: f (front), b (back), cli, mod, script…only if clear
{desc}what you are doing, e.g. init spec, plan testsalways (required)

With the default format:

bug-1234/claude-mods-f: fix login redirect
claude-mods-cli: plan tests
claude-mods: init spec

Field options

{field:option:option|fallback}, options can be combined:

OptionEffectExample
U L CUPPER, lower, Capitalized{type:U} → BUG
K Skebab-case, snake_case{desc:K} → init-spec
3 2,5 ,5 3,length in characters: exact, min-max, max, min (cut / padded){type:3} → fea
_x after a lengthpad with x on the left{id:4,_0} → 0042
w2,5 w,3 w3number of words{desc:w,3}
[a,b,c]allowed values; anything else counts as empty{type:[bug,us,pr]}
`\text`value used when the field is empty`{kind\gen} → gen`

Haiku is told about lengths and allowed values, so it picks words that fit instead of being cut. Example of another convention:

[{project}] {desc:C:w,5} ({type:U:[FEAT,FIX,CHORE]} #{id:4,_0})
→ [claude-mods] Fix login redirect (FIX #0042)

Cost and privacy

One small Haiku call per Claude reply (low effort, at most ~12,000 characters of conversation: the first message plus the most recent ones), through your own Claude Code session like any other request. Subagent turns and interrupted turns are skipped.

The band, /rs and /rs help show what it costs (turn it off with Session name cost display): the call behind the current suggestions and the session total, which also counts calls that changed nothing on screen:

≈$0.00031 (2.6k tokens) · session ≈$0.0021 (17k tokens, 7 calls)

The dollar figure is an estimate at Claude Haiku 5.5 API rates ($0.10 / $0.50 per million input / output tokens). On a Claude subscription you are not billed per token: the calls count toward your usage limits instead.

Development

claude plugin validate .
claude plugin test .
claude --plugin-dir .   # run Claude Code with this working copy loaded
  • hooks/register.tsx: hooks, the band, the /rs command
  • hooks/naming.ts: project code, template engine, Haiku prompt (pure functions)
  • tests/: claude plugin test

License

MIT

Source 3 files
hooks/register.tsx 342 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as Engine, Register } from 'claude-code'
3
4import type { Baseline, Edits, Spend, Suggestions } from '../types'
5import {
6  addUsage,
7  DEFAULT_TEMPLATE,
8  helpText,
9  names,
10  NO_SPEND,
11  parseVerdict,
12  projectCode,
13  prompt,
14  specs,
15  spendText,
16  SYSTEM,
17  transcript,
18} from './naming'
19import type { Settings } from './naming'
20
21const suggestions = atom({ plugin: 'session-namer', key: 'suggestions' } as const, [] as Suggestions)
22const baseline = atom({ plugin: 'session-namer', key: 'baseline' } as const, null as Baseline)
23const lastCall = atom({ plugin: 'session-namer', key: 'lastCall' } as const, null as Spend | null)
24const total = atom({ plugin: 'session-namer', key: 'total' } as const, NO_SPEND as Spend)
25const isStopped = atom({ plugin: 'session-namer', key: 'isStopped' } as const, false)
26const isGenerating = atom({ plugin: 'session-namer', key: 'isGenerating' } as const, false)
27const frame = atom({ plugin: 'session-namer', key: 'frame' } as const, 0)
28const edits = atom({ plugin: 'session-namer', key: 'edits' } as const, {} as Edits)
29
30const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
31
32const sameList = (a: readonly string[], b: readonly string[]) =>
33  a.length === b.length && a.every((x, i) => x === b[i])
34
35// Mod options (/config); a change reloads the module, so register reads them again.
36let settings: Settings = { template: DEFAULT_TEMPLATE, rules: '' }
37let forcedProject = ''
38let isCostShown = true
39let rejectedTemplate: string | undefined
40
41const text = (v: unknown) => (typeof v === 'string' ? v.trim() : '')
42
43// One request to Haiku at a time, automatic or not: each job waits for the previous one.
44let queue: Promise<unknown> = Promise.resolve()
45const enqueue = <T,>(job: () => Promise<T>): Promise<T> => {
46  const run = queue.then(job, job)
47  queue = run.catch(() => undefined)
48  return run
49}
50// An automatic request already waiting in the queue: another one adds nothing.
51let isAutoQueued = false
52
53const APPLIED_HINT = 'No more automatic suggestions in this session: /rs suggests new names, /rs start turns them back on.'
54const STOPPED_HINT = 'Automatic suggestions are stopped for this session; /rs start turns them back on.'
55
56/** Replaces the names shown; new names drop the edits made to the previous ones. */
57async function show($: Engine, next: Suggestions) {
58  if (sameList(await read($, suggestions), next)) return
59  await update($, suggestions, () => next)
60  await update($, edits, () => ({}))
61}
62
63/**
64 * Asks Haiku for 3 names. Without `force`, shows them only if the subject has
65 * changed compared to the baseline name. `avoid` lists names already shown,
66 * so Haiku proposes different ones. Returns the names shown, or the reason
67 * for the failure.
68 */
69async function suggest($: Engine, force: boolean, avoid: readonly string[] = []): Promise<string[] | string> {
70  const messages = await $.session.messages()
71  if (!Array.isArray(messages)) return 'could not read the conversation'
72  const convo = transcript(messages)
73  if (convo === '') return 'the conversation is empty'
74
75  const project = forcedProject || projectCode(await $.session.cwd())
76  const current = await read($, baseline)
77  const r = await $.model.complete({
78    model: 'haiku',
79    system: SYSTEM,
80    prompt: prompt(convo, project, current, settings, avoid),
81    effort: 'low',
82    maxTokens: 400,
83    timeoutMs: 20000,
84  })
85  // Every call counts, even a failed one or one that shows no suggestion.
86  await update($, total, prev => addUsage(prev ?? NO_SPEND, r.usage))
87  if (!r.isAnswered) return `Haiku did not answer (${r.reason})`
88
89  const verdict = parseVerdict(r.text)
90  if (verdict === undefined) return "could not read Haiku's answer"
91  // Stop pressed while this automatic call was on its way: show nothing.
92  if (!force && ((current !== null && verdict.isSameSubject) || (await read($, isStopped)))) return []
93
94  const next = names(settings.template, project, verdict)
95  await show($, next)
96  await update($, lastCall, () => addUsage(NO_SPEND, r.usage))
97  return next
98}
99
100/** Runs `job` with the band's spinner turning. */
101async function spinning<T>($: Engine, job: () => Promise<T>): Promise<T> {
102  await update($, frame, () => 0)
103  await update($, isGenerating, () => true)
104  const tick = $.clock.every(100, () => {
105    void update($, frame, f => f + 1)
106  })
107  try {
108    return await job()
109  } finally {
110    tick.cancel()
111    await update($, isGenerating, () => false)
112  }
113}
114
115/** Asks for 3 names different from those shown (Reroll button, /rs). */
116function reroll($: Engine): Promise<string[] | string> {
117  return enqueue(() => spinning($, async () => suggest($, true, await read($, suggestions))))
118}
119
120/**
121 * An automatic call is shown as generating only when its names will likely be
122 * shown: the band is already up, or the session has no name yet. Otherwise
123 * (same subject, the usual case) the band would flash after every reply.
124 */
125async function auto($: Engine): Promise<string[] | string> {
126  // Stopped: no Haiku call at all.
127  if (await read($, isStopped)) return []
128  const isAwaited = (await read($, suggestions)).length > 0 || (await read($, baseline)) === null
129  return isAwaited ? spinning($, () => suggest($, false)) : suggest($, false)
130}
131
132/** Turns automatic suggestions off (hiding the band) or back on for this session. */
133async function setStopped($: Engine, stopped: boolean) {
134  await update($, isStopped, () => stopped)
135  if (stopped) await show($, [])
136}
137
138/** Runs a suggestion outside the turn, without delaying it. */
139function schedule($: Engine) {
140  if (isAutoQueued) return
141  isAutoQueued = true
142  $.clock.after(0, () => {
143    enqueue(() => {
144      isAutoQueued = false
145      return auto($)
146    }).catch(() => {
147      // A failed suggestion must never get in the way of the session.
148    })
149  })
150}
151
152export const register: Register = (on, options) => {
153  const template = text(options.template)
154  // A template without {desc} would give meaningless names: keep the default.
155  const isUsable = specs(template).some(s => s.field === 'desc')
156  rejectedTemplate = isUsable || template === '' ? undefined : template
157  settings = { template: isUsable ? template : DEFAULT_TEMPLATE, rules: text(options.rules) }
158  forcedProject = text(options.project)
159  isCostShown = options.showCost !== false
160
161  on('session.start', async ($, e, next) => {
162    await $.command.register({
163      name: 'rs',
164      description: 'Rename suggest: Haiku suggests 3 session names now (/rs stop|start: automatic suggestions off/on; /rs help)',
165      argumentHint: '[help|stop|start]',
166    })
167    return next(e)
168  })
169
170  // Resumed session that already has a name: that name becomes the baseline.
171  on('classic.SessionStart', async ($, e, next) => {
172    const title = e.session_title?.trim()
173    if (title) await update($, baseline, prev => prev ?? title)
174    return next(e)
175  }).catch(($, e, next) => next(e))
176
177  on('turn.complete', ($, e, next) => {
178    if (e.agentId === undefined && e.reason === 'answer') schedule($)
179    return next(e)
180  })
181
182  on('command.run', { command: 'rs' }, async ($, e) => {
183    const arg = e.args.trim()
184    if (arg === 'stop') {
185      await setStopped($, true)
186      return { text: `Session names: ${STOPPED_HINT}` }
187    }
188    if (arg === 'start') {
189      await setStopped($, false)
190      return { text: 'Session names: automatic suggestions back on for this session.' }
191    }
192    if (arg === 'help') {
193      const project = forcedProject || projectCode(await $.session.cwd())
194      const [spent, stopped] = await Promise.all([read($, total), read($, isStopped)])
195      return {
196        text: helpText({
197          ...settings,
198          project,
199          isProjectForced: forcedProject !== '',
200          rejectedTemplate,
201          total: spent,
202          isCostShown,
203          isStopped: stopped,
204        }),
205      }
206    }
207    // With the band shown, /rs asks for different names (like Reroll).
208    const shown = await reroll($)
209    if (typeof shown === 'string') return { text: `No suggestion: ${shown}.` }
210    const [stopped, call, spent] = await Promise.all([read($, isStopped), read($, lastCall), read($, total)])
211    return {
212      text: [
213        'Suggestions in the band above the prompt:',
214        ...shown.map((n, i) => `${i + 1}. ${n}`),
215        ...(isCostShown ? [`Cost: ${call ? spendText(call) : '?'} · this session: ${spendText(spent, true)}`] : []),
216        ...(stopped ? [STOPPED_HINT] : []),
217      ].join('\n'),
218    }
219  })
220
221  // Any /rename (yours or the band's) becomes the new baseline.
222  on('command.run', { command: 'rename' }, async ($, e, next) => {
223    const result = await next(e)
224    const title = e.args.trim()
225    if (title) {
226      await update($, baseline, () => title)
227      await show($, [])
228    }
229    return result
230  }).catch(($, e, next) => next(e))
231
232  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
233    const shown = await read($, suggestions)
234    const generating = await read($, isGenerating)
235    if (e.props.hasSurvey || (shown.length === 0 && !generating)) return next(e)
236    const spin = generating ? `${SPINNER[(await read($, frame)) % SPINNER.length]} generating names…` : ''
237
238    const elements = $.ui.resolve(e)
239    const { Box, Button, Text } = elements
240    const Input = 'Input' in elements ? elements.Input : undefined
241    // Only the terminal hides a field's own submit button while it is not focused.
242    const hasApplyButton = !Input || e.surface === 'terminal'
243    if (shown.length === 0) {
244      return (
245        <Box flexDirection="row" gap={1}>
246          <Text dimColor>Session name:</Text>
247          <Text color="claude">
248            {spin}
249          </Text>
250        </Box>
251      )
252    }
253    const call = await read($, lastCall)
254    const spent = await read($, total)
255    const typed = await read($, edits)
256    const valueAt = (i: number) => typed[i] ?? shown[i] ?? ''
257
258    const choose = async (typed: string) => {
259      const name = typed.trim()
260      if (!name) {
261        $.ui.toast('Type a name before applying it.')
262        return
263      }
264      try {
265        const result = await $.command.run({ command: 'rename', args: name })
266        $.ui.toast(`${result.text?.trim() || `Session renamed to: ${name}`}. ${APPLIED_HINT}`)
267      } catch {
268        $.ui.toast(`Could not rename, type: /rename ${name}`)
269      }
270      await update($, baseline, () => name)
271      // A name applied from the band ends automatic suggestions, as Stop does.
272      await setStopped($, true)
273    }
274
275    const dismiss = async () => {
276      // The current subject becomes the baseline: suggestions only come back if it changes.
277      await update($, baseline, () => shown[0])
278      await show($, [])
279    }
280
281    const onReroll = async () => {
282      try {
283        const result = await reroll($)
284        if (typeof result === 'string') $.ui.toast(`No new names: ${result}.`)
285      } catch {
286        $.ui.toast('No new names: Haiku could not be reached.')
287      }
288    }
289
290    const onStop = async () => {
291      await setStopped($, true)
292      $.ui.toast(STOPPED_HINT)
293    }
294
295    return (
296      <Box flexDirection="column">
297        <Text dimColor>Session name:</Text>
298        {shown.map((_, i) => (
299          <Box key={`row-${i}`} flexDirection="row" gap={1}>
300            {Input && (
301              <Box flexGrow={1}>
302                <Input
303                  key={`name-${i}`}
304                  value={valueAt(i)}
305                  submitLabel={hasApplyButton ? 'apply' : 'Apply'}
306                  onInput={(value: string) => update($, edits, prev => ({ ...prev, [i]: value }))}
307                  onSubmit={(value: string) => choose(value)}
308                />
309              </Box>
310            )}
311            {hasApplyButton && (
312              <Button
313                key={`pick-${i}`}
314                label={Input ? 'Apply' : valueAt(i)}
315                hotkey={String(i + 1)}
316                variant={i === 0 ? 'primary' : 'secondary'}
317                onPress={() => choose(valueAt(i))}
318              />
319            )}
320          </Box>
321        ))}
322        <Box flexDirection="row" flexWrap="wrap" gap={1}>
323          {generating ? (
324            <Text color="claude">
325              {spin}
326            </Text>
327          ) : (
328            <Button key="reroll" label="Reroll" hotkey="r" onPress={onReroll} />
329          )}
330          <Button key="dismiss" label="Dismiss" hotkey="x" role="dismiss" onPress={dismiss} />
331          <Button key="stop" label="Stop" hotkey="s" onPress={onStop} />
332          {isCostShown && (
333            <Text key="cost" dimColor>
334              {call ? `${spendText(call)} · ` : ''}session {spendText(spent, true)}
335            </Text>
336          )}
337        </Box>
338      </Box>
339    )
340  })
341}
342
hooks/naming.ts 398 lines
1// Pure logic (no `$`): project code, name format, Haiku prompt and parsing.
2
3export type Parts = {
4  type?: string // bug, us, pr, feat, ...
5  id?: string // 1234, ABC-12, ...
6  kind?: string // f, b, cli, mod, script, ...
7  desc: string // 2 to 5 words
8}
9
10export type Verdict = {
11  isSameSubject: boolean
12  suggestions: Parts[]
13}
14
15/** Project code: the folder name in kebab-case, ClaudeMods → claude-mods. */
16export function projectCode(cwd: string): string {
17  const base = cwd.replace(/[\\/]+$/, '').split(/[\\/]/).pop() ?? ''
18  const words = base
19    .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
20    .split(/[^A-Za-z0-9]+/)
21    .filter(Boolean)
22    .map(w => w.toLowerCase())
23
24  return words.join('-') || 'project'
25}
26
27export const DEFAULT_TEMPLATE = '{type:L}-{id}/{project:L}-{kind:L}: {desc:L:w2,5}'
28
29export const FIELDS = ['type', 'id', 'project', 'kind', 'desc'] as const
30export type Field = (typeof FIELDS)[number]
31
32/**
33 * A template field: `{name:mod:mod|fallback}`.
34 *   U / L / C           UPPERCASE, lowercase, Capitalized
35 *   K / S               words joined by - (kebab) or _ (snake)
36 *   3  2,5  ,5  3,      length in characters: exact, min-max, max, min
37 *   …_0                 padding character, on the left (4,_0: 42 → 0042)
38 *   w2,5  w,5  w3       number of words (same syntax, no padding)
39 *   [bug,us,pr]         allowed values; any other value counts as empty
40 *   |gen                value used when the field is empty (otherwise it disappears)
41 */
42export type Spec = {
43  field: Field
44  cases: ('U' | 'L' | 'C' | 'K' | 'S')[]
45  chars?: { min?: number; max?: number; pad?: string }
46  words?: { min?: number; max?: number }
47  allowed?: string[]
48  fallback?: string
49}
50
51const FIELD = /\{([a-z]+)((?::[^:{}|]*)*)(?:\|([^{}]*))?\}/g
52const RANGE = /^(\d*)(,?)(\d*)(?:_(.))?$/
53
54function range(text: string): { min?: number; max?: number; pad?: string } | undefined {
55  const m = RANGE.exec(text)
56  if (!m || (m[1] === '' && m[3] === '')) return undefined
57  const [, a = '', comma, b = '', pad] = m
58  const min = a === '' ? undefined : Number(a)
59  const max = comma ? (b === '' ? undefined : Number(b)) : min
60  return { min, max, pad }
61}
62
63export function parseSpec(name: string, mods: string, fallback: string | undefined): Spec | undefined {
64  if (!(FIELDS as readonly string[]).includes(name)) return undefined
65  const spec: Spec = { field: name as Field, cases: [], fallback: fallback?.trim() || undefined }
66  for (const mod of mods.split(':').map(m => m.trim()).filter(Boolean)) {
67    if (/^[ULCKS]$/.test(mod)) spec.cases.push(mod as Spec['cases'][number])
68    else if (mod.startsWith('[') && mod.endsWith(']'))
69      spec.allowed = mod.slice(1, -1).split(',').map(v => v.trim()).filter(Boolean)
70    else if (mod.startsWith('w')) spec.words = range(mod.slice(1))
71    else spec.chars = range(mod)
72    // An unknown modifier is ignored: the name stays readable rather than broken.
73  }
74  return spec
75}
76
77/** The template's fields, in order (the same field may appear twice). */
78export function specs(template: string): Spec[] {
79  return [...template.matchAll(FIELD)].flatMap(m => parseSpec(m[1] ?? '', m[2] ?? '', m[3]) ?? [])
80}
81
82// Keeps letters (accents included), digits and a few characters useful in ids.
83const clean = (s: string | undefined) =>
84  (s ?? '').replace(/[^\p{L}\p{N}#.\- ]+/gu, '').replace(/\s+/g, ' ').trim()
85
86// Space padding must survive the final whitespace cleanup.
87const PAD_SPACE = '\u0000'
88
89export function applySpec(spec: Spec, raw: string): string {
90  let v = raw
91  if (spec.allowed && !spec.allowed.some(a => a.toLowerCase() === v.toLowerCase())) v = ''
92  else if (spec.allowed) v = spec.allowed.find(a => a.toLowerCase() === v.toLowerCase()) ?? v
93  if (v === '') v = spec.fallback ?? ''
94  if (v === '') return ''
95
96  if (spec.words?.max !== undefined) v = v.split(' ').slice(0, spec.words.max).join(' ')
97  for (const c of spec.cases) {
98    if (c === 'U') v = v.toUpperCase()
99    if (c === 'L') v = v.toLowerCase()
100    if (c === 'C') v = v.charAt(0).toUpperCase() + v.slice(1)
101    if (c === 'K') v = v.replace(/ /g, '-')
102    if (c === 'S') v = v.replace(/ /g, '_')
103  }
104  const chars = spec.chars
105  if (chars?.max !== undefined) v = [...v].slice(0, chars.max).join('').trimEnd()
106  if (chars?.min !== undefined && [...v].length < chars.min) {
107    const fill = (chars.pad ?? PAD_SPACE).repeat(chars.min - [...v].length)
108    v = chars.pad === undefined ? v + fill : fill + v
109  }
110  return v
111}
112
113const OPENERS = /[([{<]/
114
115/**
116 * Fills the template. An empty field disappears together with a neighbouring
117 * separator: the one before it if it follows a filled field and does not open a
118 * parenthesis/bracket, otherwise the one after it. Empty pairs and orphan
119 * openers are then removed.
120 *   {type:L}-{id}/{project}-{kind}: {desc}  →  bug-1234/claude-mods-mod: init spec
121 *                                           →  claude-mods: init spec
122 */
123export function formatName(template: string, project: string, p: Parts): string {
124  const values: Record<Field, string> = {
125    type: clean(p.type).replace(/ /g, ''),
126    id: clean(p.id).replace(/ /g, ''),
127    project,
128    kind: clean(p.kind).replace(/ /g, ''),
129    desc: clean(p.desc).split(' ').slice(0, 12).join(' '),
130  }
131
132  const out: { text: string; isField: boolean }[] = []
133  let skipNext = false
134  const literal = (text: string) => {
135    if (text === '') return
136    if (skipNext) skipNext = false
137    else out.push({ text, isField: false })
138  }
139
140  let at = 0
141  for (const m of template.matchAll(FIELD)) {
142    literal(template.slice(at, m.index))
143    at = m.index + m[0].length
144    const spec = parseSpec(m[1] ?? '', m[2] ?? '', m[3])
145    if (spec === undefined) {
146      literal(m[0])
147      continue
148    }
149    const value = applySpec(spec, values[spec.field])
150    if (value !== '') {
151      out.push({ text: value, isField: true })
152      skipNext = false
153      continue
154    }
155    const prev = out.at(-1)
156    const hasFieldBefore = out.some(t => t.isField)
157    if (prev && !prev.isField && hasFieldBefore && !OPENERS.test(prev.text)) out.pop()
158    else skipNext = true
159  }
160  literal(template.slice(at))
161
162  let name = out.map(t => t.text).join('')
163  for (let i = 0; i < 3; i++) name = name.replace(/\s*(\(\s*\)|\[\s*\]|\{\s*\}|<\s*>)/g, '')
164  return name
165    .replace(/\s*[([{<]\s*$/, '')
166    .replace(/\s+/g, ' ')
167    .replace(/^[\s\-/:#|_.]+|[\s\-/:#|_.]+$/g, '')
168    .replaceAll(PAD_SPACE, ' ')
169}
170
171const between = (r: { min?: number; max?: number }, unit: string) =>
172  r.min !== undefined && r.min === r.max
173    ? `exactly ${r.min} ${unit}`
174    : [r.min !== undefined && `at least ${r.min} ${unit}`, r.max !== undefined && `at most ${r.max} ${unit}`]
175        .filter(Boolean)
176        .join(' and ')
177
178/** The template's constraints, told to Haiku so it respects them without being truncated. */
179export function constraints(template: string): string {
180  const lines = specs(template)
181    .filter(s => s.field !== 'project')
182    .map(s => {
183      const parts = [
184        s.allowed && `pick one of: ${s.allowed.join(', ')} (otherwise leave empty)`,
185        s.words && between(s.words, 'words'),
186        s.chars && s.chars.max !== undefined && `at most ${s.chars.max} characters`,
187      ].filter(Boolean)
188      return parts.length ? `- ${s.field}: ${parts.join('; ')}` : ''
189    })
190    .filter(Boolean)
191  return [...new Set(lines)].join('\n')
192}
193
194export const SYSTEM = `You name a developer's work sessions.
195You provide fields; the program assembles them according to the FORMAT given in the request and adds the project code itself.
196- type (optional): nature of the item being worked on, one short lowercase word (bug, us, pr, feat, task, doc...). ONLY if it is explicit in the conversation.
197- id (optional): identifier of that item (ticket number, PR number...). ONLY if it appears verbatim in the conversation. Never invent an id.
198- kind (optional): kind of project, short (f = front, b = back, cli, mod, script, lib, api, infra...). Only if it is clear.
199- desc (required): 2 to 5 words in English, lowercase, action verb first, what is being DONE (e.g. "init spec", "update spec", "plan tests", "implement back", "fix login redirect").
200When in doubt, leave an optional field empty rather than guessing.
201The FIELD CONSTRAINTS in the request take precedence over everything else (allowed values, number of words, length).
202If the request lists ALREADY PROPOSED names, the user rejected them: give 3 new variants that differ from them in wording (same fields rules).
203If the request contains USER INSTRUCTIONS, they take precedence over the rules above (language, vocabulary, length...), but never over the response format below.
204
205Reply ONLY with a JSON object, with no text around it:
206{"sameSubject": true|false, "suggestions": [{"type": "", "id": "", "kind": "", "desc": ""}, ...]}
207- suggestions: exactly 3 distinct variants, best first.
208- sameSubject: true if the conversation is still about the same work as the CURRENT NAME provided (a neighbouring step of the same work counts as the same subject only if the description would still be accurate); false if it has changed or if there is no current name.`
209
210/** Keeps the first message and the end of the conversation, within a character budget. */
211export function transcript(
212  messages: readonly { role: 'user' | 'assistant'; text: string }[],
213  budget = 12000,
214  perMessage = 800,
215): string {
216  const lines = messages
217    .filter(m => m.text.trim() !== '')
218    .map(m => {
219      const text = m.text.trim()
220      const cut = text.length > perMessage ? text.slice(0, perMessage) + ' […]' : text
221      return `${m.role === 'user' ? 'USER' : 'CLAUDE'}: ${cut}`
222    })
223  const [first, ...rest] = lines
224  if (first === undefined) return ''
225
226  const tail: string[] = []
227  let size = first.length
228  for (const line of [...rest].reverse()) {
229    if (size + line.length > budget) break
230    size += line.length
231    tail.unshift(line)
232  }
233  const skipped = rest.length - tail.length
234  return [first, ...(skipped > 0 ? [`[… ${skipped} messages omitted …]`] : []), ...tail].join('\n\n')
235}
236
237export type Settings = { template: string; rules: string }
238
239export function prompt(
240  convo: string,
241  project: string,
242  baseline: string | null,
243  settings: Settings,
244  avoid: readonly string[] = [],
245): string {
246  const rules = settings.rules.trim()
247  const limits = constraints(settings.template)
248  return `FORMAT: ${settings.template}
249${limits ? `FIELD CONSTRAINTS (take precedence):\n${limits}\n` : ''}Project code (already set): ${project}
250CURRENT NAME: ${baseline ?? '(none)'}
251${avoid.length > 0 ? `ALREADY PROPOSED (give different ones):\n${avoid.map(n => `- ${n}`).join('\n')}\n` : ''}${rules ? `\nUSER INSTRUCTIONS:\n${rules}\n` : ''}
252<conversation>
253${convo}
254</conversation>`
255}
256
257/** Reads Haiku's JSON reply; undefined if it is unusable. */
258export function parseVerdict(text: string): Verdict | undefined {
259  const start = text.indexOf('{')
260  const end = text.lastIndexOf('}')
261  if (start < 0 || end <= start) return undefined
262  try {
263    const raw = JSON.parse(text.slice(start, end + 1)) as {
264      sameSubject?: unknown
265      suggestions?: unknown
266    }
267    const suggestions = (Array.isArray(raw.suggestions) ? raw.suggestions : [])
268      .filter((s): s is Record<string, unknown> => typeof s === 'object' && s !== null)
269      .map(s => ({
270        type: typeof s.type === 'string' ? s.type : undefined,
271        id: typeof s.id === 'string' ? s.id : undefined,
272        kind: typeof s.kind === 'string' ? s.kind : undefined,
273        desc: typeof s.desc === 'string' ? s.desc : '',
274      }))
275      .filter(s => clean(s.desc) !== '')
276    if (suggestions.length === 0) return undefined
277    return { isSameSubject: raw.sameSubject === true, suggestions }
278  } catch {
279    return undefined
280  }
281}
282
283/** Formatted names, without duplicates, at most 3. */
284export function names(template: string, project: string, v: Verdict): string[] {
285  return [...new Set(v.suggestions.map(p => formatName(template, project, p)))].slice(0, 3)
286}
287
288const SAMPLES: { label: string; parts: Parts }[] = [
289  { label: 'everything found', parts: { type: 'bug', id: '1234', kind: 'f', desc: 'fix login redirect' } },
290  { label: 'no ticket', parts: { kind: 'cli', desc: 'plan tests' } },
291  { label: 'description only', parts: { desc: 'init spec' } },
292]
293
294export type HelpInput = {
295  template: string
296  rules: string
297  project: string
298  isProjectForced: boolean
299  /** The template that was entered, when it was rejected (no {desc}). */
300  rejectedTemplate?: string
301  total?: typeof NO_SPEND
302  isCostShown?: boolean
303  isStopped?: boolean
304}
305
306/** The /rs help manual, with a preview using the current settings. */
307export function helpText(h: HelpInput): string {
308  const preview = SAMPLES.map(s => `  ${s.label.padEnd(18)} → ${formatName(h.template, h.project, s.parts)}`)
309  return [
310    'After each Claude reply, Haiku reads the conversation and suggests 3 session names',
311    'in a band above the prompt. Click one (or ctrl+x tab, then 1-3) to rename; r rerolls',
312    '(3 different names), x dismisses, s stops the suggestions for this session.',
313    "Once named, it stays quiet until the topic changes. /rs asks for suggestions right now",
314    '(different ones if the band is shown). /rs stop and /rs start turn the automatic',
315    `suggestions off and on for this session (now: ${h.isStopped === true ? 'stopped' : 'on'}).`,
316    '',
317    'SETTINGS  (/config, search "session name")',
318    `  Session name format          ${h.template}`,
319    ...(h.rejectedTemplate !== undefined
320      ? [`    ⚠ "${h.rejectedTemplate}" has no {desc} field, so the default format is used.`]
321      : []),
322    `  Session name rules for Haiku ${h.rules || '(none: default rules)'}`,
323    `  Session name project code    ${h.isProjectForced ? h.project : `(automatic: ${h.project}, from the folder name)`}`,
324    `  Session name cost display    ${h.isCostShown === false ? 'off' : 'on'}`,
325    '',
326    'PREVIEW  (current settings, sample values)',
327    ...preview,
328    '',
329    'FORMAT  Text is kept as typed; {field} is replaced by a value Haiku finds in the conversation.',
330    '  {type}     kind of work item: bug, us, pr, feat...   (only if stated)',
331    '  {id}       its ticket / PR number                    (only if stated, never invented)',
332    '  {project}  project code                              (always filled)',
333    '  {kind}     kind of project: f, b, cli, mod, script... (only if clear)',
334    '  {desc}     what you are doing, e.g. "init spec"      (always filled, required)',
335    '  An empty field disappears together with the separator next to it.',
336    '',
337    'FIELD OPTIONS  {field:option:option|fallback}, combinable',
338    '  U  L  C        UPPER, lower, Capitalized          {type:U}     → BUG',
339    '  K  S           kebab-case, snake_case             {desc:K}     → init-spec',
340    '  3  2,5  ,5  3, length in characters: exact,       {type:3}     → fea',
341    '                 min-max, max, min (cut / padded)',
342    '  _x after a length: pad with x on the left         {id:4,_0}    → 0042',
343    '  w2,5  w,3      number of words                    {desc:w,3}',
344    '  [a,b,c]        allowed values, anything else = empty  {type:[bug,us,pr]}',
345    '  |text          value used when the field is empty {kind|gen}   → gen',
346    'Haiku is told about the limits and allowed values, so it picks words that fit.',
347    '',
348    'RULES FOR HAIKU  free text, overrides the default rules, e.g.',
349    '  "description in French; allowed types: feat, fix, chore; never use {kind}"',
350    '',
351    'COST  one Haiku call per Claude reply, low effort, ≤ ~12,000 characters of conversation.',
352    '  Estimated at Claude Haiku 5.5 API rates ($0.10 / $0.50 per million input / output tokens);',
353    '  on a Claude subscription it counts toward your usage limits instead.',
354    `  This session: ${h.total ? spendText(h.total, true) : 'no call yet'}`,
355    `  Shown in the band and /rs: ${h.isCostShown === false ? 'no' : 'yes'} (Session name cost display)`,
356  ].join('\n')
357}
358
359// Claude Haiku 5.5 API prices in $ per million tokens (prompts ≤ 100K tokens).
360// Cache: reads cost 0.1× and writes 1.25× the input price (the mod marks nothing for caching).
361const PRICE = { input: 0.1, output: 0.5, cacheRead: 0.01, cacheWrite: 0.125 }
362
363export type Usage = {
364  input_tokens: number
365  output_tokens: number
366  cache_read_input_tokens: number
367  cache_creation_input_tokens: number
368}
369
370export const NO_SPEND = { calls: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
371
372export function addUsage<S extends typeof NO_SPEND>(s: S, u: Usage): typeof NO_SPEND {
373  return {
374    calls: s.calls + 1,
375    input: s.input + u.input_tokens,
376    output: s.output + u.output_tokens,
377    cacheRead: s.cacheRead + u.cache_read_input_tokens,
378    cacheWrite: s.cacheWrite + u.cache_creation_input_tokens,
379  }
380}
381
382export function dollars(s: typeof NO_SPEND): number {
383  return (
384    (s.input * PRICE.input + s.output * PRICE.output + s.cacheRead * PRICE.cacheRead + s.cacheWrite * PRICE.cacheWrite) /
385    1e6
386  )
387}
388
389const tokens = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n))
390const usd = (x: number) => (x === 0 ? '$0' : x < 0.0001 ? '<$0.0001' : `$${Number(x.toPrecision(2))}`)
391
392/** "≈$0.00037 (2.1k tokens)", plus ", 7 calls" for a total. */
393export function spendText(s: typeof NO_SPEND, isTotal = false): string {
394  const all = s.input + s.output + s.cacheRead + s.cacheWrite
395  const calls = isTotal ? `, ${s.calls} call${s.calls === 1 ? '' : 's'}` : ''
396  return `≈${usd(dollars(s))} (${tokens(all)} tokens${calls})`
397}
398
types/index.d.ts 33 lines
1/** Names proposed by Haiku, shown in the band; empty = band hidden. */
2export type Suggestions = string[]
3
4/** Text typed over a suggestion, by its index in the band. */
5export type Edits = Record<string, string>
6
7/** Baseline name (picked or dismissed): suggestions come back only if the subject diverges from it. */
8export type Baseline = string | null
9
10/** Tokens consumed by one or more Haiku calls. */
11export type Spend = { calls: number; input: number; output: number; cacheRead: number; cacheWrite: number }
12
13declare module 'claude-code' {
14  interface PluginState {
15    'session-namer': {
16      suggestions: Suggestions
17      baseline: Baseline
18      /** The call that produced the suggestions shown. */
19      lastCall: Spend | null
20      /** All calls of the session, including those that showed nothing. */
21      total: Spend
22      /** Automatic suggestions turned off for this session (Stop, /rs stop). */
23      isStopped: boolean
24      /** Haiku is writing names the band waits for: the band shows a spinner. */
25      isGenerating: boolean
26      /** The spinner's current frame, advanced by a timer while generating. */
27      frame: number
28      /** The suggestions as edited in the band, applied instead of the originals. */
29      edits: Edits
30    }
31  }
32}
33