Brewmod placeholders -- expands ++m, ++a, ++r, ++rr and +++ style placeholders into prompt context, with live highlighting and user-defined placeholders…

<!-- Stable deep link, shared outside the repo: #demo. Keep the id. --> <a id="demo"></a><img src="../assets/brewmods/placeholders-bottle.gif" width="260" alt="ASCII glass fermenter, bubbling; the tape label reads ++r · batch 01"> <img src="../assets/brewmods/placeholders.gif" width="800" alt="Claude Code: ++ opens the placeholder list and ++r goes in; the band shows the exact text Claude receives; the ++r review finds three DB bugs; /placeholders global add ++db saves a new placeholder after one question; in plan mode ++db shapes the plan, and ++db ++m together add the manager task graph (teal plan part)."><br><sub>Pick <code>++r</code>, read the band, send: the review finds DB bugs. Add <code>++db</code> in one line, then use it with <code>++m</code> in plan mode. Real Claude Code 2.1.301 screens, sped up where the title bar shows ⏩.</sub> <h1 align="center">Prompt placeholders</h1> <a href="https://github.com/kochetkov-ma/claude-brewcode/stargazers"><img src="https://badgen.net/github/stars/kochetkov-ma/claude-brewcode?icon=github&label=stars" alt="GitHub stars"></a> <img src="https://img.shields.io/badge/Claude_Code-2.1.301%2B-d97706" alt="Requires Claude Code 2.1.301+"> <img src="https://img.shields.io/badge/type-mod-8b5cf6" alt="Claude Code mod"> <img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT">
[!NOTE] Looking for ++m, ++r or +++? The codewords
++m,++a,++r,++rrand+++come with this mod. Install it once and they work in every prompt, next to placeholders you write yourself: see Install, the Quick start and the docs page.
❗ Update Claude Code first: the mods need Claude Code 2.1.301 or newer. Check with
claude --version; if it is lower, runclaude update, then restart Claude Code (exit, runclaude).
claude plugin marketplace add https://github.com/kochetkov-ma/claude-brewcode && claude plugin install brewmod-placeholders@claude-brewcode
Then run /reload-plugins. Works on Team organizations.
Update: run claude update and restart Claude Code, then claude plugin marketplace update claude-brewcode && claude plugin update brewmod-placeholders@claude-brewcode, then /reload-plugins. With brewtools installed, /brewtools:plugin-update does the same for every plugin and mod. Dev mode, no install: claude --plugin-dir ./brewmod-placeholders. Needs Claude Code 2.1.301 or newer and node on the PATH (the bundled command hook runs as plain Node). Mods use the hooks module API, which is early access.
| Want | Do |
|---|---|
| Add a block | ++r check the diff, then Enter. The block is sent as hidden context; your prompt stays as typed |
| Read a token's text while typing | Put the caret on it (arrows, Home, End). The band shows up to 15 rows of its text, cut row and plan note included; move the caret off to return to the compact band (details) |
| Print the whole text | /placeholders show ++r, or ++r? alone and Enter twice (how). /placeholders list prints all. Full help: /placeholders help, or /placeholders plus a question in your own words |
| Make your own | /placeholders add ++ship: …. With no scope word the one dialog also asks Where (Global recommended, or Project); start with global or project to skip that question |
you type ++r check the diff
Claude reads ++r check the diff <- your prompt, unchanged
+ hidden context (not shown in the transcript, not even with ctrl+o):
User typed `++r` — Two-phase review discipline is active for this turn:
[REVIEW DISCIPLINE: DOUBLE-CHECK]
Every significant change: multi-agent review ... (11 lines in all)
| Token | Normal mode | Plan mode |
|---|---|---|
++m | Manager mode is active: [ROLE: MANAGER], delegate, never code (29 lines) | Manager + Plan Mode is active: the same text + [ADDON: PLAN MODE]: stay read-only; the plan opens with the role and the full task graph (48 lines) |
++a | Architecture-first: delegate the design to expert agents before implementing | same text: ++a has no plan part |
++r | [REVIEW DISCIPLINE: DOUBLE-CHECK]: review, reproduce, fix confirmed findings only (11 lines) | same text: ++r has no plan part |
++rr | Anti-regression review: regression, project standard and functional correctness axes | same text: ++rr has no plan part |
+++ | Anti-drift cron is active: [ADDON: ANTI-DRIFT CRON], asks Claude to create one unique session cron for the current task now (9 lines) | plan the task anti-drift cron: the same text + [ADDON: ANTI-DRIFT CRON PLAN]: create no cron now, plan it as an execution step (13 lines) |
++rr + ++r | only ++rr is sent (one review per message) | same |
Every placeholder is sent in every mode. A placeholder with a plan part sends that part as an addition in plan mode only. Line counts are lines of the sent text, header line included: the numbers the band uses.
User typed `++r` — Two-phase review discipline is active for this turn:
[REVIEW DISCIPLINE: DOUBLE-CHECK]
Every significant change: multi-agent review (matching reviewer expert, else
general-purpose), simplification pass first.
1) Review - finding = defect with path:line + evidence (failing command/input).
2) Double-check - reproduce each finding.
3) Fix - confirmed findings only.
Big review -> split by area, never one long pass. Brief each: goal + area +
acceptance, what's covered (don't re-litigate), who consumes the verdict;
return verdict first, then findings.
User typed `++m` — Manager mode is active for this turn:
[ROLE: MANAGER]
Manage; never code/build/test/hand-debug: the main context is for orchestration.
Protocol: 1) TaskList; graph exists -> reuse it, else TaskCreate the full graph
before any work. 2) addBlockedBy/addBlocks only for real data-handoffs, else
parallel. 3) TaskUpdate owner, then launch. 4) Validate reports, integrate;
completed only when truly done; failure -> follow-up task + re-delegate. 5) all
code written -> final task: simplify, strip over-engineering.
No Task tools (CLAUDE_CODE_ENABLE_TODO_TOOLS=1 unset) -> same numbered graph
in the plan or .claude/features/<task>.md.
Sizing: one subagent = 1 deliverable, ~<=5 files, ~<=10 steps, ~<=20 min;
larger -> split. An hour-long agent = drift nobody can observe.
Scan all agents: best-matching expert per task, else general-purpose.
Spawn brief: six labeled fields. A subagent starts with an empty context, so a bare one-line task is never enough.
GOAL: task + why it exists - without the why it cannot rank the work.
ROLE: what it owns, must not touch - else two agents edit one file.
SCOPE: paths/commands in bounds and out - else the task widens.
CONTEXT: done, by whom, in parallel; only what this agent needs - else work is redone or overwritten.
CONSUMER: who or what uses the result next + the shape it must fit - else a correct result fails the next step.
DONE: acceptance, what counts as a finding, return (verdict first; evidence: command, result, unchecked; bounded; long output to a file it can write, path returned) - else it stops early or returns a dump.
Code/test briefs add: follow the closest well-built repo counterpart's
principles - additive to conventions/rules/docs, never instead.
Finish the whole job; decide without routine questions.
Plan mode: the first line becomes `User typed ++m — Manager + Plan Mode is active for this turn:`; the normal text stays, then a blank line and this addition:
[ADDON: PLAN MODE]
Stay read-only: no code, board/task-state writes, installation or
configuration. Read-only expert exploration is allowed.
Include in the plan (English, token economy):
- PREAMBLE: [ROLE: MANAGER] + the 5-step protocol restated verbatim as the
plan's opening section - this addon expires, so the plan carries the role
into implementation, no hook needed.
- STEP 0, stated literally: "Re-assume the MANAGER role. Call TaskList; if no
graph exists, create the ENTIRE TaskGraph now - TaskCreate for every node, or
the numbered checklist if task tools are absent - then delegate." On exit
this comes first: not code, not one task.
- The full TaskGraph: every task decomposed (subject, acceptance, owner
agent, bounded scope+acceptance per spawn), dependencies marked, parallel
branches explicit, critical path named.
Deliver the embedded role + graph, not implementation code.
User typed `+++` — Anti-drift cron is active for this turn:
# [ADDON: ANTI-DRIFT CRON]
Now: announce and create one unique session cron for the current task, hourly unless the user's interval differs, using available native scheduling tools. Record its task-specific prompt, schedule ID, timezone, tick count and stop rule. If scheduling is unavailable, report the gap without claiming a schedule exists.
Each tick rereads the goal, task-specific methodology and anti-drift rules; collects active agent updates; reconciles task statuses, dependencies and remaining work; updates the task graph, keeping all unfinished entries and only the latest 10 completed entries, with older completion evidence preserved outside the active graph. It checks delivered work against the end goal, corrects drift, and names remaining acceptance criteria, problems, blockers and user questions.
Then it emits an extremely compact report: `HH:MM TZ · tick N · elapsed`; `🟢 completed`; `🔵 active / remaining / next`; `🔴 problems / blockers / questions`; `⚪ anti-drift verdict`. Omit empty rows; use only these circles. On task completion or cancellation, stop the cron and verify its removal.
Plan mode: the first line becomes `User typed +++ in Plan mode — plan the task anti-drift cron:`; the normal text stays, then a blank line and this addition:
# [ADDON: ANTI-DRIFT CRON PLAN]
Stay read-only in Plan mode: create no cron now. Plan it as an execution step instead: on exit, announce and create one unique session cron per top-level task, with its task-specific prompt, interval and stop rule recorded in that task's methodology.
Your own placeholder can have a plan part too: see Examples.
| Hint on screen | Mac key | Glyph | Does |
|---|---|---|---|
tab | Tab | ⇥ | Inserts the selected typeahead name |
enter | Return | ⏎ | Sends the prompt. On ++r? alone it runs the query instead (how) |
esc | Esc | ⎋ | Closes the typeahead, back to typing |
↑ ↓ ← → | arrow keys | ↑↓←→ | Move in the typeahead (↑↓) or onto a token to read its text (←→) |
shift+tab | Shift + Tab | ⇧⇥ | Default mode (⏸ manual mode on): twice, accept edits then plan; or type /plan. The band does not change at the keypress, whether you enter or leave plan mode: it shows the mode of your last completed prompt, so plan mode adds: appears only after a prompt has run in plan mode. The next prompt is still sent with the new mode's text. The effort toast comes from the other mod, brewmod-plan-effort |
ctrl+o | Control + O | ⌃O | Transcript view: your prompt and the answer only. The injected text is NOT there; use the band or /placeholders show |
<!-- Stable deep link, shared outside the repo: #full-text-demo. Keep the id. -->
| Where you look | It shows | How |
|---|---|---|
| The band above the prompt | Up to 15 rows of what Claude receives, cut row and plan note included | Put the caret on the token (arrows, Home, End); move it off to close |
The chat, /placeholders show ++m | The whole text, printed locally; nothing is sent to Claude | Type it, or type ++m? alone and press Enter twice (below) |
The chat, /placeholders list | Every placeholder with its text, normal and plan mode | Type it |
What ? does. A ? right after a token, with nothing else in the message, is a query, not text. The first Enter fills /placeholders show ++m in the box and sends nothing to Claude. Claude Code prefixes the notice: Prompt dropped by a hook: ++m? = /placeholders show ++m · not sent to Claude · press Enter to print it. That is the expected result: nothing was sent. The second Enter prints the text in the chat. In a longer message (check ++r?), ++r? is ordinary text: the ++r block is sent and the ? stays.
While the name menu is open (typing ++r offers ++rr), it caps the band, and a ? right after the token closes it. If the whole text then fits in 15 rows, the cut row ends with · type ? after ++r to see all. ++m never shows that hint: its 29 lines do not fit in 15 rows. Otherwise the band looks the same with or without the ?: the caret already shows the text.
Band with the caret on ++m (default mode, 120x40). Colours come from your Claude Code theme; the not sent now row is in the plan-mode colour.
++m · Claude receives these lines now:
User typed `++m` — Manager mode is active ...
... 12 more text rows (13 in all) ...
... 16 more lines · whole text: /placeholders show ++m or ++m? alone [Enter]
not sent now · plan mode adds 18 lines
close: move the caret off ++m · send as typed: ++/
| Looks like | Means | In the band above |
|---|---|---|
| Bold, placeholder blue (the theme's suggestion colour) | A placeholder name; an unknown one is bold yellow (the theme's warning colour) | ++m, ++zz |
| Bold, theme text colour (white on a dark theme, black on a light one) | Text Claude receives with this message | the User typed ... rows |
Bold, plan-mode colour (Claude Code's planMode theme colour: teal on a dark theme, a darker teal on a light one) | The plan-mode addition Claude receives only in plan mode | the [ADDON: PLAN MODE] rows in plan mode |
| Plain, plan-mode colour | Marks that name plan mode | plan mode adds:, not sent now · plan mode adds 18 lines, plan +, · plan mode after placeholders 2 |
| Underlined, theme text colour | An action: what to type or do | /placeholders show ++m, ++m?, move the caret off ++m, ++/ |
| Plain, theme text colour | A key to press | [Enter] |
| Grey (dim) | Labels and notes; never sent. Text that is not sent (a skipped token, an escaped message) is grey too | close:, more:, ... 16 more lines, placeholders 2 |
The text under the head holds up to 15 rows, the cut row and the plan note included; the head and foot rows (and an also: row) come on top. The text rows are wrapped to the terminal width, so how many fit changes with it. K more lines counts the lines of the sent text left out (its header line and blank line included): ++m is 29 lines, 13 text rows shown at 120x40 (13 + the cut row + the plan note = 15).
plan mode adds N lines counts the lines of the plan part; an empty plan part counts as none, so it gets no plan + tag and no note.
In plan mode the band shows the plan header, the normal rows, a plan mode adds: row in the plan-mode colour and then [ADDON: PLAN MODE] with its rows in bold plan-mode colour. Outside plan mode a name with a plan part ends with the note not sent now · plan mode adds N lines in the plan-mode colour; +++ shows its own text there, sent and bold, with the note not sent now · plan mode adds 3 lines.
Hint rows, as drawn. A custom prefix replaces ++ in all of them.
| Row | Text |
|---|---|
| Cut row | ... 16 more lines · whole text: /placeholders show ++m or ++m? alone [Enter] |
| Cut row, narrow terminal or a build without the mod tools | ... 16 more lines · whole text: /placeholders show ++m |
Cut row, name menu open and ? would show it all | ... 5 more lines · type ? after ++r to see all |
| Foot with the caret on a token | close: move the caret off ++m · send as typed: ++/ |
| Foot with the caret on an unknown token | names: /placeholders list |
| Foot of the compact band | more: put the caret on ++r · send as typed: ++/ · help: /placeholders help |
| Foot of an escaped message | turn back on: delete ++/ |
| Other tokens while the caret is on one | also: ++a ++rr |
The or ++m? alone [Enter] part is the query from What ? does: [Enter] fills the show command. It appears only when the whole row fits the width. A narrower terminal shrinks the row in steps: first or ++m? alone [Enter] goes, then whole text:, then the count (... 16 more lines · ). The show command is never cut while it fits on its own. /placeholders and /placeholders help name the ++r? hand-off.
| Do | You type | What happens |
|---|---|---|
| Add | /placeholders add ++db: always use the staging DB | Claude drafts it and asks once: Save ++db as drafted? with Save as drafted (Recommended) or Change it (the question never names a layer; scope words count only outside the placeholder's own text); with no scope word, the same dialog also asks Where to save ++db? with Global (Recommended) or Project; starting with global or project skips it. Reply: saved ++db (global): ~/.claude/placeholders/db.md |
| Add with a plan part | /placeholders add ++ship: run the tests; in plan mode also list the release steps | The same dialog adds Add this plan-mode part to ++ship? (Add it (Recommended) or No plan part). Saved as ship.md (run the tests) and ship.plan.md (also list the release steps, plan: add). A plan-mode part with no normal text to join is refused, so it is never sent in every mode: ++ship has no text yet: send text too (an inline normal text: a plan-mode part needs a normal text that is not inline) |
| Change | /placeholders make ++r shorter | Claude starts from the current text; the change stays in its layer (a plugin default -> asks where) |
| Remove | /placeholders remove ++db | Asks once: Remove it (Recommended) or Keep it; if the name is in both layers, it also asks where. Removing your override of a built-in brings the built-in back; plugin defaults are never removed (++r is built in and cannot be removed). Reply: removed ++db (global): ~/.claude/placeholders/db.md · ++db is no longer defined. When another layer keeps only a plan part for the name, the reply ends · its plan-mode part is now sent in every mode |
| Remove a plan part | /placeholders remove the plan part of ++ship | Asks Remove the plan-mode part of ++ship (global)?, then deletes ship.plan.md; ++ship keeps its normal text |
| Remove the normal text only | /placeholders remove the normal text of ++ship | Refused while ship.plan.md would be left alone, since that part would then be sent in every mode; nothing is deleted: removing only the normal text of ++ship would leave its plan-mode part alone, and that part would then be sent in every mode · remove both parts (part all), or change the normal text instead. If another layer still holds the normal text, only the file in the chosen layer goes |
| Show | /placeholders show ++r ++m, or ++r? alone + Enter | Prints the exact text with no Claude turn: outside plan mode normal: then plan mode adds:; in plan mode one block normal + plan mode part: as sent. An inline placeholder that does not expand shows stays as typed; an empty body silences the token, in plan mode too. For ++r? see Read the full text |
| List | /placeholders list | Prints every placeholder with its text as sent, normal and plan mode, with no Claude turn |
| Escape | ++/ what does ++r do? | Sent exactly as typed: no block, ++/ stays in the text |
| Scope | /placeholders project add ++lint: run npm run lint first | Reply: saved ++lint (project): .claude/placeholders/lint.md; the project copy wins over global |
| Command | What it does |
|---|---|
/placeholders (also status) | One row per name with layer and tags (plan + for a plan part with text, inline), plus hints for reading texts (caret, /placeholders show), escape and scope |
/placeholders show ++<name> ..., list, help | Print the exact text sent (list = all, normal and plan), or the full help, with no Claude turn |
/placeholders <anything else> | Claude answers, or drafts, asks once and saves; any language. A first word global or project picks the layer; without it your words decide, else one question (Global first) |
The status view explains the plan + tag, and /placeholders help describes the two file kinds, in these lines (default prefix):
`plan +`: its `<name>.plan.md` adds text in Plan mode; `<name>.md` is sent in every mode
Plan mode: `<name>.md` is sent in every mode; an optional `<name>.plan.md` (`plan: add`) adds its text in Plan mode (`++m`, `+++`), marked `plan +`. One review per message: `++rr` wins over `++r`.
Files: `<name>.md` = optional front matter (description, insert: context|inline, order, group, priority, header) + the text; `<name>.plan.md` = its Plan mode addition. Edit by hand any time; the next prompt reads it.
| State | What you see |
|---|---|
| Highlight, typeahead | Terminal UI only. A known token is underlined; after the prefix, matching names appear, Tab inserts one. After Tab or Enter on a name row, a history recall (arrow keys) or an undo, the band shows at once; the underline in the box appears with the next key (an engine limit). The one option, prefix (default ++, 2-8 punctuation characters), is set in /config |
| Compact band | Header placeholders 3 in grey ( · plan mode is appended in the plan-mode colour in plan mode), then one row per token: ++r <description> (name in bold blue, description grey), with · Claude receives these lines now: and the text under it when the text is drawn. Rows past the space fold into ... K more placeholders. Foot (actions underlined): more: put the caret on ++r · send as typed: ++/ · help: /placeholders help. plan +, in the plan-mode colour, marks a name with a plan part that has text; a skipped token says why, for example (not sent: ++rr wins) |
| Caret on a token | The band shown in Read the full text. A name with a plan part that has text ends with not sent now · plan mode adds N lines in the plan-mode colour; other tokens sit on one also: ++m ++a row |
| Rows from other mods | Rows another mod draws above the prompt, for example the plan-mode row of brewmod-plan-effort (same plan-mode colour), stay visible above the band; the band fits into the rows that are left, in the default and the fullscreen view alike, whichever of the two mods loads first: head, text, cut row and foot all stay on screen |
| Escaped | `
hooks/register.ts 403 lines1// SPDX-License-Identifier: MIT
2// Copyright (c) 2025-2026 Maksim Kochetkov
3
4import { atom, read, update } from 'claude-code'
5import type { Register, Timer } from 'claude-code'
6import { editorMatchers, getEditorEntries, setEditorEntries } from './lib/editor-state'
7import { caretFocus, heldFocus, highlight, isMenuOpen, sameFocus, sameView, suggest, type CaretFocus } from './lib/editor'
8import { escapeMarkers, isEscaped, markerOf, validatePrefix, type PlaceholderView } from './lib/match'
9import { memoCompile, type Compiled } from './lib/compiled'
10import { FILES_GONE, PluginFilesGone, configDirOf, issuesMessage, loadRegistry, newRegistryCache, toEditorEntries, type Registry } from './lib/defs'
11import { modeStatePath, planFromState } from './lib/mode'
12import { bandRows, bandState, budgets, renderBand, treeRows } from './lib/band'
13import { assembleDraft, planParts } from './lib/sent'
14import { NEEDS_NEW_CC, TOOL_PREFIX, handoffAck, handoffText, listTool, oneLayer, removeTool, saveTool, tools, type RemoveInput, type SaveInput, type ToolOut } from './lib/command'
15import { fillText, fullText, helpText, parseArgs, queryDrop, queryNames, shownDirs, statusText } from './lib/show'
16import { expandInline, isInlineSubmit, unknownMessage, unknownTokens, type SubmitLike } from './lib/inline'
17
18// Atoms are declared in this file only (the scan reads this file); the band reads the same view atom.
19const viewAtom = atom({ plugin: 'brewmod-placeholders', key: 'view' } as const, { tokens: [] })
20const focusAtom = atom({ plugin: 'brewmod-placeholders', key: 'focus' } as const, { name: null, isQuery: false, isMenuOpen: false })
21
22const REFRESH_MS = 1000
23// The engine drops a token's unanswered rows 150 ms after it asks (2.1.301): a hold outlasts that, then ends.
24const HOLD_MS = 300
25
26type Writers = { view: (v: PlaceholderView) => Promise<unknown>; focus: (f: CaretFocus) => Promise<unknown>; after: (ms: number, fn: () => void) => Timer }
27
28// No guards around the mod's own logic: the engine skips a failing hook and the chain goes on (reference.md:78).
29// `$` is never passed on, so each registry load spells its `$.fs.*` lambdas at the call site.
30export const register: Register = (on, options) => {
31 const check = validatePrefix(options.prefix)
32 const prefix = check.prefix
33 const cache = newRegistryCache()
34 let hasTools = false // the model tools were registered at session.start
35 // Settles with hasTools once session.start's registration ends: a command typed right after launch waits for it.
36 let toolsSettled: (v: boolean) => void = () => undefined
37 const toolsReady = new Promise<boolean>((resolve) => (toolsSettled = resolve))
38 let isPlan = false // permission_mode of the last state file hooks/inject.mjs wrote for this session
39 let compiled: Compiled | null = null
40 let published: Registry | null = null
41 let shown: PlaceholderView | null = null // last view written to viewAtom
42 let focused: CaretFocus | null = null // last focus written to focusAtom
43 // The engine may ask prompt.autocomplete before prompt.edit's writes land: answers read `want` and wait for `pending`.
44 let at: { text: string; cursor: number } | null = null // box of the last publish
45 let want: CaretFocus | null = null // focus published for box `at`, its write maybe still in flight
46 let pending: Promise<void> = Promise.resolve() // the atom writes queued so far, focus writes in order; never rejects
47 let held: CaretFocus | null = null // true focus of box `at` while heldFocus keeps the menu open
48 let holdTimer: Timer | null = null
49 let refreshedAt = -REFRESH_MS // clock of the last typeahead registry refresh
50 let wasDraft: boolean | null = null // isDraft of the last hint-line draw
51 let isGone = false // the plugin's own placeholders/ folder vanished: the cached list stays, the band shows the reload line
52 let goneToasted = false
53
54 // A load that finds the plugin files gone resolves null (cache kept); a flip of that state redraws the band, the first sighting toasts.
55 const settle = async (load: Promise<Registry>, toast: (text: string) => void, redraw: () => void): Promise<Registry | null> => {
56 const was = isGone
57 let reg: Registry | null = null
58 try {
59 reg = await load
60 isGone = false
61 } catch (err) {
62 if (!(err instanceof PluginFilesGone)) throw err
63 isGone = true
64 }
65 if (isGone !== was) redraw()
66 if (isGone && !goneToasted) {
67 goneToasted = true
68 toast(FILES_GONE)
69 }
70 return reg
71 }
72
73 // Hands a freshly loaded registry to the editor/band names and the compiled matchers; both skip an unchanged registry.
74 const adopt = (reg: Registry): Compiled => {
75 if (published !== reg) {
76 published = reg
77 setEditorEntries(toEditorEntries(reg.defs))
78 }
79 compiled = memoCompile(compiled, reg.defs, prefix)
80 return compiled
81 }
82
83 // Command registration cannot fail the warm-up below, and the warm-up cannot block the session.
84 on('session.start', async ($, e, next) => {
85 await $.command
86 .register({ name: 'placeholders', description: 'Show, list or explain your placeholders; or say in any words what to add, change or remove', argumentHint: `[show ${prefix}<names> | list | help | any words]` })
87 .catch(() => undefined)
88 // Older builds have no $.tool (the call throws): hasTools stays false and the command answers with the status only.
89 try {
90 for (const t of tools(prefix)) await $.tool.register({ name: t.name, description: t.description, inputSchema: t.inputSchema, isDeferred: false })
91 hasTools = true
92 // A band drawn while the tools were registering lacks the `P<name>?` hand-off: draw it again.
93 $.ui.invalidate('ui.render')
94 } catch {
95 hasTools = false
96 }
97 toolsSettled(hasTools)
98 if (check.warning !== null) $.ui.toast(check.warning)
99 const reg = await settle(
100 loadRegistry(
101 { exists: (p) => $.fs.exists(p), list: (p) => $.fs.list(p), read: (p) => $.fs.read(p) },
102 { pluginRoot: $.plugin.root, root: await $.session.root(), configDir: configDirOf(await $.env.get('CLAUDE_CONFIG_DIR'), (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))) },
103 cache,
104 ),
105 (t) => $.ui.toast(t, { timeoutMs: 8000 }), () => $.ui.invalidate('ui.render'),
106 )
107 if (reg !== null) {
108 adopt(reg)
109 const issues = issuesMessage(reg)
110 if (issues !== null) $.ui.toast(issues)
111 }
112 const wasPlan = isPlan
113 try {
114 const file = modeStatePath($.plugin.root, await $.session.id())
115 if (file !== null) isPlan = planFromState(await $.fs.read(file)) ?? isPlan
116 } catch {
117 // no state file yet: not in plan mode
118 }
119 // The band reads a module variable, not an atom: a flipped mode redraws it now, not at the next key.
120 if (isPlan !== wasPlan) $.ui.invalidate('ui.render')
121 return next(e)
122 })
123
124 // The command hook records the mode at each prompt and tool batch; a finished turn has seen both. No I/O in prompt.edit, so the band reads the module variable.
125 on('turn.complete', async ($, e, next) => {
126 const wasPlan = isPlan
127 try {
128 const file = modeStatePath($.plugin.root, await $.session.id())
129 if (file !== null) isPlan = planFromState(await $.fs.read(file)) ?? isPlan
130 } catch {
131 // keep the last known mode
132 }
133 if (isPlan !== wasPlan) $.ui.invalidate('ui.render')
134 return next(e)
135 })
136
137 // Writes `f` as the box's focus after every write queued before it, if `want` is still `from` (no later publish or release).
138 const replace = (from: CaretFocus, f: CaretFocus, writeFocus: (f: CaretFocus) => Promise<unknown>): Promise<void> =>
139 (pending = pending.then(async () => {
140 if (want !== from) return
141 want = f
142 try {
143 await writeFocus(f)
144 focused = f
145 } catch {
146 // write refused: the atom keeps the last focus
147 }
148 }))
149
150 // Ends a hold with the true focus, unless a later publish or our rows ended it first.
151 const release = (wait: CaretFocus, writeFocus: (f: CaretFocus) => Promise<unknown>) => {
152 const from = want
153 if (held !== wait || from === null) return
154 held = null
155 holdTimer?.cancel()
156 void replace(from, wait, writeFocus)
157 }
158
159 // The box's view and focus, each atom written only when it changed; writers spelled at the call site. Returns the highlight.
160 // A recall: no menu, no hold (no typeahead while an entry is shown; a draft put back is corrected by our rows).
161 const publish = async (text: string, cursor: number, io: Writers, isRecall = false) => {
162 const h = highlight(editorMatchers(prefix), text)
163 const real = { ...caretFocus(h.view, text, cursor), isMenuOpen: !isRecall && isMenuOpen(prefix, text, cursor, getEditorEntries()) }
164 const f = isRecall ? real : heldFocus(real, want, text, cursor)
165 at = { text, cursor }
166 want = f
167 holdTimer?.cancel()
168 const wait = f === real ? null : real
169 held = wait
170 // No answer comes when the engine asks nothing (Esc dropped the rows, bash mode): the hold ends on its own.
171 holdTimer = wait === null ? null : io.after(HOLD_MS, () => release(wait, io.focus))
172 const prior = pending
173 pending = (async () => {
174 try {
175 if (shown === null || !sameView(h.view, shown)) {
176 await io.view(h.view)
177 shown = h.view
178 }
179 // A focus write in flight (the last key's, a release) lands first: compared with it, this one is never lost.
180 await prior
181 if (focused === null || !sameFocus(f, focused)) {
182 await io.focus(f)
183 focused = f
184 }
185 } catch {
186 // state write failed: keep the highlight, retry on the next edit; a refused view write still keeps the order
187 await prior
188 }
189 })()
190 await pending
191 return h
192 }
193
194 // Zero I/O except the view and focus atoms, each written only when it changes; caret moves arrive here too (inputText '').
195 on('prompt.edit', async ($, e, next) => {
196 const r = await next(e)
197 const io: Writers = { view: (v) => update($, viewAtom, () => v), focus: (f) => update($, focusAtom, () => f), after: (ms, fn) => $.clock.after(ms, fn) }
198 const h = await publish(r.text, r.cursor, io)
199 return h.decorations.length === 0 ? r : { ...r, decorations: [...(r.decorations ?? []), ...h.decorations] }
200 })
201
202 // A taken row, a recall, an undo, a dropped draft put back or a fill change the box without prompt.edit: the band follows here.
203 // No paint channel here: the box underline waits for the next key.
204 on('prompt.change', async ($, e, next) => {
205 const io: Writers = { view: (v) => update($, viewAtom, () => v), focus: (f) => update($, focusAtom, () => f), after: (ms, fn) => $.clock.after(ms, fn) }
206 await publish(e.text, e.cursor, io, e.origin.kind === 'history')
207 return next(e)
208 })
209
210 // The hint line redraws when the box turns empty or non-empty (Esc Esc, submit, a recall into an empty box): draw the band again, it reads the box. A state write is refused while drawing.
211 on('ui.render', { component: 'PromptHint' }, ($, e, next) => {
212 const flipped = wasDraft !== null && wasDraft !== e.props.isDraft
213 wasDraft = e.props.isDraft
214 if (flipped) $.ui.invalidate('ui.render')
215 return next(e)
216 })
217
218 // A prefixed token re-reads the definitions at most once a second, so a file made by hand shows as known without a submit. A failed read keeps the rows.
219 // prompt.edit already drew this key's view with the old names: a changed list re-draws it here, so the band does not lag a key.
220 on('prompt.autocomplete', { token: /^[^\w\s]{2}/ }, async ($, e, next) => {
221 const r = await next(e)
222 try {
223 const now = await $.clock.now()
224 if (e.token.startsWith(prefix) && now - refreshedAt >= REFRESH_MS) {
225 refreshedAt = now
226 const reg = await settle(
227 loadRegistry(
228 { exists: (p) => $.fs.exists(p), list: (p) => $.fs.list(p), read: (p) => $.fs.read(p) },
229 { pluginRoot: $.plugin.root, root: await $.session.root(), configDir: configDirOf(await $.env.get('CLAUDE_CONFIG_DIR'), (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))) },
230 cache,
231 ),
232 (t) => $.ui.toast(t, { timeoutMs: 8000 }), () => $.ui.invalidate('ui.render'),
233 )
234 const before = getEditorEntries()
235 if (reg !== null) adopt(reg)
236 const view = highlight(editorMatchers(prefix), e.text).view
237 if (getEditorEntries() !== before && (shown === null || !sameView(view, shown))) {
238 await update($, viewAtom, () => view)
239 shown = view
240 }
241 }
242 } catch {
243 // keep the entries we have: a failed refresh must not drop the typeahead rows
244 }
245 const rows = suggest(prefix, e.token, getEditorEntries(), /\s/.test(e.text.charAt(e.cursor)))
246 const isShown = at !== null && at.text === e.text && at.cursor === e.cursor
247 const wait = held
248 // No rows closes the held menu: the true focus goes out after this answer (clock.after), so the band grows only once the rows are gone.
249 if (wait !== null && isShown && rows.length === 0 && r.suggestions.length === 0) $.clock.after(0, () => release(wait, (f) => update($, focusAtom, () => f)))
250 // Our rows for the box shown: the menu is open whatever publish assumed (a draft a recall put back); written before the rows go out.
251 if (isShown && rows.length > 0) {
252 held = null
253 holdTimer?.cancel()
254 const from = want
255 if (from !== null && !from.isMenuOpen) await replace(from, { ...from, isMenuOpen: true }, (f) => update($, focusAtom, () => f))
256 }
257 return rows.length === 0 ? r : { suggestions: [...r.suggestions, ...rows] }
258 })
259
260 // Inline defs are expanded in the submitted text; context defs go through hooks/inject.mjs. No mode here: an inline plan part never expands.
261 // The unknown-token toast fires here (a command hook has no UI): only for text the person typed, after the expansion.
262 on('prompt.submit', async ($, e, next) => {
263 const own: SubmitLike = e // isMeta is absent from the 2.1.296 types
264 const isTyped = own.origin.kind === 'composer' && own.isMeta === undefined
265 // The draft leaves the composer only on the person's own Enter: other origins keep the band.
266 if (isTyped) {
267 try {
268 await update($, viewAtom, () => ({ tokens: [] }))
269 shown = null
270 } catch {
271 // band stays until the next edit
272 }
273 }
274 // `P/` or `P\` anywhere: sent as typed, no expansion and no toast; inject.mjs skips it too.
275 if (isEscaped(prefix, e.text)) return next(e)
276 // Only `P<name>?` items, no attachments, a build with tools (the hand-off's gate; fill proven only there): dropped, the box gets `/placeholders show P<names> `.
277 // Not run in place: $.command.run passes "every hook but the calling one" (claude-code.d.ts); seen live: `prompt.submit skipped: re-entry` (hand-off).
278 const asked = isTyped && hasTools && e.command === undefined && (e.attachments?.length ?? 0) === 0 ? queryNames(editorMatchers(prefix), e.text) : null
279 if (asked !== null) {
280 $.clock.after(0, () => {
281 try {
282 void $.prompt.fill({ text: fillText(prefix, asked), mode: 'replace' }).catch(() => undefined)
283 } catch {
284 // a fill that throws at once: the drop notice stays, the box stays empty
285 }
286 })
287 return { drop: queryDrop(prefix, asked) }
288 }
289 if (!isInlineSubmit(e) || !e.text.includes(prefix)) return next(e)
290 const reg = await settle(
291 loadRegistry(
292 { exists: (p) => $.fs.exists(p), list: (p) => $.fs.list(p), read: (p) => $.fs.read(p) },
293 { pluginRoot: $.plugin.root, root: await $.session.root(), configDir: configDirOf(await $.env.get('CLAUDE_CONFIG_DIR'), (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))) },
294 cache,
295 ),
296 (t) => $.ui.toast(t, { timeoutMs: 8000 }), () => $.ui.invalidate('ui.render'),
297 )
298 // Gone: inline defs expand from the cached list; no unknown toast, the list cannot be vouched for.
299 const c = reg === null ? compiled : adopt(reg)
300 if (c === null) return next(e)
301 const text = expandInline(c, e.text)
302 const bad = reg === null ? [] : unknownTokens(c.matchers, text ?? e.text)
303 if (bad.length > 0) $.ui.toast(unknownMessage(bad))
304 return next(text === null ? e : { ...e, text })
305 })
306
307 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
308 // An emptied box (Esc Esc, submit) draws no band: the box is read, as the atoms may still hold the last draft. Other surfaces answer '', so only the terminal is asked.
309 const draft = e.surface === 'terminal' ? (await $.prompt.read()).text : null
310 const view = await read($, viewAtom)
311 const focus = await read($, focusAtom)
312 const mode = bandState({ hasSurvey: e.props.hasSurvey, draft, view, focus: focus.name })
313 if (mode === 'hidden') return next(e)
314 // The exact text per token, from the draft (terminal) or the token texts; before the first registry load the entries' bodies stand.
315 const sent = compiled === null ? undefined : assembleDraft(draft ?? view.tokens.map((t) => t.text).join(' '), compiled, prefix, isPlan).tokens
316 const defs = compiled?.defs
317 const plans = defs === undefined ? undefined : (name: string) => planParts(defs, name, prefix)
318 // Another mod's rows beneath sit above the band (kept on screen, as when that mod is outermost); the band gives up their rows.
319 const below = await next(e)
320 const ui = $.ui.resolve(e)
321 const band = renderBand(ui, bandRows(view, getEditorEntries(), sent, plans), {
322 mode,
323 focus,
324 prefix,
325 // No draft (desktop): the marker the last edit saw.
326 marker: (draft === null ? null : markerOf(compiled?.matchers ?? prefix, draft)) ?? view.escapedBy ?? escapeMarkers(prefix)[0],
327 isPlan,
328 isGone,
329 ...budgets(e.props.maxRows - treeRows(below), e.viewport?.isFullscreen === true, focus.isMenuOpen),
330 columns: e.props.bodyColumns,
331 hasQuery: hasTools,
332 })
333 return below.type === 'engine' ? band : ui.Box({ flexDirection: 'column', children: [below, band] })
334 })
335
336 on('command.run', { command: 'placeholders' }, async ($, e) => {
337 const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
338 const roots = { pluginRoot: $.plugin.root, root: await $.session.root().catch(() => undefined), configDir: configDirOf(await $.env.get('CLAUDE_CONFIG_DIR'), home) }
339 const reg = await settle(loadRegistry({ exists: (p) => $.fs.exists(p), list: (p) => $.fs.list(p), read: (p) => $.fs.read(p) }, roots, cache), (t) => $.ui.toast(t, { timeoutMs: 8000 }), () => $.ui.invalidate('ui.render'))
340 if (reg === null) return { text: FILES_GONE }
341 adopt(reg)
342 // A command run before the tools registered waits for them, at most 3 s.
343 const withTools = hasTools || (await Promise.race([toolsReady, new Promise<boolean>((resolve) => $.clock.after(3000, () => resolve(false)))]))
344 // status, help, show and list answer here; the rest goes to Claude.
345 const act = parseArgs(e.args, prefix, reg.defs.map((d) => d.name))
346 const dirs = shownDirs(roots, home)
347 const one = oneLayer(reg, roots)
348 if (act.kind === 'help') return { text: helpText(prefix, dirs, withTools) }
349 if (act.kind === 'list' || act.kind === 'show') return { text: fullText(one, act.kind === 'list' ? null : act.names, prefix, isPlan) }
350 const status = statusText(one, prefix, dirs, withTools)
351 if (act.kind === 'status') return { text: status }
352 if (!withTools) return { text: `${status}\n${NEEDS_NEW_CC}` }
353 // submit is refused inside command.run: hand off from a timer; fill is the fallback when submit refuses.
354 const text = handoffText(act.request, prefix, act.scope)
355 $.clock.after(250, () => {
356 void (async () => {
357 try {
358 await $.prompt.submit({ text, asUser: true })
359 } catch {
360 await $.prompt.fill({ text, mode: 'replace' }).catch(() => undefined)
361 }
362 })()
363 })
364 return { text: handoffAck(status) }
365 }).catch((_$, _e, next) => ({ text: `failed: ${next.error.message ?? next.error.kind}` }))
366
367 // The model's tools: answered here, so Claude Code asks no permission for the file write.
368 on('tool.call', { tool: /^mcp__brewmod-placeholders__/ }, async ($, e) => {
369 const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
370 const roots = { pluginRoot: $.plugin.root, root: await $.session.root().catch(() => undefined), configDir: configDirOf(await $.env.get('CLAUDE_CONFIG_DIR'), home) }
371 if (e.tool === `${TOOL_PREFIX}placeholders_help`) {
372 const help = helpText(prefix, shownDirs(roots, home))
373 return { result: help, text: help }
374 }
375 const io = {
376 exists: (p: string) => $.fs.exists(p),
377 list: (p: string) => $.fs.list(p),
378 read: (p: string) => $.fs.read(p),
379 write: (p: string, t: string) => $.fs.write(p, t),
380 stat: (p: string) => $.fs.stat(p, { resolve: true }).catch(() => undefined),
381 remove: async (p: string) => {
382 const r = await $.process.run(['rm', '--', p])
383 return { exitCode: r.exitCode, stderr: r.stderr }
384 },
385 }
386 const input = e as SaveInput & RemoveInput
387 // Gone: nothing is written or removed, the model gets the reload hint.
388 const reg = await settle(loadRegistry(io, roots, cache), (t) => $.ui.toast(t, { timeoutMs: 8000 }), () => $.ui.invalidate('ui.render'))
389 if (reg === null) return { result: FILES_GONE, text: FILES_GONE, isError: true }
390 const out: ToolOut =
391 e.tool === `${TOOL_PREFIX}save_placeholder`
392 ? await saveTool(io, roots, input, prefix, home)
393 : e.tool === `${TOOL_PREFIX}remove_placeholder`
394 ? await removeTool(io, roots, input, prefix, home)
395 : await listTool(io, roots, reg, prefix)
396 if (out.registry !== null) adopt(out.registry)
397 return out.isError === true ? { result: out.text, text: out.text, isError: true } : { result: out.text, text: out.text }
398 }).catch((_$, _e, next) => {
399 const text = `failed: ${next.error.message ?? next.error.kind}`
400 return { result: text, text, isError: true }
401 })
402}
403hooks/lib/editor-state.ts 32 lines1// Module state shared by the editor hooks and the registry: names for highlight and typeahead.
2import { compileMatchers, type Matchers } from './match'
3import type { EditorEntry } from './editor'
4
5export const DEFAULT_ENTRIES: readonly EditorEntry[] = [
6 { name: 'm', description: 'Manager mode: orchestrate and delegate, never code in the main context' },
7 { name: 'a', description: 'Architecture-first: delegate the design to expert agents before implementing' },
8 { name: 'r', description: 'Two-phase review: review every significant change, then double-check each finding' },
9 { name: 'rr', description: 'Anti-regression review: regression, project standard and functional correctness axes' },
10 { name: '+', description: 'Anti-drift cron for the current task; plan mode plans it as a step' },
11]
12
13let entries: readonly EditorEntry[] = DEFAULT_ENTRIES
14let compiled: { entries: readonly EditorEntry[]; prefix: string; ms: Matchers } | null = null
15
16// Registry hook (session.start): replace the names the editor knows; pass a NEW array each time.
17export function setEditorEntries(next: readonly EditorEntry[]): void {
18 entries = next
19}
20
21export function getEditorEntries(): readonly EditorEntry[] {
22 return entries
23}
24
25// Matchers for the current entries; rebuilt only when the entries array or the prefix changes.
26export function editorMatchers(prefix: string): Matchers {
27 if (compiled === null || compiled.entries !== entries || compiled.prefix !== prefix) {
28 compiled = { entries, prefix, ms: compileMatchers(prefix, entries.map((e) => e.name)) }
29 }
30 return compiled.ms
31}
32hooks/lib/editor.ts 106 lines1// Pure editor UX: draft -> view + decorations, view diff, typeahead rows. Zero I/O, no engine state.
2import type { PromptAutocompleteSuggestion, PromptDecoration } from 'claude-code'
3import type { PlaceholderFocus as CaretFocus, PlaceholderView } from '../../types'
4import { scanDraft, type Matchers } from './match'
5
6export const MAX_DECORATED_CHARS = 20_000
7export const EMPTY_VIEW: PlaceholderView = { tokens: [] }
8
9export const KNOWN_COLOR = 'suggestion'
10export const UNKNOWN_COLOR = 'warning'
11// Claude Code's plan-mode colour: every plan-mode label, tag and addition.
12export const PLAN_COLOR = 'planMode'
13export type EditorEntry = { name: string; description?: string; body?: string; isInline?: boolean }
14export type Highlight = { view: PlaceholderView; decorations: PromptDecoration[] }
15export type { CaretFocus }
16
17const GRAPHEME_TAIL = /[\p{M}\u200D\uFE00-\uFE0F]*/uy
18
19// A run ends on a grapheme edge: the engine moves an end inside a grapheme back to its start, so combining marks, ZWJ and variation selectors after the token join it.
20function graphemeEnd(text: string, end: number): number {
21 GRAPHEME_TAIL.lastIndex = end
22 const m = GRAPHEME_TAIL.exec(text)
23 return end + (m === null ? 0 : m[0].length)
24}
25
26// Known token -> KNOWN_COLOR + underline; unknown -> UNKNOWN_COLOR. Above the cap or without the prefix -> nothing.
27// Escaped draft: markers bold UNKNOWN_COLOR, every token dim and struck through (nothing in it is substituted); escapedBy = the first marker.
28export function highlight(ms: Matchers, text: string): Highlight {
29 if (text.length > MAX_DECORATED_CHARS || !text.includes(ms.prefix)) return { view: EMPTY_VIEW, decorations: [] }
30 const view = scanDraft(ms, text)
31 const marks = [...text.matchAll(ms.escape)]
32 const first = marks[0]
33 if (first !== undefined) {
34 const runs = [
35 ...view.tokens.map((t): PromptDecoration => ({ start: t.start, end: graphemeEnd(text, t.end), dimColor: true, strikethrough: true })),
36 ...marks.map((m): PromptDecoration => ({ start: m.index, end: graphemeEnd(text, m.index + m[0].length), color: UNKNOWN_COLOR, bold: true })),
37 ]
38 return { view: { ...view, isEscaped: true, escapedBy: first[0] }, decorations: runs.sort((a, b) => a.start - b.start) }
39 }
40 const decorations = view.tokens.map((t): PromptDecoration => {
41 const end = graphemeEnd(text, t.end)
42 return t.isKnown ? { start: t.start, end, color: KNOWN_COLOR, underline: true } : { start: t.start, end, color: UNKNOWN_COLOR }
43 })
44 return { view, decorations }
45}
46
47// Offsets are not compared: the band reads text/name/isKnown and the escape marker only; decorations are rebuilt on every edit.
48export function sameView(a: PlaceholderView, b: PlaceholderView): boolean {
49 if (a.tokens.length !== b.tokens.length || a.isEscaped !== b.isEscaped || a.escapedBy !== b.escapedBy) return false
50 return a.tokens.every((x, i) => {
51 const y = b.tokens[i]
52 return y !== undefined && x.text === y.text && x.name === y.name && x.isKnown === y.isKnown
53 })
54}
55
56// Token whose [start, end] holds the caret, or end+1 when `?` follows it (isQuery): the band's FOCUS trigger.
57export function caretFocus(view: PlaceholderView, text: string, cursor: number): Omit<CaretFocus, 'isMenuOpen'> {
58 for (const t of view.tokens) {
59 const isQuery = text.charAt(t.end) === '?'
60 if (cursor >= t.start && cursor <= t.end + (isQuery ? 1 : 0)) return { name: t.name, isQuery }
61 }
62 return { name: null, isQuery: false }
63}
64
65const SPACE = /\s/
66// Tokens our prompt.autocomplete hook answers: the literal matcher in register.ts (validate reads only a literal there).
67const ASKED_TOKEN = /^[^\w\s]{2}/
68
69// The engine's typeahead token: the word before the caret. A backward walk, not /\S*$/: that regex is quadratic on a long word (a pasted blob).
70export function tokenAt(text: string, cursor: number): string {
71 let i = cursor
72 while (i > 0 && !SPACE.test(text.charAt(i - 1))) i--
73 return text.slice(i, cursor)
74}
75
76// Our typeahead has rows for the word before the caret; computed in prompt.edit, as prompt.autocomplete lands too late.
77export function isMenuOpen(prefix: string, text: string, cursor: number, entries: readonly EditorEntry[]): boolean {
78 return suggest(prefix, tokenAt(text, cursor), entries).length > 0
79}
80
81// A menu closing on a token we still answer stays open until that answer or the hold timer (register.ts): the engine draws its last rows till then,
82// and a band grown under them overflows the screen, its top scrolled away for good. Same name keeps isQuery, so the band does not change.
83export function heldFocus(next: CaretFocus, last: CaretFocus | null, text: string, cursor: number): CaretFocus {
84 if (next.isMenuOpen || last?.isMenuOpen !== true || !ASKED_TOKEN.test(tokenAt(text, cursor))) return next
85 return { ...next, isMenuOpen: true, isQuery: next.name === last.name ? last.isQuery : next.isQuery }
86}
87
88export const sameFocus = (a: CaretFocus, b: CaretFocus): boolean => a.name === b.name && a.isQuery === b.isQuery && a.isMenuOpen === b.isMenuOpen
89
90// Rows for the token at the cursor: names whose `P+name` extends it; an exact match and a repeated name give no row.
91// A space already after the caret -> rows drop their own trailing space, so taking one never leaves two.
92export function suggest(prefix: string, token: string, entries: readonly EditorEntry[], isSpaceAfter = false): PromptAutocompleteSuggestion[] {
93 if (!token.startsWith(prefix)) return []
94 const typed = token.toLowerCase()
95 const seen = new Set<string>()
96 const rows: PromptAutocompleteSuggestion[] = []
97 for (const entry of entries) {
98 const name = entry.name.toLowerCase()
99 const full = prefix + name
100 if (seen.has(name) || full === typed || !full.startsWith(typed)) continue
101 seen.add(name)
102 rows.push({ text: isSpaceAfter ? full : `${full} `, label: full, description: entry.description ?? name })
103 }
104 return rows
105}
106hooks/lib/match.ts 96 lines1// Pure placeholder matching: precompiled regexes, draft scan -> tokens. Zero I/O; bit-identical to brewtools for prefix `++`.
2
3export const DEFAULT_PREFIX = '++'
4
5export type PlaceholderToken = { text: string; name: string; isKnown: boolean; start: number; end: number }
6// Same shape as types/index.d.ts PlaceholderView: escapedBy = the first escape marker, set with isEscaped.
7export type PlaceholderView = { tokens: PlaceholderToken[]; isEscaped?: true; escapedBy?: string }
8export type PrefixCheck = { prefix: string; warning: string | null }
9export type NameKind = 'word' | 'symbol'
10
11export type Matcher = { name: string; kind: NameKind; scan: RegExp }
12export type Matchers = { prefix: string; byName: ReadonlyMap<string, Matcher>; unknown: RegExp; escape: RegExp }
13
14const PREFIX_FIX = '/config -> Placeholder prefix'
15const PREFIX_RE = /^[!-/:-@[-^`{-~]{2,8}$/
16const WORD_NAME = /^[A-Za-z0-9_]{1,32}$/
17const SYMBOL_NAME = /^[!-/:-@[-^`{-~]+$/
18
19// Invalid prefix -> `++` plus a warning; a leading `/` is allowed but warned (slash-command clash).
20export function validatePrefix(raw: unknown): PrefixCheck {
21 if (raw === undefined) return { prefix: DEFAULT_PREFIX, warning: null }
22 if (typeof raw !== 'string' || !PREFIX_RE.test(raw)) {
23 return { prefix: DEFAULT_PREFIX, warning: `prefix must be 2-8 ASCII punctuation characters (not _), using ${DEFAULT_PREFIX} · change: ${PREFIX_FIX}` }
24 }
25 return { prefix: raw, warning: raw.startsWith('/') ? `prefix starting with / clashes with slash commands · change: ${PREFIX_FIX}` : null }
26}
27
28export function nameKind(name: string): NameKind | null {
29 if (WORD_NAME.test(name)) return 'word'
30 if (SYMBOL_NAME.test(name)) return 'symbol'
31 return null
32}
33
34const escRe = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
35const escClass = (s: string): string => s.replace(/[\\\][^-]/g, '\\$&')
36// Class of what glues to a symbol token or a marker: letters, digits, marks, `_` and `chars`.
37const glue = (chars: string): string => `[\\p{L}\\p{N}\\p{M}_${escClass([...new Set(chars)].join(''))}]`
38
39function build(prefix: string, name: string, kind: NameKind): Matcher {
40 const token = escRe(prefix + name)
41 if (kind === 'word') {
42 const src = `(?<![\\w${escClass(prefix)}])${token}(?![\\w])`
43 return { name, kind, scan: new RegExp(src, 'gi') }
44 }
45 const cls = glue(prefix + name)
46 const src = `(?<!${cls})${token}(?!${cls})`
47 return { name, kind, scan: new RegExp(src, 'gu') }
48}
49
50// Names are keyed lowercase; a name that is neither word nor symbol is skipped.
51export function compileMatchers(prefix: string, names: Iterable<string>): Matchers {
52 const byName = new Map<string, Matcher>()
53 for (const raw of names) {
54 const name = raw.toLowerCase()
55 const kind = nameKind(name)
56 if (kind === null || byName.has(name)) continue
57 byName.set(name, build(prefix, name, kind))
58 }
59 const unknown = new RegExp(`(?<![\\w${escClass(prefix)}])${escRe(prefix)}(\\w+)`, 'g')
60 return { prefix, byName, unknown, escape: escapeScan(prefix) }
61}
62
63// `P/` and `P\`: either one anywhere in a message sends it as typed, every placeholder off.
64export const escapeMarkers = (prefix: string): [string, string] => [`${prefix}/`, `${prefix}\\`]
65
66// A marker glued on its left to a letter, digit, mark, `_` or a prefix char is none (`c++/java`, `+++/`).
67export const escapeScan = (prefix: string): RegExp => new RegExp(`(?<!${glue(prefix)})(?:${escapeMarkers(prefix).map(escRe).join('|')})`, 'gu')
68
69// First escape marker in a text, null = not escaped; compiled matchers reuse their regex (`match`, never `exec`: it is `g`).
70export function markerOf(src: Matchers | string, text: string): string | null {
71 const prefix = typeof src === 'string' ? src : src.prefix
72 if (!text.includes(prefix)) return null
73 return text.match(typeof src === 'string' ? escapeScan(prefix) : src.escape)?.[0] ?? null
74}
75
76export const isEscaped = (src: Matchers | string, text: string): boolean => markerOf(src, text) !== null
77
78// Draft -> known and unknown tokens sorted by start; unknown = standalone `P\w+` with an undefined name.
79export function scanDraft(ms: Matchers, text: string): PlaceholderView {
80 if (!text.includes(ms.prefix)) return { tokens: [] }
81 const tokens: PlaceholderToken[] = []
82 for (const m of ms.byName.values()) {
83 for (const hit of text.matchAll(m.scan)) {
84 const start = hit.index ?? 0
85 tokens.push({ text: hit[0], name: m.name, isKnown: true, start, end: start + hit[0].length })
86 }
87 }
88 for (const hit of text.matchAll(ms.unknown)) {
89 const name = (hit[1] ?? '').toLowerCase()
90 if (ms.byName.has(name)) continue
91 const start = hit.index ?? 0
92 tokens.push({ text: hit[0], name, isKnown: false, start, end: start + hit[0].length })
93 }
94 return { tokens: tokens.sort((a, b) => a.start - b.start) }
95}
96hooks/lib/compiled.ts 16 lines1// Compiled matchers for the editor, band and inline expansion; the context assembly itself lives in hooks/inject.mjs.
2
3import type { Def } from './defs'
4import { DEFAULT_PREFIX, compileMatchers, type Matchers } from './match'
5
6export type Compiled = { prefix: string; defs: readonly Def[]; matchers: Matchers }
7
8export function compileDefs(defs: readonly Def[], prefix = DEFAULT_PREFIX): Compiled {
9 return { prefix, defs, matchers: compileMatchers(prefix, defs.map((d) => d.name)) }
10}
11
12// Recompile only when the defs array (registry identity) or the prefix changed.
13export function memoCompile(prev: Compiled | null, defs: readonly Def[], prefix: string): Compiled {
14 return prev !== null && prev.defs === defs && prev.prefix === prefix ? prev : compileDefs(defs, prefix)
15}
16hooks/lib/defs.ts 421 lines1// Definition parsing (pure) + layered registry. File access only through an injected Io, never `$`.
2import type { EditorEntry } from './editor'
3import { nameKind } from './match'
4
5export type Insert = 'context' | 'inline'
6
7export type DefMeta = {
8 name?: string
9 description?: string
10 insert?: Insert
11 order?: number
12 group?: string
13 priority?: number
14 header?: string
15 legacy?: string
16 // Raw values, read only for the 6.9.5 migration warnings.
17 when?: string
18 plan?: string
19}
20
21// `skip` = the file cannot be read as a definition (front matter never closes): the loader drops it.
22export type Parsed = { meta: DefMeta; text: string; hasFrontMatter: boolean; issues: string[]; skip?: true }
23
24export type Def = {
25 name: string
26 body: string
27 insert: Insert
28 order: number
29 group?: string
30 priority: number
31 header: string
32 legacy?: string
33 description?: string
34 // A `<name>.plan.md` part: its text is added to the name's normal text in plan mode.
35 isPlan: boolean
36}
37
38// Text inside all ``` or ~~~ fences, blank-line joined; no fence -> whole raw trimmed. 1:1 port of brewtools.
39export function extractFenced(raw: string): string {
40 const blocks: string[] = []
41 const re = /(?:```|~~~)[^\n]*\n([\s\S]*?)\n?(?:```|~~~)/g
42 let m: RegExpExecArray | null
43 while ((m = re.exec(raw)) !== null) {
44 blocks.push((m[1] ?? '').replace(/\n+$/, ''))
45 }
46 if (blocks.length === 0) return raw.trim()
47 return blocks.join('\n\n').trim()
48}
49
50type Split = { fm: string; body: string }
51
52const OPEN = /^(?:[ \t]*\r?\n)*---[ \t]*(?:\r?\n|$)/
53
54// Front matter = first non-blank line `---` (after an optional BOM) up to the next `---` line; no opening line -> null, no closing line -> 'unclosed'.
55function splitFrontMatter(raw: string): Split | 'unclosed' | null {
56 const src = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw
57 const open = OPEN.exec(src)
58 if (!open) return null
59 const start = open[0].length
60 let pos = start
61 while (pos <= src.length) {
62 const nl = src.indexOf('\n', pos)
63 const end = nl === -1 ? src.length : nl
64 if (/^---[ \t]*$/.test(src.slice(pos, end).replace(/\r$/, ''))) {
65 return { fm: src.slice(start, pos), body: nl === -1 ? '' : src.slice(nl + 1) }
66 }
67 if (nl === -1) break
68 pos = nl + 1
69 }
70 return 'unclosed'
71}
72
73function scalar(value: string): string {
74 const dq = /^"((?:[^"\\]|\\.)*)"/.exec(value)
75 if (dq) {
76 try {
77 return JSON.parse(dq[0]) as string
78 } catch {
79 return dq[1] ?? ''
80 }
81 }
82 const sq = /^'((?:[^']|'')*)'/.exec(value)
83 if (sq) return (sq[1] ?? '').replace(/''/g, "'")
84 return value.replace(/\s+#.*$/, '').trim()
85}
86
87const INT = /^-?\d+$/
88
89// Tolerant subset: `key: scalar` lines, "double"/'single'/bare scalars; unknown keys and bad values -> issues, never throws.
90export function parseFrontMatter(fm: string): { meta: DefMeta; issues: string[] } {
91 const meta: DefMeta = {}
92 const issues: string[] = []
93 fm.split('\n').forEach((rawLine, i) => {
94 const line = rawLine.replace(/\r$/, '')
95 if (line.trim() === '' || line.trimStart().startsWith('#')) return
96 const kv = /^([A-Za-z_][\w-]*)[ \t]*:[ \t]*(.*)$/.exec(line)
97 if (!kv) {
98 issues.push(`line ${i + 1}: not a key: value pair`)
99 return
100 }
101 const key = kv[1] ?? ''
102 const value = scalar(kv[2] ?? '')
103 switch (key) {
104 case 'name':
105 case 'description':
106 case 'group':
107 case 'header':
108 case 'legacy':
109 case 'when':
110 case 'plan':
111 meta[key] = value
112 break
113 case 'insert':
114 if (value === 'context' || value === 'inline') meta.insert = value
115 else issues.push(`insert: '${value}' is not context|inline`)
116 break
117 case 'order':
118 case 'priority':
119 if (INT.test(value)) meta[key] = Number(value)
120 else issues.push(`${key}: '${value}' is not an integer`)
121 break
122 default:
123 issues.push(`unknown key '${key}'`)
124 }
125 })
126 return { meta, issues }
127}
128
129// Mod-native definition file: optional front matter, body through extractFenced (no front matter -> whole file).
130export function parseDefinition(raw: string): Parsed {
131 const split = splitFrontMatter(raw)
132 if (split === 'unclosed') return { meta: {}, text: '', hasFrontMatter: true, issues: ['front matter is not closed'], skip: true }
133 if (split === null) return { meta: {}, text: extractFenced(raw), hasFrontMatter: false, issues: [] }
134 const { meta, issues } = parseFrontMatter(split.fm)
135 return { meta, text: extractFenced(split.body), hasFrontMatter: true, issues }
136}
137
138// Brewtools override file: never front matter, the whole file is the fenced source.
139export function parseLegacy(raw: string): Parsed {
140 return { meta: {}, text: extractFenced(raw), hasFrontMatter: false, issues: [] }
141}
142
143// Per-field inheritance: parsed meta wins, then base, then built-ins. No name anywhere -> null.
144// isPlan comes only from base (the `x.plan` stem or the lower layer's def of that key), never from meta.
145export function toDef(parsed: Parsed, base?: Partial<Def>): Def | null {
146 const m = parsed.meta
147 const name = m.name ?? base?.name
148 if (name === undefined || name === '') return null
149 const group = m.group ?? base?.group
150 const legacy = m.legacy ?? base?.legacy
151 const description = m.description ?? base?.description
152 return {
153 name,
154 body: parsed.text,
155 insert: m.insert ?? base?.insert ?? 'context',
156 order: m.order ?? base?.order ?? 100,
157 priority: m.priority ?? base?.priority ?? 0,
158 header: m.header ?? base?.header ?? '',
159 ...(group === undefined ? {} : { group }),
160 ...(legacy === undefined ? {} : { legacy }),
161 ...(description === undefined ? {} : { description }),
162 isPlan: base?.isPlan ?? false,
163 }
164}
165
166// ---- Layers: lowest to highest priority; a layer file replaces the one below it, field by field.
167
168export type IoEntry = { name: string; kind: 'file' | 'dir' | 'other'; size: number; mtimeMs: number; isLink: boolean }
169export type Io = {
170 exists: (path: string) => Promise<boolean>
171 list: (path: string) => Promise<readonly IoEntry[]>
172 read: (path: string) => Promise<string>
173}
174
175export type LayerKind = 'native' | 'legacy'
176export type LayerSpec = { id: string; kind: LayerKind; dir: string }
177// dir = the layer's real dir, named in a legacy file's warning.
178export type LayerFiles = { id: string; kind: LayerKind; dir?: string; files: ReadonlyMap<string, string> }
179export type Roots = { pluginRoot: string; root?: string; configDir?: string }
180export type Resolved = { defs: Def[]; issues: string[]; skipped: string[]; sources: Map<string, string> }
181export type Registry = { defs: readonly Def[]; issues: readonly string[]; skipped: readonly string[]; sources: ReadonlyMap<string, string> }
182
183const trimSep = (p: string): string => (p.length > 1 ? p.replace(/[\\/]+$/, '') : p)
184
185// Absolute POSIX paths get `.`/`..`/double-slash folding (path.resolve); anything else only loses trailing separators.
186export function normalizeDir(p: string): string {
187 if (!p.startsWith('/')) return trimSep(p)
188 const out: string[] = []
189 for (const seg of p.split('/')) {
190 if (seg === '' || seg === '.') continue
191 if (seg === '..') out.pop()
192 else out.push(seg)
193 }
194 return '/' + out.join('/')
195}
196
197// Port of brewtools configDir(): CLAUDE_CONFIG_DIR when non-empty, else <home>/.claude; no home -> undefined.
198export function configDirOf(configEnv: string | undefined, home: string | undefined): string | undefined {
199 if (configEnv !== undefined && configEnv !== '') return normalizeDir(configEnv)
200 if (home === undefined || home === '') return undefined
201 return `${trimSep(home)}/.claude`
202}
203
204// Plugin defaults, then per scope the brewtools legacy dir under the mod's own dir (global below project).
205export function layerSpecs(r: Roots): LayerSpec[] {
206 const specs: LayerSpec[] = [{ id: 'default', kind: 'native', dir: `${trimSep(r.pluginRoot)}/placeholders` }]
207 if (r.configDir !== undefined) {
208 const cfg = trimSep(r.configDir)
209 specs.push({ id: 'global-legacy', kind: 'legacy', dir: `${cfg}/manager/prompts` })
210 specs.push({ id: 'global', kind: 'native', dir: `${cfg}/placeholders` })
211 }
212 if (r.root !== undefined) {
213 const root = trimSep(r.root)
214 specs.push({ id: 'project-legacy', kind: 'legacy', dir: `${root}/.claude/brewtools/manager/prompts` })
215 specs.push({ id: 'project', kind: 'native', dir: `${root}/.claude/placeholders` })
216 }
217 return specs
218}
219
220// Base of a native file without a lower layer: `x.plan` -> name x, plan part.
221export function stemBase(stem: string): Partial<Def> {
222 return stem.endsWith('.plan') && stem.length > 5 ? { name: stem.slice(0, -5), isPlan: true } : { name: stem }
223}
224
225// One 6.9.5 migration warning per file: `when` is gone, a plan part needs `plan: add`, `plan:` belongs in a plan file.
226function modeIssue(def: Def, meta: DefMeta, isLegacy: boolean): string | null {
227 const plan = `${def.name.toLowerCase()}.plan.md`
228 if (def.isPlan && isLegacy) return `brewtools file: its text is added in plan mode; to clear this, move it to placeholders/${plan} with plan: add`
229 if (def.isPlan) return meta.plan === 'add' ? null : 'no plan: add; its text is added in plan mode'
230 if (meta.when !== undefined && meta.when !== 'always') return `when: ${meta.when} is gone; sent in every mode`
231 return meta.plan === undefined ? null : `plan: is for ${plan}; ignored`
232}
233
234const partId = (d: Def): string => `${d.name.toLowerCase()}${d.isPlan ? '.plan' : ''}`
235
236// Layers low to high, keyed by lower-case stem; a legacy file maps to the key whose def carries that `legacy`. Unusable files are skipped.
237// D1: a plan part with no normal def of its name in any layer is sent in every mode; a shadowed file's mode warning says it is not sent.
238export function resolveDefs(layers: readonly LayerFiles[]): Resolved {
239 const cur = new Map<string, Def>()
240 const sources = new Map<string, string>()
241 const issues: string[] = []
242 const skipped: string[] = []
243 const legacyStem = new Map<string, string>()
244 // Served file per key and the index of its mode warning (-1 = none), so an orphan warning replaces it.
245 const served = new Map<string, { where: string; at: number }>()
246 const put = (id: string, where: string, key: string, parsed: Parsed, base: Partial<Def> | undefined, isLegacy = false): void => {
247 for (const i of parsed.issues) issues.push(`${where}: ${i}`)
248 const def = parsed.skip === true ? null : toDef(parsed, base)
249 if (def === null) {
250 if (parsed.skip !== true) issues.push(`${where}: no name`)
251 skipped.push(where)
252 return
253 }
254 if (nameKind(def.name.toLowerCase()) === null) {
255 issues.push(`${where}: name '${def.name}' is not a placeholder name (1-32 of A-Z a-z 0-9 _, or punctuation only)`)
256 skipped.push(where)
257 return
258 }
259 const warn = modeIssue(def, parsed.meta, isLegacy)
260 if (warn !== null) issues.push(`${where}: ${warn}`)
261 served.set(key, { where, at: warn === null ? -1 : issues.length - 1 })
262 cur.set(key, def)
263 sources.set(key, id)
264 if (def.legacy !== undefined) legacyStem.set(def.legacy, key)
265 }
266 for (const layer of layers) {
267 for (const [file, raw] of [...layer.files].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))) {
268 if (layer.kind === 'native') {
269 const key = file.toLowerCase()
270 put(layer.id, `${layer.id}/${file}.md`, key, parseDefinition(raw), cur.get(key) ?? stemBase(key))
271 continue
272 }
273 const stem = legacyStem.get(file)
274 if (stem !== undefined) put(layer.id, `${layer.dir ?? layer.id}/${file}.md`, stem, parseLegacy(raw), cur.get(stem), true)
275 }
276 }
277 const normal = new Set([...cur.values()].filter((d) => !d.isPlan).map((d) => d.name.toLowerCase()))
278 for (const [key, d] of cur) {
279 const name = d.name.toLowerCase()
280 if (!d.isPlan || normal.has(name)) continue
281 cur.set(key, { ...d, isPlan: false })
282 const s = served.get(key)
283 const msg = `${s?.where ?? key}: no ${name}.md; sent in every mode`
284 if (s !== undefined && s.at >= 0) issues[s.at] = msg
285 else {
286 issues.push(msg)
287 if (s !== undefined) served.set(key, { ...s, at: issues.length - 1 })
288 }
289 }
290 // Per name and part the first context def is sent, else the first def (sent.ts parts, inline.ts inlineBodies).
291 const winner = new Map<string, string>()
292 for (const isCtx of [true, false]) {
293 for (const [key, d] of cur) {
294 if ((!isCtx || d.insert === 'context') && !winner.has(partId(d))) winner.set(partId(d), key)
295 }
296 }
297 for (const [key, d] of cur) {
298 const won = winner.get(partId(d))
299 const s = served.get(key)
300 if (won === undefined || won === key || s === undefined || s.at < 0) continue
301 issues[s.at] = `${s.where}: shadowed by ${served.get(won)?.where ?? won}; not sent`
302 }
303 return { defs: [...cur.values()], issues, skipped, sources }
304}
305
306// ---- mtime cache: a layer is re-read only when its listing (name, size, mtime) changed.
307
308type Cached = { sig: string; raw: string; error?: string }
309export type RegistryCache = {
310 files: Map<string, Map<string, Cached>>
311 layerSig: Map<string, string>
312 legacyNames: ReadonlySet<string>
313 registry: Registry | null
314}
315
316export const newRegistryCache = (): RegistryCache => ({ files: new Map(), layerSig: new Map(), legacyNames: new Set(), registry: null })
317
318const listSig = (es: readonly IoEntry[]): string =>
319 es.map((en) => `${en.name}:${en.size}:${en.mtimeMs}:${en.isLink ? 'L' : 'F'}`).sort().join('|')
320
321export const FILES_GONE = 'plugin files removed (updated?) · run /reload-plugins'
322
323// The plugin's own placeholders/ folder is missing or holds no .md file (an rm -rf mid-walk): its root was deleted or replaced.
324export class PluginFilesGone extends Error {
325 constructor() {
326 super(FILES_GONE)
327 }
328}
329
330// A listing failure, a missing or unreadable shipped default rejects and leaves the cache untouched (the caller fails open); an unreadable user file is skipped.
331export async function loadRegistry(io: Io, roots: Roots, cache: RegistryCache): Promise<Registry> {
332 const layers: LayerFiles[] = []
333 const nextFiles = new Map<string, Map<string, Cached>>()
334 const nextSig = new Map<string, string>()
335 const unreadable: string[] = []
336 let legacyNames = cache.legacyNames
337 let changed = cache.registry === null
338
339 for (const spec of layerSpecs(roots)) {
340 const listing = (await io.exists(spec.dir)) ? await io.list(spec.dir) : []
341 const entries = listing.filter((en) => {
342 if (en.kind === 'dir' || en.name.startsWith('.') || !en.name.endsWith('.md')) return false
343 return spec.kind === 'native' || legacyNames.has(en.name.slice(0, -3))
344 })
345 if (spec.id === 'default' && entries.length === 0) throw new PluginFilesGone()
346 const sig = listSig(entries)
347 const prev = cache.files.get(spec.id)
348 const kept = new Map<string, Cached>()
349 if (cache.layerSig.get(spec.id) !== sig) changed = true
350 for (const en of entries) {
351 const stem = en.name.slice(0, -3)
352 const fsig = `${en.size}:${en.mtimeMs}`
353 const hit = prev?.get(stem)
354 if (hit !== undefined && hit.sig === fsig && !en.isLink) {
355 kept.set(stem, hit)
356 continue
357 }
358 try {
359 const raw = await io.read(`${spec.dir}/${en.name}`)
360 if (hit?.error !== undefined || hit?.raw !== raw) changed = true
361 kept.set(stem, { sig: fsig, raw })
362 } catch (err) {
363 if (spec.id === 'default') throw err
364 const error = err instanceof Error ? err.message : String(err)
365 if (hit?.error !== error) changed = true
366 kept.set(stem, { sig: fsig, raw: '', error })
367 }
368 }
369 for (const [stem, c] of kept) if (c.error !== undefined) unreadable.push(`${spec.id}/${stem}.md: unreadable (${c.error})`)
370 nextFiles.set(spec.id, kept)
371 nextSig.set(spec.id, sig)
372 layers.push({ id: spec.id, kind: spec.kind, dir: spec.dir, files: new Map([...kept].filter(([, v]) => v.error === undefined).map(([k, v]) => [k, v.raw])) })
373 if (spec.id === 'default' && changed) {
374 const names = new Set<string>()
375 for (const raw of kept.values()) {
376 const legacy = parseDefinition(raw.raw).meta.legacy
377 if (legacy !== undefined && legacy !== '') names.add(legacy)
378 }
379 legacyNames = names
380 }
381 }
382
383 if (!changed && cache.registry !== null) return cache.registry
384 const out = resolveDefs(layers)
385 const registry: Registry = {
386 defs: out.defs,
387 issues: [...out.issues, ...unreadable],
388 skipped: [...out.skipped, ...unreadable.map((u) => u.slice(0, u.indexOf(': ')))],
389 sources: out.sources,
390 }
391 cache.files = nextFiles
392 cache.layerSig = nextSig
393 cache.legacyNames = legacyNames
394 cache.registry = registry
395 return registry
396}
397
398const MAX_SHOWN = 5
399
400// One session toast text: issue count, the first issue and the skipped files; null = nothing to say.
401export function issuesMessage(reg: Pick<Registry, 'issues' | 'skipped'>): string | null {
402 if (reg.issues.length === 0) return null
403 const more = reg.skipped.length > MAX_SHOWN ? ` and ${reg.skipped.length - MAX_SHOWN} more` : ''
404 const skipped = reg.skipped.length === 0 ? '' : `; skipped ${reg.skipped.slice(0, MAX_SHOWN).join(', ')}${more}`
405 return `${reg.issues.length} definition issue(s), first: ${reg.issues[0]}${skipped} · all: /placeholders status`
406}
407
408// Editor/band names: one entry per name, first-seen order; the first normal def wins (every plan part has one after resolveDefs).
409export function toEditorEntries(defs: readonly Def[]): EditorEntry[] {
410 const pick = new Map<string, Def>()
411 for (const d of defs) {
412 const key = d.name.toLowerCase()
413 const cur = pick.get(key)
414 if (cur === undefined || (cur.isPlan && !d.isPlan)) pick.set(key, d)
415 }
416 return [...pick.values()].map((d) => {
417 const base = { name: d.name, body: d.body, ...(d.insert === 'inline' ? { isInline: true } : {}) }
418 return d.description === undefined ? base : { ...base, description: d.description }
419 })
420}
421hooks/lib/mode.ts 19 lines1// Plan-mode state written by hooks/inject.mjs: <plugin root>/.state/mode-<session id>.json = {mode, ts}.
2
3const SESSION_ID = /^[A-Za-z0-9_-]+$/
4
5// Null = no valid path for this id (never read a file outside .state).
6export function modeStatePath(pluginRoot: string, sessionId: unknown): string | null {
7 return typeof sessionId === 'string' && SESSION_ID.test(sessionId) ? `${pluginRoot.replace(/[\\/]+$/, '')}/.state/mode-${sessionId}.json` : null
8}
9
10// True = plan, false = any other mode; null = unreadable or no string mode (the caller keeps its last value).
11export function planFromState(raw: string): boolean | null {
12 try {
13 const mode: unknown = (JSON.parse(raw) as { mode?: unknown } | null)?.mode
14 return typeof mode === 'string' ? mode === 'plan' : null
15 } catch {
16 return null
17 }
18}
19hooks/lib/band.tsx 478 lines1// Pure band rendering: view + registry entries + sent texts -> rows -> tree. Zero I/O; atoms and `$` stay in register.ts.
2import type { ElementTable, RenderElement } from 'claude-code'
3import { FILES_GONE } from './defs'
4import { KNOWN_COLOR, PLAN_COLOR, UNKNOWN_COLOR, type CaretFocus, type EditorEntry } from './editor'
5import type { PlaceholderView } from './match'
6import { PLAN_LABEL, REASON, escapedReason, type PlanParts, type Sent } from './sent'
7
8// body = exact text the token sends; reason = why it is not sent; plan = the text its `<name>.plan.md` adds in plan mode.
9export type BandRow = { text: string; name: string; isKnown: boolean; description: string; body: string; isInline?: boolean; reason?: string; plan?: string }
10export type BandMode = 'hidden' | 'escaped' | 'focus' | 'compact'
11// mode = bandState's pick; marker = the escape typed; budget = focus band and hover rows, autoBudget = compact rows, queryBudget = rows once `?` closes the menu; columns = bodyColumns.
12export type BandOptions = {
13 mode: Exclude<BandMode, 'hidden'>
14 focus: CaretFocus
15 prefix: string
16 marker: string
17 isPlan: boolean
18 isGone: boolean
19 budget: number
20 autoBudget: number
21 queryBudget: number
22 columns: number
23 // The `P<name>?` hand-off runs (the build has the mod tools): the cut row names it.
24 hasQuery: boolean
25}
26export type BandUi = Pick<ElementTable<'terminal'>, 'Box' | 'Text'>
27
28// Default TUI: maxRows = terminal height and the prompt box + footer take 8 rows more (45-row probe: 37 fit, 38 clip); +4 for a wrapped draft or a spinner.
29const BAND_RESERVE = 12
30const BAND_MAX = 30
31const BAND_MIN = 6
32const AUTO_MAX = 15
33const AUTO_SHARE = 0.4
34// Up to this many token rows show their bodies in the compact band; more get hover bodies.
35const AUTO_MAX_ROWS = 2
36// An open typeahead reserves rows under the box that maxRows does not subtract (80x24: 6 rows fit, 120x40: 14).
37const MENU_RESERVE = 6
38const MENU_MIN = 3
39export const FOCUS_MAX = 15
40
41// Focus band: fullscreen -> the engine's bottom-slot rows, else the terminal height less the reserve; always 6..30 (fullscreen up to maxRows).
42export const bandBudget = (maxRows: number, isFullscreen: boolean): number =>
43 isFullscreen ? Math.min(BAND_MAX, maxRows) : Math.max(BAND_MIN, Math.min(BAND_MAX, maxRows - BAND_RESERVE))
44
45// Compact band: min(15, 40% of the terminal rows), at least 6, never above the focus budget.
46export const autoBudget = (maxRows: number, isFullscreen: boolean): number =>
47 Math.min(bandBudget(maxRows, isFullscreen), isFullscreen ? AUTO_MAX : Math.max(BAND_MIN, Math.min(AUTO_MAX, Math.floor(maxRows * AUTO_SHARE))))
48
49// The budgets; outside fullscreen an open menu caps budget and autoBudget, else the band's top rows are pushed into scrollback.
50export function budgets(maxRows: number, isFullscreen: boolean, isMenuOpen: boolean): { budget: number; autoBudget: number; queryBudget: number } {
51 const cap = isMenuOpen && !isFullscreen ? Math.max(MENU_MIN, Math.floor(maxRows / 2) - MENU_RESERVE) : Number.POSITIVE_INFINITY
52 const open = bandBudget(maxRows, isFullscreen)
53 return { budget: Math.min(open, cap), autoBudget: Math.min(autoBudget(maxRows, isFullscreen), cap), queryBudget: open }
54}
55
56// Rows a tree drawn beneath takes: Text or string 1, column Box the sum, row Box its tallest child; core's own drawing 0.
57export function treeRows(node: unknown): number {
58 if (typeof node === 'string') return 1
59 if (node === null || typeof node !== 'object') return 0
60 const el = node as { type?: unknown; props?: { flexDirection?: unknown; display?: unknown }; children?: unknown[] }
61 if (el.type === 'engine' || el.props?.display === 'none') return 0
62 if (el.type !== 'Box') return 1
63 const rows = (el.children ?? []).map(treeRows)
64 return String(el.props?.flexDirection ?? '').startsWith('column') ? rows.reduce((a, b) => a + b, 0) : Math.max(0, ...rows)
65}
66
67// Precedence: hidden > escaped > focus > compact.
68export function bandState(p: { hasSurvey: boolean; draft: string | null; view: PlaceholderView; focus: string | null }): BandMode {
69 if (p.hasSurvey || p.draft === '') return 'hidden'
70 if (p.view.isEscaped === true) return 'escaped'
71 if (p.view.tokens.length === 0) return 'hidden'
72 return p.focus !== null && p.view.tokens.some((t) => t.name === p.focus) ? 'focus' : 'compact'
73}
74
75const ASCII = /^[\x20-\x7e]*$/
76// East Asian Wide/Fullwidth blocks, sorted and disjoint; escapes only, as editors NFC-fold a raw U+F900 to U+8C48.
77const WIDE = /[\p{Emoji_Presentation}\u1100-\u115F\u2E80-\uA4CF\uA960-\uA97C\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F300}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u
78const ZERO = /[\p{M}\u200B-\u200D\uFE00-\uFE0F]/u
79const PICTO = /\p{Extended_Pictographic}/u
80const VS16 = '\uFE0F'
81
82// Terminal cells of a text: wide CJK and emoji 2, combining marks, ZWJ and VS16 0, the rest 1; VS16 turns a text-style pictograph (☺) to 2.
83export function cells(s: string): number {
84 if (ASCII.test(s)) return s.length
85 let n = 0
86 let prev = ''
87 for (const ch of s) {
88 if (ch === VS16 && PICTO.test(prev) && !WIDE.test(prev)) n += 1
89 n += ZERO.test(ch) ? 0 : WIDE.test(ch) ? 2 : 1
90 prev = ch
91 }
92 return n
93}
94
95// One line as rows of at most `width` cells: greedy by words, a word wider than a row broken hard; each row is drawn truncate-end.
96export function wrapRows(line: string, width: number): string[] {
97 if (width < 1 || cells(line) <= width) return [line]
98 const rows: string[] = []
99 let cur = ''
100 let col = 0
101 for (const m of line.matchAll(/ +|[^ ]+/g)) {
102 const seg = m[0]
103 const w = cells(seg)
104 if (col + w <= width) {
105 cur += seg
106 col += w
107 continue
108 }
109 if (seg.startsWith(' ')) {
110 rows.push(cur.trimEnd())
111 cur = ''
112 col = 0
113 continue
114 }
115 if (col > 0) rows.push(cur.trimEnd())
116 cur = ''
117 col = 0
118 for (const ch of seg) {
119 const cw = cells(ch)
120 if (col + cw > width && col > 0) {
121 rows.push(cur)
122 cur = ''
123 col = 0
124 }
125 cur += ch
126 col += cw
127 }
128 }
129 // Trailing spaces past the width leave no blank row of their own.
130 if (cur.trimEnd() !== '' || rows.length === 0) rows.push(cur.trimEnd())
131 return rows
132}
133
134// Text cut to `room` cells with a trailing ellipsis; nothing when there is no room.
135export function clip(s: string, room: number): string {
136 if (cells(s) <= room) return s
137 if (room < 1) return ''
138 let out = ''
139 let used = 0
140 for (const ch of s) {
141 const w = cells(ch)
142 if (used + w > room - 1) break
143 out += ch
144 used += w
145 }
146 return `${out}…`
147}
148
149// Rows a body takes at `width`: its source lines as they are (the text exactly as sent), each wrapped.
150const rowsOf = (body: string, width: number): number => (body === '' ? 0 : body.split('\n').reduce((n, l) => n + wrapRows(l, width).length, 0))
151// Rows a drawn body needs: a plan note (outside plan mode) adds one; plan mode's `adds` mark takes the blank separator row.
152const needOf = (r: BandRow, isPlan: boolean, width: number): number => rowsOf(r.body, width) + (r.plan !== undefined && !isPlan ? 1 : 0)
153
154// Rows per body, never more than `free` in all: a body needing less leaves its spare rows to the rest; each gets one while rows are left.
155export function shareRows(needs: readonly number[], free: number): number[] {
156 const out = needs.map(() => 0)
157 const order = needs.map((_, i) => i).sort((a, b) => (needs[a] ?? 0) - (needs[b] ?? 0))
158 let left = free
159 order.forEach((i, k) => {
160 const give = left <= 0 ? 0 : Math.min(needs[i] ?? 0, Math.max(1, Math.floor(left / (order.length - k))))
161 out[i] = give
162 left -= give
163 })
164 return out
165}
166
167// Body rows: sent now = bold theme text colour (a plan-mode addition: bold plan colour), else dim; plan-mode labels in the plan colour.
168const SENT_STYLE = { color: 'text', bold: true } as const
169const DIM_STYLE = { dimColor: true } as const
170const PLAN_STYLE = { color: PLAN_COLOR } as const
171const PLAN_SENT_STYLE = { color: PLAN_COLOR, bold: true } as const
172type BodyStyle = typeof SENT_STYLE | typeof DIM_STYLE | typeof PLAN_SENT_STYLE
173const styleOf = (isSent: boolean, isAddition = false): BodyStyle => (!isSent ? DIM_STYLE : isAddition ? PLAN_SENT_STYLE : SENT_STYLE)
174const plural = (n: number, word: string): string => (n === 1 ? word : `${word}s`)
175const nMore = (n: number, word: string): string => `... ${n} more ${plural(n, word)}`
176
177// A row piece: plain = dim label, act = what to type or do, key = a key to press, tok = a placeholder name.
178type Part = string | { act: string } | { key: string } | { tok: string; isKnown: boolean }
179// Token names: placeholder colour (unknown: warning), bold; actions: theme text colour, underlined; keys: theme text colour.
180const tokStyle = (isKnown: boolean) => ({ color: isKnown ? KNOWN_COLOR : UNKNOWN_COLOR, bold: true }) as const
181const ACT_STYLE = { color: 'text', underline: true } as const
182const KEY_STYLE = { color: 'text' } as const
183type Style = typeof DIM_STYLE | typeof ACT_STYLE | typeof KEY_STYLE | ReturnType<typeof tokStyle>
184const pieceOf = (p: Part): [Style, string] =>
185 typeof p === 'string' ? [DIM_STYLE, p] : 'act' in p ? [ACT_STYLE, p.act] : 'key' in p ? [KEY_STYLE, p.key] : [tokStyle(p.isKnown), p.tok]
186const partsCells = (parts: readonly Part[]): number => cells(parts.map((p) => pieceOf(p)[1]).join(''))
187
188// One row of styled pieces, cut at the end as a whole.
189function partsRow(Text: BandUi['Text'], key: string, parts: readonly Part[]): RenderElement {
190 return (
191 <Text key={key} wrap="truncate-end">
192 {parts.map((p, i) => {
193 const [style, text] = pieceOf(p)
194 return (
195 <Text key={`${key}:${i}`} {...style}>
196 {text}
197 </Text>
198 )
199 })}
200 </Text>
201 )
202}
203
204// What a cut row offers: the show command (plus the `P<name>?` hand-off where it runs), or `?` while the menu caps the rows.
205type More = { kind: 'show'; token: string; hasQuery: boolean } | { kind: 'query'; token: string } | null
206
207// The cut row: the widest variant that fits `width`; the hand-off goes first, the show command is never cut while it fits alone.
208function cutParts(left: number, more: More, width: number): Part[] {
209 const lines = nMore(left, 'line')
210 if (more === null) return [lines]
211 if (more.kind === 'query') return [`${lines} · `, { act: `type ? after ${more.token}` }, ' to see all']
212 const show: Part = { act: `/placeholders show ${more.token}` }
213 const tiers: Part[][] = [
214 ...(more.hasQuery ? [[`${lines} · whole text: `, show, ' or ', { act: `${more.token}?` }, ' alone ', { key: '[Enter]' }]] : []),
215 [`${lines} · whole text: `, show],
216 [`${lines} · `, show],
217 ]
218 return tiers.find((t) => partsCells(t) <= width) ?? [show]
219}
220
221// Whole source lines of a body while their pre-wrapped rows fit `rows`; a cut adds one row counting the source lines left and what `more` offers.
222function bodyRows(Text: BandUi['Text'], body: string, rows: number, key: string, width: number, more: More, style: BodyStyle): RenderElement[] {
223 const lines = body.split('\n').map((l) => wrapRows(l, width))
224 const total = lines.reduce((n, l) => n + l.length, 0)
225 const room = total > rows ? rows - 1 : total
226 let take = 0
227 let used = 0
228 for (const l of lines) {
229 if (used + l.length > room) break
230 used += l.length
231 take++
232 }
233 const out = lines.slice(0, take).flatMap((parts, i) =>
234 parts.map((p, j) => (
235 <Text key={`${key}:${i}:${j}`} {...style} wrap="truncate-end">
236 {p === '' ? ' ' : p}
237 </Text>
238 )),
239 )
240 if (used < total) out.push(partsRow(Text, `${key}:more`, cutParts(lines.length - take, more, width)))
241 return out
242}
243
244export const UNKNOWN_LABEL = 'unknown placeholder'
245const GONE_REASON = 'not sent: plugin files removed'
246
247// One row per distinct token (case-insensitive, first occurrence); known rows take the description from the entry, the text from `sent` when given.
248export function bandRows(view: PlaceholderView, entries: readonly EditorEntry[], sent?: readonly Sent[], plans?: (name: string) => PlanParts): BandRow[] {
249 const byName = new Map<string, EditorEntry>()
250 for (const entry of entries) {
251 const name = entry.name.toLowerCase()
252 if (!byName.has(name)) byName.set(name, entry)
253 }
254 const bySent = new Map((sent ?? []).map((s) => [s.name, s]))
255 const seen = new Set<string>()
256 const rows: BandRow[] = []
257 for (const token of view.tokens) {
258 const id = token.text.toLowerCase()
259 if (seen.has(id)) continue
260 seen.add(id)
261 const entry = token.isKnown ? byName.get(token.name) : undefined
262 const s = token.isKnown ? bySent.get(token.name) : undefined
263 const reason = s?.reason ?? null
264 const pp = token.isKnown ? plans?.(token.name) : undefined
265 rows.push({
266 text: token.text,
267 name: token.name,
268 isKnown: token.isKnown,
269 description: token.isKnown ? (entry?.description ?? token.name) : UNKNOWN_LABEL,
270 body: s === undefined ? (entry?.body ?? '') : s.text,
271 ...(entry?.isInline === true ? { isInline: true } : {}),
272 ...(reason !== null ? { reason } : {}),
273 ...(pp?.kind === 'add' ? { plan: pp.plan } : {}),
274 })
275 }
276 return rows
277}
278
279// Every band string; P = the prefix, token = the first or focused token as typed.
280const showMore = (o: BandOptions, row: BandRow): More => ({ kind: 'show', token: o.prefix + row.name, hasQuery: o.hasQuery })
281const compactFoot = (token: string, prefix: string): Part[] => ['more: ', { act: `put the caret on ${token}` }, ' · send as typed: ', { act: `${prefix}/` }, ' · help: ', { act: '/placeholders help' }]
282const focusFoot = (token: string, prefix: string): Part[] => ['close: ', { act: `move the caret off ${token}` }, ' · send as typed: ', { act: `${prefix}/` }]
283const UNKNOWN_FOOT: Part[] = ['names: ', { act: '/placeholders list' }]
284const alsoRow = (rows: readonly BandRow[]): Part[] => ['also:', ...rows.flatMap((r): Part[] => [' ', { tok: r.text, isKnown: r.isKnown }])]
285const ESCAPED_HEAD = ' placeholders off: this message is sent exactly as typed'
286const escapedFoot = (marker: string): Part[] => ['turn back on: ', { act: `delete ${marker}` }]
287const PLAN_HEAD = ' · plan mode'
288const PLAN_PLUS = ` ${PLAN_LABEL.plus}`
289// The band knows plan mode only after a prompt (state file), so the note says when the text is sent.
290const planNote = (plan: string): string => {
291 const n = plan.split('\n').length
292 return `not sent now · plan mode adds ${n} ${plural(n, 'line')}`
293}
294
295// Body rows sit 2 cells in.
296const bodyWidth = (o: BandOptions): number => Math.max(o.columns - 2, 1)
297// Token rows that fit `budget` beside the band head, the foot and a `K more` row.
298const fitting = (rows: readonly BandRow[], budget: number): readonly BandRow[] => (rows.length + 2 <= budget ? rows : rows.slice(0, Math.max(budget - 3, 0)))
299// Rows left for bodies once the head, the foot, `shown` token rows and a `K more` row past them are drawn.
300const freeRows = (budget: number, shown: number, total: number): number => budget - 2 - shown - (shown < total ? 1 : 0)
301
302type Fit = { shown: readonly BandRow[]; alloc: ReadonlyMap<BandRow, number> }
303
304// Token rows that fit `budget` and the body rows each shown row gets.
305// Fewer free rows than bodies: the last token rows fold into `K more` (one stays), so the band never passes `budget`.
306function fitRows(rows: readonly BandRow[], budget: number, width: number, isPlan: boolean): Fit {
307 let shown = fitting(rows, budget)
308 while (shown.length > 1 && freeRows(budget, shown.length, rows.length) < shown.filter((r) => r.body !== '').length) shown = shown.slice(0, -1)
309 const bodies = shown.filter((r) => r.body !== '')
310 const needs = bodies.map((r) => needOf(r, isPlan, width))
311 const give = shareRows(needs, freeRows(budget, shown.length, rows.length))
312 return { shown, alloc: new Map(bodies.map((r, i) => [r, give[i] ?? 0])) }
313}
314
315// The body is what Claude receives with this message (a cut body too).
316export const isSentNow = (row: BandRow): boolean => row.isKnown && row.body !== '' && (row.reason === undefined || row.reason === REASON.cut)
317
318export const RECEIVES = 'Claude receives these lines now:'
319// Label over a drawn body; null = nothing drawn or not sent (the head keeps its reason tag).
320export function receivesLabel(row: BandRow): string | null {
321 if (!row.isKnown || row.body === '') return null
322 if (row.reason === REASON.cut) return `Claude receives these lines now (${REASON.cut}):`
323 return row.reason === undefined ? RECEIVES : null
324}
325
326// A token's one line: the description gives way so the token and its labels stay whole.
327// label = receivesLabel of a drawn body: it replaces the reason tag; isFocus also drops the description and the plan tag.
328function drawHead(ui: BandUi, row: BandRow, o: BandOptions, label: string | null = null, isFocus = false): RenderElement {
329 const { Box, Text } = ui
330 const tail = label === null ? '' : ` · ${label}`
331 const reasonLabel = label !== null || row.reason === undefined ? '' : ` (${row.reason})`
332 const plus = row.plan === undefined || (isFocus && label !== null) ? '' : PLAN_PLUS
333 const description = isFocus && label !== null ? '' : clip(` ${row.description}`, o.columns - cells(row.text) - cells(plus) - cells(reasonLabel) - cells(tail))
334 return (
335 <Box>
336 <Text {...tokStyle(row.isKnown)}>{row.text}</Text>
337 {description === '' ? null : (
338 <Text dimColor wrap="truncate-end">
339 {description}
340 </Text>
341 )}
342 {plus === '' ? null : <Text {...PLAN_STYLE}>{plus}</Text>}
343 {reasonLabel === '' ? null : <Text dimColor>{reasonLabel}</Text>}
344 {tail === '' ? null : (
345 <Text dimColor wrap="truncate-end">
346 {tail}
347 </Text>
348 )}
349 </Box>
350 )
351}
352
353function foot(ui: BandUi, o: BandOptions, parts: readonly Part[]): RenderElement {
354 return partsRow(ui.Text, 'hint', o.isGone ? [FILES_GONE] : parts)
355}
356
357// Gone: a context row cannot be sent (its hook is gone); an inline one still expands.
358const goneRow = (r: BandRow): BandRow => (r.isInline === true || !r.isKnown ? r : { ...r, body: '', reason: GONE_REASON })
359
360export function renderBand(ui: BandUi, all: readonly BandRow[], o: BandOptions): RenderElement {
361 if (o.mode === 'escaped') return renderEscaped(ui, all, o)
362 const rows = o.isGone ? all.map(goneRow) : all
363 const row = o.mode === 'focus' ? rows.find((r) => r.name === o.focus.name) : undefined
364 return row === undefined ? renderCompact(ui, rows, o) : renderFocus(ui, rows, row, o)
365}
366
367// The caret token's sent text (up to 15 rows), the other tokens on one row; no Button.
368// A cut names `?` only when the menu caps the rows and `?` would show the whole text; else the show command.
369function renderFocus(ui: BandUi, rows: readonly BandRow[], row: BandRow, o: BandOptions): RenderElement {
370 const { Box, Text } = ui
371 const others = rows.filter((r) => r !== row)
372 const roomOf = (budget: number): number => Math.max(0, Math.min(FOCUS_MAX, budget - 2 - (others.length > 0 ? 1 : 0)))
373 const room = roomOf(o.budget)
374 const need = needOf(row, o.isPlan, bodyWidth(o))
375 const more: More = o.focus.isMenuOpen && !o.focus.isQuery && need <= roomOf(o.queryBudget) ? { kind: 'query', token: row.text } : showMore(o, row)
376 return (
377 <Box key="band" flexDirection="column">
378 {tokenRow(ui, row, o, room, more, false, true)}
379 {others.length === 0 ? null : partsRow(Text, 'also', alsoRow(others))}
380 {foot(ui, o, row.isKnown ? focusFoot(row.text, o.prefix) : UNKNOWN_FOOT)}
381 </Box>
382 )
383}
384
385// A token's head and its body within `rows`; isHover = the body stays hidden until hovered (un-keyed Box: a keyed one is refused).
386// A drawn body gets the receives label on the head; isFocus = the label replaces the description.
387function tokenRow(ui: BandUi, row: BandRow, o: BandOptions, rows: number, more: More, isHover = false, isFocus = false): RenderElement {
388 const { Box, Text } = ui
389 const key = row.text.toLowerCase()
390 const body = row.body === '' || rows < 1 ? null : planBody(Text, row, rows, key, o, more)
391 return (
392 <Box key={`row:${key}`} flexDirection="column">
393 {drawHead(ui, row, o, body === null || isHover ? null : receivesLabel(row), isFocus)}
394 {body === null ? null : isHover ? (
395 <Box marginLeft={2} flexDirection="column" display="none" hover={{ display: 'flex' }}>
396 {body}
397 </Box>
398 ) : (
399 <Box marginLeft={2} flexDirection="column">
400 {body}
401 </Box>
402 )}
403 </Box>
404 )
405}
406
407// A body within `rows`: plan mode marks where the addition starts (plan-colour label row), outside a plan-colour row says it exists.
408function planBody(Text: BandUi['Text'], row: BandRow, rows: number, key: string, o: BandOptions, more: More): RenderElement[] {
409 const plan = row.plan
410 const width = bodyWidth(o)
411 const isSent = isSentNow(row)
412 const whole = (n: number): RenderElement[] => bodyRows(Text, row.body, n, key, width, more, styleOf(isSent))
413 if (plan === undefined || rows < (o.isPlan ? 3 : 2)) return whole(rows)
414 const mark = (label: string): RenderElement => (
415 <Text key={`${key}:plan`} {...PLAN_STYLE} wrap="truncate-end">
416 {label}
417 </Text>
418 )
419 if (!o.isPlan) return [...whole(rows - 1), mark(planNote(plan))]
420 const sep = `\n\n${plan}`
421 if (!row.body.endsWith(sep)) return whole(rows)
422 const normal = row.body.slice(0, -sep.length)
423 const [a, b] = shareRows([rowsOf(normal, width), rowsOf(plan, width)], rows - 1)
424 return [
425 ...bodyRows(Text, normal, a ?? 1, `${key}:a`, width, null, styleOf(isSent)),
426 mark(PLAN_LABEL.adds),
427 ...bodyRows(Text, plan, b ?? 1, `${key}:b`, width, more, styleOf(isSent, true)),
428 ]
429}
430
431// `P/` in the message: nothing is substituted, so no bodies and no Button; one row per token says so.
432function renderEscaped(ui: BandUi, rows: readonly BandRow[], o: BandOptions): RenderElement {
433 const { Box, Text } = ui
434 const shown = fitting(rows, o.budget)
435 const reason = ` (${escapedReason(o.marker)})`
436 return (
437 <Box key="band" flexDirection="column">
438 <Box key="head">
439 <Text {...tokStyle(true)}>{o.marker}</Text>
440 <Text dimColor wrap="truncate-end">
441 {ESCAPED_HEAD}
442 </Text>
443 </Box>
444 {shown.map((r) => (
445 <Box key={`row:${r.text.toLowerCase()}`}>
446 <Text {...tokStyle(r.isKnown)}>{r.text}</Text>
447 <Text dimColor wrap="truncate-end">
448 {reason}
449 </Text>
450 </Box>
451 ))}
452 {rows.length > shown.length ? <Text dimColor>{nMore(rows.length - shown.length, 'placeholder')}</Text> : null}
453 {partsRow(Text, 'hint', escapedFoot(o.marker))}
454 </Box>
455 )
456}
457
458// Header `placeholders N`, one keyed row per token, `K more placeholders` past the budget, a foot hint.
459// 1-2 rows: bodies within the auto budget, a cut names the show command; 3+ rows: each body in a hidden hover Box.
460function renderCompact(ui: BandUi, rows: readonly BandRow[], o: BandOptions): RenderElement {
461 const { Box, Text } = ui
462 const view = rows.length <= AUTO_MAX_ROWS ? fitRows(rows, o.autoBudget, bodyWidth(o), o.isPlan) : null
463 const shown = view?.shown ?? fitting(rows, o.autoBudget)
464 const hoverRows = Math.max(freeRows(o.budget, shown.length, rows.length), 1)
465 const first = rows.find((r) => r.isKnown) ?? rows[0]
466 return (
467 <Box key="band" flexDirection="column">
468 <Box key="head">
469 <Text dimColor>{`placeholders ${rows.length}`}</Text>
470 {o.isPlan ? <Text {...PLAN_STYLE}>{PLAN_HEAD}</Text> : null}
471 </Box>
472 {shown.map((row) => (view === null ? tokenRow(ui, row, o, hoverRows, showMore(o, row), true) : tokenRow(ui, row, o, view.alloc.get(row) ?? 0, showMore(o, row))))}
473 {rows.length > shown.length ? <Text dimColor>{nMore(rows.length - shown.length, 'placeholder')}</Text> : null}
474 {foot(ui, o, compactFoot(first?.text ?? `${o.prefix}name`, o.prefix))}
475 </Box>
476 )
477}
478hooks/lib/sent.ts 176 lines1// What a prompt sends, per token: TS port of `assemble` in hooks/inject.mjs plus a reason for every token not sent. Zero I/O.
2import type { Def } from './defs'
3import { compileDefs, type Compiled } from './compiled'
4import { expandInline, inlineBodies } from './inline'
5import { DEFAULT_PREFIX, markerOf, scanDraft } from './match'
6
7export const MAX_CHARS = 9000
8const JOINER = '\n\n---\n\n'
9const CUT_NOTE = '\n...[truncated]'
10// First `at` chars, one fewer when the last would be a lone high surrogate (inject.mjs cuts the same way).
11const cutAt = (text: string, at: number): string => {
12 const c = text.charCodeAt(at - 1)
13 return text.slice(0, c >= 0xd800 && c <= 0xdbff ? at - 1 : at)
14}
15// Subagent deliveries arrive as prompts too; only the leading tag marks them (inject.mjs skips them).
16const SYNTHETIC_PROMPT = /^\s*<(?:task-notification>|agent-message\s+from=)/
17
18export const REASON = {
19 empty: 'not sent: empty',
20 staysAsTyped: 'stays as typed',
21 overCap: `not sent: over ${MAX_CHARS} chars`,
22 cut: `cut at ${MAX_CHARS} chars`,
23 delivery: 'not sent: delivery tag',
24 unknown: 'unknown placeholder',
25} as const
26// Plan-mode part labels and tags of the band and `/placeholders show`.
27export const PLAN_LABEL = { adds: 'plan mode adds:', plus: 'plan +' } as const
28const winsReason = (token: string): string => `not sent: ${token} wins`
29export const escapedReason = (marker: string): string => `not sent: ${marker} in this message`
30
31// text = exact text the token adds ('' = nothing).
32export type Sent = { token: string; name: string; kind: 'context' | 'inline' | 'none'; text: string; isSent: boolean; reason: string | null }
33// prompt = the text after inline expansion; context = the hook's additionalContext ('' = none); tokens = one per known draft name, draft order.
34export type Draft = { prompt: string; context: string; tokens: Sent[] }
35
36const unsent = (reason: string): Pick<Sent, 'text' | 'isSent' | 'reason'> => ({ text: '', isSent: false, reason })
37// The hook sends nothing for a delivery tag or a prompt without the prefix.
38const isSkipped = (prompt: string, prefix: string): boolean => SYNTHETIC_PROMPT.test(prompt) || !prompt.includes(prefix)
39
40function blockOf(d: Def, prefix: string): { text: string } {
41 const head = d.header.split('{token}').join(prefix + d.name.toLowerCase())
42 return { text: head === '' ? d.body : `${head}\n\n${d.body}` }
43}
44
45// Per name, context defs only: the first normal def and the first plan part (a part without a normal context def is never sent).
46function parts(defs: readonly Def[]): { normal: Map<string, Def>; plan: Map<string, Def> } {
47 const normal = new Map<string, Def>()
48 const plan = new Map<string, Def>()
49 for (const d of defs) {
50 if (d.insert !== 'context') continue
51 const m = d.isPlan ? plan : normal
52 if (!m.has(d.name.toLowerCase())) m.set(d.name.toLowerCase(), d)
53 }
54 return { normal, plan }
55}
56
57// Plan part on its normal def: plan header if any, normal body, '\n\n', addition. Empty normal body = silenced in both modes.
58const withPart = (base: Def, part: Def): Def =>
59 base.body === '' ? base : { ...base, header: part.header === '' ? base.header : part.header, body: part.body === '' ? base.body : `${base.body}\n\n${part.body}` }
60
61// What each name sends in this mode: the normal def; in plan mode its plan part joined to it.
62function winners(defs: readonly Def[], plan: boolean): Map<string, Def> {
63 const { normal, plan: part } = parts(defs)
64 if (!plan) return normal
65 return new Map([...normal].map(([key, d]) => {
66 const p = part.get(key)
67 return [key, p === undefined ? d : withPart(d, p)]
68 }))
69}
70
71// The caller's compiled defs (register.ts memoises them); a bare defs array is compiled per call.
72export type DefsLike = Compiled | readonly Def[]
73const isCompiled = (src: DefsLike): src is Compiled => !Array.isArray(src)
74const compiledOf = (src: DefsLike, prefix: string): Compiled => (isCompiled(src) ? (src.prefix === prefix ? src : compileDefs(src.defs, prefix)) : compileDefs(src, prefix))
75
76// inject.mjs order: mode winners that hit the prompt, then the top priority per group, then `order`. lost = group loser name -> its winner.
77function pick(c: Compiled, prompt: string, plan: boolean): { picked: Def[]; lost: Map<string, Def> } {
78 const hit = [...winners(c.defs, plan).values()].filter((d) => {
79 const m = c.matchers.byName.get(d.name.toLowerCase())
80 return m !== undefined && prompt.search(m.scan) >= 0
81 })
82 const best = new Map<string, Def>()
83 for (const d of hit) {
84 if (d.group === undefined) continue
85 const cur = best.get(d.group)
86 if (cur === undefined || d.priority > cur.priority) best.set(d.group, d)
87 }
88 const lost = new Map<string, Def>()
89 for (const d of hit) {
90 const top = d.group === undefined ? d : best.get(d.group)
91 if (top !== undefined && top !== d) lost.set(d.name.toLowerCase(), top)
92 }
93 return { picked: hit.filter((d) => !lost.has(d.name.toLowerCase())).sort((a, b) => a.order - b.order), lost }
94}
95
96// Joined blocks capped like inject.mjs; cuts = name -> its block text past the cap ('' = dropped), whole blocks absent.
97function join(picked: readonly Def[], prefix: string): { context: string; cuts: Map<string, string> } {
98 const blocks = picked.filter((d) => d.body !== '').map((d) => ({ name: d.name.toLowerCase(), text: blockOf(d, prefix).text }))
99 const cuts = new Map<string, string>()
100 let at = 0
101 for (const b of blocks) {
102 const room = MAX_CHARS - at
103 if (room < b.text.length) cuts.set(b.name, room > 0 ? cutAt(b.text, room) + CUT_NOTE : '')
104 at += b.text.length + JOINER.length
105 }
106 const joined = blocks.map((b) => b.text).join(JOINER)
107 return { context: joined.length > MAX_CHARS ? cutAt(joined, MAX_CHARS) + CUT_NOTE : joined, cuts }
108}
109
110// The hook's whole answer, port of inject.mjs `run` + `assemble`: '' = nothing; only the mode string `plan` is plan mode.
111export function injectedContext(src: DefsLike, prefix: string, prompt: string, mode: unknown): string {
112 const c = compiledOf(src, prefix)
113 if (isSkipped(prompt, prefix) || markerOf(c.matchers, prompt) !== null) return ''
114 return join(pick(c, prompt, mode === 'plan').picked, prefix).context
115}
116
117// A name's plan-mode text: add (plan = the addition body) or none (no plan part, an empty part, or an empty normal body).
118export type PlanParts = { normal: string; plan: string; kind: 'add' | 'none' }
119export function planParts(defs: readonly Def[], name: string, prefix: string = DEFAULT_PREFIX): PlanParts {
120 const key = name.toLowerCase()
121 const { normal: n, plan: pp } = parts(defs.filter((d) => d.name.toLowerCase() === key))
122 const b = n.get(key)
123 const p = pp.get(key)
124 const normal = b === undefined || b.body === '' ? '' : blockOf(b, prefix).text
125 return b === undefined || p === undefined || b.body === '' || p.body === '' ? { normal, plan: '', kind: 'none' } : { normal, plan: p.body, kind: 'add' }
126}
127
128// Known names of a draft, first occurrence order.
129function knownNames(c: Compiled, text: string): string[] {
130 const names: string[] = []
131 for (const t of scanDraft(c.matchers, text).tokens) if (t.isKnown && !names.includes(t.name)) names.push(t.name)
132 return names
133}
134
135const strip = (token: string, prefix: string): string => (token.startsWith(prefix) && token.length > prefix.length ? token.slice(prefix.length) : token).toLowerCase()
136
137// One token alone in a prompt (`r` or `++r`): its context block or inline text in this mode, else why not.
138export function sentText(token: string, defs: readonly Def[], prefix: string, isPlan: boolean): Sent {
139 const name = strip(token, prefix)
140 const base = { token: prefix + name, name }
141 const ctx = defs.filter((d) => d.insert === 'context' && d.name.toLowerCase() === name)
142 const now = winners(ctx, isPlan).get(name)
143 if (now !== undefined) return now.body === '' ? { ...base, kind: 'context', ...unsent(REASON.empty) } : { ...base, kind: 'context', ...blockOf(now, prefix), isSent: true, reason: null }
144 const body = inlineBodies(defs).get(name)
145 if (body !== undefined) return { ...base, kind: 'inline', text: body, isSent: true, reason: null }
146 const inl = defs.filter((d) => d.insert === 'inline' && d.name.toLowerCase() === name)
147 if (inl.length === 0) return { ...base, kind: 'none', ...unsent(REASON.unknown) }
148 return { ...base, kind: 'inline', ...unsent(inl.some((d) => !d.isPlan && d.body === '') ? REASON.empty : REASON.staysAsTyped) }
149}
150
151// A typed draft as the person sends it: inline expansion (module), then the context blocks (command hook) with group and cap reasons.
152// Escaped (`P/`): sent verbatim, nothing expanded or injected. A marker an inline body brings in: no context, inline text stays expanded.
153export function assembleDraft(text: string, src: DefsLike, prefix: string, isPlan: boolean): Draft {
154 const c = compiledOf(src, prefix)
155 const marker = markerOf(c.matchers, text)
156 if (marker !== null) return { prompt: text, context: '', tokens: knownNames(c, text).map((name) => ({ ...sentText(name, c.defs, prefix, isPlan), ...unsent(escapedReason(marker)) })) }
157 const prompt = expandInline(c, text) ?? text
158 const late = markerOf(c.matchers, prompt)
159 const skipped = isSkipped(prompt, prefix)
160 const { picked, lost } = skipped || late !== null ? { picked: [], lost: new Map<string, Def>() } : pick(c, prompt, isPlan)
161 const { context, cuts } = join(picked, prefix)
162 const tokens = knownNames(c, text).map((name): Sent => {
163 const s = sentText(name, c.defs, prefix, isPlan)
164 if (s.kind !== 'context') return s
165 if (late !== null) return { ...s, ...unsent(escapedReason(late)) }
166 if (!s.isSent) return s
167 if (skipped) return { ...s, ...unsent(REASON.delivery) }
168 const top = lost.get(name)
169 if (top !== undefined) return { ...s, ...unsent(winsReason(prefix + top.name.toLowerCase())) }
170 const cut = cuts.get(name)
171 if (cut === undefined) return s
172 return cut === '' ? { ...s, ...unsent(REASON.overCap) } : { ...s, text: cut, reason: REASON.cut }
173 })
174 return { prompt, context, tokens }
175}
176hooks/lib/command.ts 341 lines1// /placeholders model hand-off text and the model tools: pure over an injected Io, never `$`.
2import { DEFAULT_PREFIX, escapeMarkers } from './match'
3import { planParts, type PlanParts } from './sent'
4import { FOCUS_MAX } from './band'
5import { layerSpecs, loadRegistry, newRegistryCache, parseDefinition, type Def, type Io, type Registry, type Roots } from './defs'
6
7export type StatLite = { kind: 'file' | 'dir' | 'other'; isLink: boolean; realPath?: string }
8export type CmdIo = Io & {
9 write: (path: string, text: string) => Promise<void>
10 stat: (path: string) => Promise<StatLite | undefined>
11 remove: (path: string) => Promise<{ exitCode: number; stderr: string }>
12}
13export type Scope = 'project' | 'global'
14export type Part = 'all' | 'normal' | 'plan'
15// A stale `when` from an older tool spec may still arrive: it is ignored, never rejected.
16export type SaveInput = { name?: unknown; description?: unknown; text?: unknown; planText?: unknown; scope?: unknown }
17export type RemoveInput = { name?: unknown; scope?: unknown; part?: unknown }
18export type ToolOut = { text: string; registry: Registry | null; isError?: true }
19export type Row = { stem: string; layer: string; def: Def }
20
21export const TOOL_PREFIX = 'mcp__brewmod-placeholders__'
22export const NEEDS_NEW_CC = 'changing placeholders by words needs Claude Code 2.1.300+ · meanwhile: edit the <name>.md files by hand'
23export const SCOPE_REQUIRED = "scope is required: 'global' or 'project'"
24const BAD_SCOPE = "scope must be 'project' or 'global'"
25const BAD_FENCE = 'that text holds a ``` or ~~~ fence marker or opens with a --- line, which the definition format cannot carry'
26const NEEDS_CONTEXT = 'a plan-mode part needs a normal text that is not inline'
27const LEAVES_PLAN = (token: string): string =>
28 `removing only the normal text of ${token} would leave its plan-mode part alone, and that part would then be sent in every mode · remove both parts (part all), or change the normal text instead`
29
30// Markdown-safe block: the first line stays plain (the engine glues "<plugin>: " in front of it, so a fence cannot open there), the rest sits in a fence longer than any backtick run inside.
31export function block(head: string, lines: readonly string[], foot: readonly string[] = []): string {
32 const run = Math.max(0, ...[...lines.join('\n').matchAll(/`+/g)].map((m) => m[0].length))
33 const fence = '`'.repeat(Math.max(3, run + 1))
34 return [head, fence, ...lines, fence, ...foot].join('\n')
35}
36
37const WORD = /^[a-z0-9_]{1,32}$/
38const SYMBOL = /^[!#$%&'()+,\-;=@[\]^`{}~]{1,32}$/
39const PLAN = '.plan'
40const PLAN_MD = '.plan.md'
41
42// File-safe stem: lowercase word or punctuation run (no / \ or .; shell characters pass, names only reach argv), optional `.plan`; else null.
43export function normalizeName(raw: string): string | null {
44 const lower = raw.toLowerCase()
45 const base = lower.endsWith(PLAN) ? lower.slice(0, -PLAN.length) : lower
46 return WORD.test(base) || SYMBOL.test(base) ? lower : null
47}
48
49const why = (e: unknown): string => (e instanceof Error ? e.message : String(e))
50export const layerLabel = (id: string): string => (id === 'default' ? 'plugin' : id)
51const dirOf = (roots: Roots, layer: string): string | undefined => layerSpecs(roots).find((s) => s.id === layer)?.dir
52
53// Launched in HOME: the project dir is the global one, so both are one layer, global.
54const isOneDir = (roots: Roots): boolean => dirOf(roots, 'project') !== undefined && dirOf(roots, 'project') === dirOf(roots, 'global')
55export const oneLayer = (reg: Registry, roots: Roots): Registry =>
56 isOneDir(roots) ? { ...reg, sources: new Map([...reg.sources].map(([k, v]) => [k, v === 'project' ? 'global' : v])) } : reg
57const scopeIn = (roots: Roots, scope: Scope): Scope => (isOneDir(roots) ? 'global' : scope)
58const load = async (io: Io, roots: Roots): Promise<Registry> => oneLayer(await loadRegistry(io, roots, newRegistryCache()), roots)
59
60// Shown layer dirs: the config dir with `~` for HOME; the project one relative to its root.
61export type Dirs = { global: string; project: string }
62export function shownDirs(roots: Roots, home: string | undefined): Dirs {
63 const cfg = roots.configDir
64 const h = home === undefined || home === '' ? undefined : home.replace(/\/+$/, '')
65 const tilde = cfg !== undefined && h !== undefined && cfg.startsWith(`${h}/`) ? `~${cfg.slice(h.length)}` : cfg
66 return { global: tilde === undefined ? '(no config dir)' : `${tilde}/placeholders`, project: '.claude/placeholders' }
67}
68const noDir = (scope: Scope): string => (scope === 'project' ? 'no project root for this session' : 'no config directory (CLAUDE_CONFIG_DIR and HOME are unset)')
69const fail = (text: string): ToolOut => ({ text, registry: null, isError: true })
70export const isScope = (v: unknown): v is Scope => v === 'project' || v === 'global'
71
72// defs[i] pairs with the i-th source key: resolveDefs inserts into both maps together.
73function rowsOf(reg: Registry): Row[] {
74 const stems = [...reg.sources.keys()]
75 return reg.defs
76 .map((def, i): Row => {
77 const stem = stems[i] ?? def.name
78 return { stem, layer: reg.sources.get(stem) ?? 'default', def }
79 })
80 .sort((a, b) => (a.stem < b.stem ? -1 : a.stem > b.stem ? 1 : 0))
81}
82
83export type Named = { name: string; lead: Row; plan: Row | undefined; own: Row[]; kind: PlanParts['kind'] }
84
85// One entry per name (any case), in stem order; lead = the normal part, else the plan-mode part.
86export function byName(reg: Registry, prefix: string): Named[] {
87 const rows = rowsOf(reg)
88 return [...new Set(rows.map((r) => r.def.name.toLowerCase()))].flatMap((name) => {
89 const own = rows.filter((r) => r.def.name.toLowerCase() === name)
90 const plan = own.find((r) => r.def.isPlan)
91 const lead = own.find((r) => !r.def.isPlan) ?? plan
92 return lead === undefined ? [] : [{ name, lead, plan, own, kind: planParts(reg.defs, name, prefix).kind }]
93 })
94}
95
96export const handoffAck = (status: string): string => `asking Claude to help with your placeholder ...\n${status}`
97
98const ASK_FIRST = 'Ask first: no save_placeholder or remove_placeholder call before I answered your one AskUserQuestion about that exact change in this turn, even if my request is explicit (only a remove of a name with files: none skips it).'
99const NO_SCOPE = 'Scope: not given; infer it from my words outside the placeholder text, else ask "Where to save?" in the same dialog, Global first; a change keeps its layer, a remove uses the layer that holds it.'
100
101// Short on purpose: it shows in the transcript. The confirm rule leads; the other rules live in the tool descriptions.
102// The escape marker keeps the tokens named in the request from being expanded or injected into this message.
103export const handoffText = (request: string, prefix: string = DEFAULT_PREFIX, scope: Scope | null = null): string =>
104 `Placeholder helper. My request: <request>${request}</request>\n${ASK_FIRST}\n${scope === null ? NO_SCOPE : `Scope: ${scope} (I said it; skip only the Where question).`}\nUse the ${TOOL_PREFIX}* tools (list_placeholders first); a placeholder is inserted into prompts as ${prefix}name (not in this message: ${escapeMarkers(prefix)[0]}).`
105
106// Tool specs for the configured prefix: every token they name is spelled with it.
107export const tools = (p: string) => [
108 {
109 name: 'list_placeholders',
110 description: `List every placeholder, one entry per name: token, layer (plugin | global | project | global-legacy | project-legacy), files (the user files per layer; both layers when it is in both), plan (add | none), description, its text and its plan-mode text. Call it first before creating, changing, removing or showing one. To show placeholders, print the requested ones verbatim; /placeholders show ${p}<name> also prints them instantly.`,
111 inputSchema: { type: 'object', properties: {} },
112 },
113 {
114 name: 'save_placeholder',
115 description: `Never call this tool before the user answered your one AskUserQuestion about this exact save in this turn, even when the request is explicit. Create or change a placeholder file; never use Write. Call list_placeholders first. name: lowercase letters, digits, underscore, no prefix. text: the user's words verbatim when given, else your draft; a change starts from its text in list_placeholders. planText: a plan-mode part, added to the text only in Plan mode (file <name>.plan.md); draft one only when the user mentions plan mode (plan, plan mode, planning, план, планир, режим плана) or the name already has one. A change picks the part by words: plan part, plan mode, план, в режиме плана -> planText only; normal, обычн, основн -> text only; both, оба -> both; else text. An omitted part stays as it is. scope (required): a first word global or project wins; else infer it only from the words outside the placeholder's own text (global: global, everywhere, all projects, глобально, везде, во всех проектах; project: project, this project, here, this repo, в проекте, здесь, локально); a change keeps its layer from list_placeholders (global-legacy = global, project-legacy = project). That one AskUserQuestion call holds these questions in this order: 1. header "Placeholder", question exactly "Save ${p}<name> as drafted?" (never a layer in it) with the text, options "Save as drafted (Recommended)" / "Change it" (Other = a different name or text; apply it and save without asking again). 2. Only with a plan-mode part: header "Plan mode", question "Add this plan-mode part to ${p}<name>?", the draft as the first option's preview, options "Add it (Recommended)" / "No plan part". 3. Only when the scope is unclear (no word, or a new override of a plugin default): header "Where", question "Where to save ${p}<name>?", options "Global (Recommended)" (all your projects) then "Project" (only this project; wins over global). Only with no AskUserQuestion tool at all: save as drafted, scope global unless a word outside the text says project. Then say where it was saved.`,
116 inputSchema: {
117 type: 'object',
118 properties: {
119 name: { type: 'string', description: 'lowercase name without the prefix' },
120 description: { type: 'string', description: 'one short line shown in the list and the typeahead' },
121 text: { type: 'string', description: 'the normal text inserted into prompts; optional when only planText changes on an existing name' },
122 planText: { type: 'string', description: 'optional plan-mode part, added to the text only in Plan mode' },
123 scope: { type: 'string', enum: ['global', 'project'], description: 'required: global (all projects) or project (this project only)' },
124 },
125 required: ['name', 'description', 'scope'],
126 },
127 },
128 {
129 name: 'remove_placeholder',
130 description: `Never call this tool before the user answered your one AskUserQuestion about this exact removal in this turn, even when the request is explicit; only a name with files: none in list_placeholders skips the question (a plugin default or legacy brewtools file: nothing is removed; relay the result). Remove a placeholder file from the global or project layer; never use Bash rm. The wording is free (remove, delete, drop, удали, убери, сотри). Call list_placeholders first. part: all (default; <name>.md and <name>.plan.md), plan (the plan-mode part only: plan part, plan mode, план, в режиме плана), normal (the normal text only; refused while a plan-mode part would be left without it, since that part would then be sent in every mode). scope: a first word global or project wins; else omit it and the tool takes the one layer holding the file. Question 1, header "Remove": "Remove ${p}<name> (<layer>)?", options "Remove it (Recommended)" / "Keep it"; when it has a plan-mode part and no part was named: "Remove ${p}<name> (<layer>)? It has a plan-mode part.", options "Both parts (Recommended)" / "Only the plan-mode part" / "Keep it"; when the plan part was named: "Remove the plan-mode part of ${p}<name> (<layer>)?", options "Remove it (Recommended)" / "Keep it". When list_placeholders shows files in both layers and no scope was given, add question 2 in the same call: header "Where", "Remove ${p}<name> from where?", options "Global" / "Project". Then say what is served afterwards (the result says it).`,
131 inputSchema: {
132 type: 'object',
133 properties: {
134 name: { type: 'string', description: 'name without the prefix' },
135 scope: { type: 'string', enum: ['global', 'project'], description: 'omit to use the one layer holding the file' },
136 part: { type: 'string', enum: ['all', 'normal', 'plan'], description: 'default all' },
137 },
138 required: ['name'],
139 },
140 },
141 {
142 name: 'placeholders_help',
143 description: `How the user's ${p} placeholders work: syntax, full text (/placeholders show ${p}name; the caret on a token shows up to ${FOCUS_MAX} rows in the band), sending a message as typed (${escapeMarkers(p)[0]}), global vs project, file format, /placeholders commands and doc links. Call it before answering any question about placeholders or the ${p} prefix.`,
144 inputSchema: { type: 'object', properties: {} },
145 },
146] as const
147
148type Held = { scope: Scope; dir: string; files: string[] }
149
150// File names in the global and project dirs (`.md`, no dot files, no dirs); a missing dir lists nothing; one shared dir is global only.
151async function userFiles(io: Io, roots: Roots): Promise<Held[]> {
152 const out: Held[] = []
153 for (const scope of isOneDir(roots) ? (['global'] as const) : (['global', 'project'] as const)) {
154 const dir = dirOf(roots, scope)
155 if (dir === undefined) continue
156 const listing = (await io.exists(dir)) ? await io.list(dir) : []
157 out.push({ scope, dir, files: listing.filter((en) => en.kind !== 'dir' && !en.name.startsWith('.') && en.name.toLowerCase().endsWith('.md')).map((en) => en.name) })
158 }
159 return out
160}
161
162// `<stem>.md` = normal part, `<stem>.plan.md` = plan-mode part, normal first; names match case-insensitively.
163const isPlanFile = (f: string): boolean => f.toLowerCase().endsWith(PLAN_MD)
164const partFiles = (files: readonly string[], stem: string, part: Part): string[] =>
165 files
166 .filter((f) => {
167 const l = f.toLowerCase()
168 return (part !== 'plan' && l === `${stem}.md`) || (part !== 'normal' && l === `${stem}${PLAN_MD}`)
169 })
170 .sort((a, b) => Number(isPlanFile(a)) - Number(isPlanFile(b)))
171
172const bodyOf = (d: Def): string => (d.body === '' ? '(empty)' : d.body)
173
174function entry({ name, lead, plan, kind }: Named, held: readonly Held[], prefix: string): string {
175 const files = held.map((h) => ({ scope: h.scope, files: partFiles(h.files, name, 'all') })).filter((h) => h.files.length > 0)
176 const head = [
177 `## ${prefix}${name}`,
178 `layer: ${layerLabel(lead.layer)}`,
179 `files: ${files.length === 0 ? 'none' : files.map((h) => `${h.scope} (${h.files.join(', ')})`).join(', ')}`,
180 `plan: ${kind}`,
181 ...(lead.def.insert === 'inline' ? ['insert: inline'] : []),
182 lead.def.description ?? '-',
183 ].join(' · ')
184 const extra = plan === undefined || plan === lead ? [] : [`### plan mode adds · layer: ${layerLabel(plan.layer)}`, bodyOf(plan.def)]
185 return [head, bodyOf(lead.def), ...extra].join('\n')
186}
187
188// One entry per name: layer, user files per layer, plan kind, the text and the plan-mode text.
189export async function listTool(io: Io, roots: Roots, reg: Registry, prefix: string = DEFAULT_PREFIX): Promise<ToolOut> {
190 const held = await userFiles(io, roots)
191 const text = byName(oneLayer(reg, roots), prefix).map((n) => entry(n, held, prefix)).join('\n\n')
192 return { text: text === '' ? 'no placeholders defined' : text, registry: null }
193}
194
195const bare = (raw: unknown, prefix: string): string | null => {
196 if (typeof raw !== 'string') return null
197 const s = raw.trim()
198 return normalizeName(s.startsWith(prefix) && s.length > prefix.length ? s.slice(prefix.length) : s)
199}
200const filled = (v: unknown): string | null => (typeof v === 'string' && v.trim() !== '' ? v : null)
201
202// File = front matter (description, plan when given) + body; null when the text would not read back (fence marker, leading ---).
203export function definitionFile(description: string, text: string, plan?: 'add'): string | null {
204 const head = [`description: ${JSON.stringify(description)}`, ...(plan === undefined ? [] : [`plan: ${plan}`])]
205 const body = text.trim()
206 const content = `---\n${head.join('\n')}\n---\n${body}\n`
207 const back = parseDefinition(content)
208 return body === '' || back.issues.length > 0 || back.text !== body || back.meta.description !== description || back.meta.plan !== plan ? null : content
209}
210
211// text -> `<stem>.md`, planText -> `<stem>.plan.md` (`plan: add`), both in the scope's dir; an omitted part is left untouched. home: shown paths use `~`.
212export async function saveTool(io: CmdIo, roots: Roots, input: SaveInput, prefix: string = DEFAULT_PREFIX, home?: string): Promise<ToolOut> {
213 try {
214 const stem = bare(input.name, prefix)
215 if (stem === null) return fail('bad name: use lowercase letters, digits, underscore (1-32) or punctuation only, optional .plan suffix')
216 if (input.scope === undefined || input.scope === null || input.scope === '') return fail(SCOPE_REQUIRED)
217 if (!isScope(input.scope)) return fail(BAD_SCOPE)
218 const scope = scopeIn(roots, input.scope)
219 const text = filled(input.text)
220 const planText = filled(input.planText)
221 if (text === null && planText === null) return fail('text is empty')
222 const description = typeof input.description === 'string' ? input.description.trim().replace(/\s+/g, ' ') : ''
223 if (description === '') return fail('description is empty')
224 const isPlanName = stem.endsWith(PLAN)
225 const name = isPlanName ? stem.slice(0, -PLAN.length) : stem
226 const token = prefix + name
227 if (planText !== null && isPlanName) return fail('planText needs the name without .plan')
228 if (planText !== null || isPlanName) {
229 // The normal def the part joins (an orphan plan part sent in every mode is none); a new text file inherits its insert.
230 const base = rowsOf(await load(io, roots)).find((r) => r.def.name.toLowerCase() === name && !r.def.isPlan && !r.stem.endsWith(PLAN))?.def
231 if (base === undefined && isPlanName) return fail(`${token} has no text yet: save name ${name} with text and planText`)
232 if (base === undefined && text === null) return fail(`${token} has no text yet: send text too`)
233 if ((base?.insert ?? 'context') !== 'context') return fail(NEEDS_CONTEXT)
234 }
235 const dir = dirOf(roots, scope)
236 if (dir === undefined) return fail(noDir(scope))
237 const files: [string, string][] = []
238 for (const [file, content] of [
239 [`${stem}.md`, text === null ? undefined : definitionFile(description, text, isPlanName ? 'add' : undefined)],
240 [`${stem}${PLAN_MD}`, planText === null ? undefined : definitionFile(description, planText, 'add')],
241 ] as const) {
242 if (content === null) return fail(BAD_FENCE)
243 if (content !== undefined) files.push([file, content])
244 }
245 // Same-name entry (any case): a symlink or directory would send the write outside the layer dir.
246 const listing = (await io.exists(dir)) ? await io.list(dir) : []
247 const clash = listing.find((en) => files.some(([f]) => en.name.toLowerCase() === f) && (en.isLink || en.kind !== 'file'))
248 if (clash !== undefined) return fail(`refused, ${dir}/${clash.name} is not a plain file`)
249 for (const [file, content] of files) await io.write(`${dir}/${file}`, content)
250 const registry = await load(io, roots)
251 const won = files.map(([f]) => registry.sources.get(f.slice(0, -3))).find((l) => l !== undefined && l !== scope)
252 const note = won === undefined ? '' : `; note: the ${layerLabel(won)} layer wins over ${scope}`
253 const what = text === null || isPlanName ? `the plan-mode part of ${token}` : token
254 const shown = shownDirs(roots, home)[scope]
255 return { text: `saved ${what} (${scope}): ${files.map(([f]) => `${shown}/${f}`).join(', ')}${note}`, registry }
256 } catch (e) {
257 return fail(`failed: ${why(e)}`)
258 }
259}
260
261const servedLabel = (id: string): string => (id.endsWith('-legacy') ? `brewtools ${id.slice(0, -'-legacy'.length)}` : id)
262
263// What the name sends after the removal: the layer now serving the removed part, else what is left.
264function after(reg: Registry, stem: string, token: string, isPlanPart: boolean): string {
265 const now = reg.sources.get(isPlanPart ? `${stem}${PLAN}` : stem)
266 const what = isPlanPart ? `plan-mode part of ${token}` : token
267 if (now !== undefined) return now === 'default' ? `the built-in ${what} is back` : `the ${servedLabel(now)} ${what} is served now`
268 if (!reg.sources.has(isPlanPart ? stem : `${stem}${PLAN}`)) return `${token} is no longer defined`
269 return isPlanPart ? `${token} keeps its normal text` : `its plan-mode part is now sent in every mode`
270}
271
272// The registry as if the given files were gone: their listing entries are hidden.
273const hiding = (io: Io, gone: readonly string[]): Io => ({ ...io, list: async (dir) => (await io.list(dir)).filter((en) => !gone.includes(`${dir}/${en.name}`)) })
274// The name is served only by plan files: an orphan plan part, sent in every mode.
275const isLeftAlone = (reg: Registry, stem: string): boolean => {
276 const own = rowsOf(reg).filter((r) => r.def.name.toLowerCase() === stem)
277 return own.length > 0 && own.every((r) => r.stem.endsWith(PLAN))
278}
279
280// No user file to remove: a legacy brewtools file, a built-in, a missing plan part or an unknown name.
281async function notRemovable(io: Io, roots: Roots, stem: string, part: Part, token: string): Promise<string> {
282 const keys = part === 'plan' ? [`${stem}${PLAN}`] : part === 'normal' ? [stem] : [stem, `${stem}${PLAN}`]
283 const reg = await load(io, roots)
284 const rows = rowsOf(reg).filter((r) => keys.includes(r.stem))
285 const legacy = rows.find((r) => r.layer.endsWith('-legacy'))
286 if (legacy !== undefined) {
287 const dir = dirOf(roots, legacy.layer) ?? legacy.layer
288 return `${token} comes from a brewtools file (${dir}/${legacy.def.legacy ?? stem}.md) · delete it by hand if you no longer need it`
289 }
290 if (rows.some((r) => r.layer === 'default')) return `${token} is built in and cannot be removed · change what it sends: /placeholders change ${token} ...`
291 if (part === 'plan' && reg.sources.has(stem)) return `${token} has no plan-mode part`
292 return `unknown placeholder ${token}`
293}
294
295// Removes the part's files from one layer: the given scope, else the one layer holding them; both layers -> ask. home: shown paths use `~`.
296export async function removeTool(io: CmdIo, roots: Roots, input: RemoveInput, prefix: string = DEFAULT_PREFIX, home?: string): Promise<ToolOut> {
297 try {
298 const raw = bare(input.name, prefix)
299 if (raw === null) return fail('bad name')
300 const isPlanStem = raw.endsWith(PLAN)
301 const stem = isPlanStem ? raw.slice(0, -PLAN.length) : raw
302 const part = input.part === undefined ? (isPlanStem ? 'plan' : 'all') : input.part
303 if (part !== 'all' && part !== 'normal' && part !== 'plan') return fail("part must be 'all', 'normal' or 'plan'")
304 if (input.scope !== undefined && !isScope(input.scope)) return fail(BAD_SCOPE)
305 const scope = input.scope === undefined ? undefined : scopeIn(roots, input.scope)
306 const token = prefix + stem
307 const held = (await userFiles(io, roots)).map((h) => ({ ...h, files: partFiles(h.files, stem, part) })).filter((h) => h.files.length > 0)
308 const picked = scope === undefined ? held : held.filter((h) => h.scope === scope)
309 if (picked.length > 1) return fail(`${token} is in both layers (global and project): ask "Remove ${token} from where?" (Global / Project), then call remove_placeholder again with scope`)
310 const target = picked[0]
311 if (target === undefined) {
312 const other = held[0]
313 return fail(other !== undefined ? `${token} has no ${String(scope)} file; it is in the ${other.scope} layer` : await notRemovable(io, roots, stem, part, token))
314 }
315 // Every file must be a plain file whose real path sits inside the real layer dir; nothing goes until all pass.
316 const base = (await io.stat(target.dir))?.realPath?.replace(/\/+$/, '')
317 const reals: string[] = []
318 for (const f of target.files) {
319 const st = await io.stat(`${target.dir}/${f}`)
320 const real = st?.realPath
321 if (st === undefined || st.kind !== 'file' || st.isLink || base === undefined || base === '' || real === undefined || !real.startsWith(`${base}/`)) {
322 return fail(`refused, ${target.dir}/${f} is not a plain file inside ${target.dir}`)
323 }
324 reals.push(real)
325 }
326 if (part === 'normal' && isLeftAlone(await load(hiding(io, target.files.map((f) => `${target.dir}/${f}`)), roots), stem)) return fail(LEAVES_PLAN(token))
327 for (const real of reals) {
328 const res = await io.remove(real)
329 if (res.exitCode !== 0) return fail(`rm failed (exit ${res.exitCode}): ${res.stderr.trim()}`)
330 }
331 const registry = await load(io, roots)
332 const shown = shownDirs(roots, home)[target.scope]
333 const paths = target.files.map((f) => `${shown}/${f}`).join(', ')
334 const isPlanPart = target.files.every(isPlanFile)
335 const what = isPlanPart ? `the plan-mode part of ${token}` : token
336 return { text: `removed ${what} (${target.scope}): ${paths} · ${after(registry, stem, token, isPlanPart)}`, registry }
337 } catch (e) {
338 return fail(`failed: ${why(e)}`)
339 }
340}
341hooks/lib/show.ts 193 lines1// What /placeholders answers without Claude: the grammar, status, help, show and list texts. Pure, zero I/O.
2import { DEFAULT_PREFIX, compileMatchers, scanDraft, type Matchers } from './match'
3import { MAX_CHARS, PLAN_LABEL, REASON, planParts, sentText, type PlanParts } from './sent'
4import { inlineBodies } from './inline'
5import { FOCUS_MAX } from './band'
6import { block, byName, isScope, layerLabel, type Dirs, type Scope } from './command'
7import type { Registry } from './defs'
8
9export { shownDirs, type Dirs } from './command'
10
11export const DOCS_URL = 'https://doc-claude.brewcode.app/mods/placeholders/'
12export const README_URL = 'https://github.com/kochetkov-ma/claude-brewcode/tree/main/brewmod-placeholders'
13
14export type Action =
15 | { kind: 'status' }
16 | { kind: 'help' }
17 | { kind: 'list' }
18 | { kind: 'show'; names: string[] }
19 | { kind: 'claude'; request: string; scope: Scope | null }
20
21type Cue = 'status' | 'help' | 'list' | 'show' | 'mutate' | 'filler'
22
23// Per cue: exact EN/RU words, then RU stems (prefix match). The order is the lookup order.
24const CUES: readonly [Cue, readonly string[], readonly string[]][] = [
25 ['status', ['status'], ['статус']],
26 ['help', ['help', '-h', '--help', '?', 'usage', 'docs'], ['помощ', 'справк', 'хелп', 'инструкц']],
27 ['list', ['list', 'ls', 'all', 'every', 'everything', 'все', 'весь', 'всех'], ['список']],
28 ['show', ['show', 'print', 'display', 'view', 'see', 'cat', 'open', 'expand', 'what', 'whats', 'что'], ['покаж', 'показ', 'выве', 'вывод', 'отобраз', 'откр', 'раскр', 'посмотр', 'глян']],
29 [
30 'mutate',
31 ['add', 'new', 'create', 'make', 'save', 'set', 'write', 'change', 'edit', 'update', 'modify', 'fix', 'rename', 'replace', 'rewrite', 'shorten', 'extend', 'remove', 'delete', 'drop', 'rm', 'del'],
32 ['добав', 'нов', 'созда', 'сдела', 'сохран', 'запомн', 'измен', 'поменя', 'замен', 'исправ', 'обнов', 'редакт', 'переимен', 'перепиш', 'сократ', 'укорот', 'допиш', 'расшир', 'удал', 'убер', 'сотр'],
33 ],
34 [
35 'filler',
36 ['me', 'the', 'and', 'please', 'text', 'full', 'whole', 'of', 'for', 'placeholder', 'placeholders', 'is', 'are', 'does', 'do', 'it', 'its', 'mean', 'means', 'about', 'мне', 'и', 'а', 'пожалуйста', 'целиком', 'такое', 'за', 'это', 'про'],
37 ['текст', 'полн', 'плейсхолдер', 'значит', 'делает'],
38 ],
39]
40
41const cueOf = (word: string): Cue | null => CUES.find(([, words, stems]) => words.includes(word) || stems.some((st) => word.startsWith(st)))?.[0] ?? null
42
43// Prefix tokens (known or not) cut out, a `?` right after one taken with it; isQueries = every token had one, none overlapped.
44function walk(ms: Matchers, text: string): { names: string[]; isQueries: boolean; rest: string } {
45 const names: string[] = []
46 let isQueries = true
47 let rest = ''
48 let at = 0
49 for (const t of scanDraft(ms, text).tokens) {
50 const isQuery = text.charAt(t.end) === '?'
51 isQueries = isQueries && t.start >= at && isQuery
52 if (t.start < at) continue
53 rest += `${text.slice(at, t.start)} `
54 names.push(t.name)
55 at = isQuery ? t.end + 1 : t.end
56 }
57 return { names, isQueries, rest: rest + text.slice(at) }
58}
59
60// First match wins: scope word, a change word, names to show, help, list, status; any other word goes to Claude.
61// Lowercase, `ё` -> `е`; words split on spaces and `,;:!.`, a trailing `?` dropped.
62export function parseArgs(args: string, prefix: string, names: readonly string[]): Action {
63 const request = args.trim()
64 const toClaude = (scope: Scope | null = null): Action => ({ kind: 'claude', request, scope })
65 const known = new Set(names.map((n) => n.toLowerCase()))
66 const { names: tokens, rest } = walk(compileMatchers(prefix, known), request.toLowerCase().replace(/ё/g, 'е'))
67 const words = rest
68 .replace(/['’]/g, '')
69 .split(/[\s,;:!.]+/)
70 .filter((w) => w !== '')
71 .map((w) => (w.length > 1 ? w.replace(/\?+$/, '') : w))
72 const first = request.split(/\s+/)[0]?.toLowerCase() ?? ''
73 if (isScope(first)) return words.length + tokens.length > 1 ? toClaude(first) : { kind: 'status' }
74 const cues = words.map((w) => ({ w, cue: cueOf(w) }))
75 if (cues.some((c) => c.cue === 'mutate' || (c.cue === null && !known.has(c.w)))) return toClaude()
76 const items = [...new Set([...tokens, ...cues.filter((c) => c.cue === null).map((c) => c.w)])]
77 if (items.length > 0) return cues.some((c) => c.cue === 'status' || c.cue === 'help') ? toClaude() : { kind: 'show', names: items }
78 if (cues.some((c) => c.cue === 'help')) return { kind: 'help' }
79 if (cues.some((c) => c.cue === 'list')) return { kind: 'list' }
80 return { kind: 'status' }
81}
82
83// P1: a prompt made only of `P<name>?` items (spaces, commas between) -> the names; anything else -> null.
84export function queryNames(ms: Matchers, text: string): string[] | null {
85 const w = walk(ms, text)
86 return w.names.length > 0 && w.isQueries && /^[\s,;]*$/.test(w.rest) ? [...new Set(w.names)] : null
87}
88
89// Prefixed tokens: a bare name can be a cue word (`fix`, `docs`, `all`) and turn the line into another command.
90export const showCommand = (prefix: string, names: readonly string[]): string => `/placeholders show ${names.map((n) => prefix + n).join(' ')}`
91// P1 fill: a trailing space puts the caret past the last token, so no name typeahead opens under the box and Enter runs the command.
92export const fillText = (prefix: string, names: readonly string[]): string => `${showCommand(prefix, names)} `
93export const queryDrop = (prefix: string, names: readonly string[]): string =>
94 `${names.map((n) => `${prefix}${n}?`).join(' ')} = ${showCommand(prefix, names)} · not sent to Claude · press Enter to print it`
95
96const DEFAULT_DIRS: Dirs = { global: '~/.claude/placeholders', project: '.claude/placeholders' }
97
98type NameRow = { name: string; layer: string; planLayer: string | null; kind: PlanParts['kind']; inline: boolean; description: string }
99
100// One row per name, sorted by name; layer = the normal part's.
101const nameRows = (reg: Registry, prefix: string): NameRow[] =>
102 byName(reg, prefix).map(({ name, lead, plan, own, kind }) => ({
103 name,
104 layer: layerLabel(lead.layer),
105 planLayer: plan === undefined ? null : layerLabel(plan.layer),
106 kind,
107 inline: own.every((r) => r.def.insert === 'inline'),
108 description: lead.def.description ?? '-',
109 }))
110
111const tagOf = (r: NameRow): string =>
112 r.kind === 'add' ? (r.planLayer === null || r.planLayer === r.layer ? PLAN_LABEL.plus : `${PLAN_LABEL.plus} (${r.planLayer})`) : r.inline ? 'inline' : ''
113
114// The example name in hints: `r` when defined, else the first word name, else the first name.
115const sample = (rows: readonly NameRow[]): string => rows.find((r) => r.name === 'r')?.name ?? rows.find((r) => /^\w+$/.test(r.name))?.name ?? rows[0]?.name ?? 'name'
116
117// hasQuery = the `P<name>?` hand-off runs (the build has the mod tools); else the texts name only the show command.
118export function statusText(reg: Registry, prefix: string = DEFAULT_PREFIX, dirs: Dirs = DEFAULT_DIRS, hasQuery = true): string {
119 const rows = nameRows(reg, prefix)
120 const tags = rows.map(tagOf)
121 const w = Math.max(4, ...rows.map((r) => (prefix + r.name).length))
122 const lw = Math.max(6, ...rows.map((r) => r.layer.length))
123 const tw = Math.max(0, ...tags.map((t) => t.length))
124 const lines = rows.map((r, i) => [(prefix + r.name).padEnd(w), r.layer.padEnd(lw), ...(tw === 0 ? [] : [(tags[i] ?? '').padEnd(tw)]), r.description].join(' '))
125 const issues = reg.issues.length === 0 ? [] : ['', `issues (${reg.issues.length}):`, ...reg.issues.map((i) => ` ${i}`)]
126 const s = sample(rows)
127 return block(`${rows.length} placeholders · type ${prefix}name anywhere in a prompt`, [...lines, ...issues], [
128 `Caret on a token: the band shows up to ${FOCUS_MAX} rows of what it sends · whole text: \`${showCommand(prefix, [s])}\`${hasQuery ? `, or \`${prefix}${s}?\` alone + Enter twice` : ''} · \`/placeholders list\` for all`,
129 `Send one message as typed: put \`${prefix}/\` anywhere in it`,
130 `\`${PLAN_LABEL.plus}\`: its \`<name>.plan.md\` adds text in Plan mode; \`<name>.md\` is sent in every mode`,
131 `Add, change, remove: \`/placeholders <your words>\` in any language, e.g. \`/placeholders add ${prefix}db: use the staging DB\``,
132 `Where: global = all projects (\`${dirs.global}\`), project = this one (\`${dirs.project}\`, wins over global); start with \`global\` or \`project\`, or just say it`,
133 'Commands (`list`, `show`, `help`) are only faster; plain words work too · full help: `/placeholders help`',
134 ])
135}
136
137export function helpText(prefix: string = DEFAULT_PREFIX, dirs: Dirs = DEFAULT_DIRS, hasQuery = true): string {
138 const p = prefix
139 return [
140 `placeholders help · a placeholder is a short token (${p}name) that adds saved text to your prompt`,
141 `Use: type \`${p}m\` anywhere in a prompt; Tab completes; the band above the prompt shows what each token sends.`,
142 `Caret on a token (arrows, Home, End): the band shows up to ${FOCUS_MAX} rows of what it sends; \`?\` right after the token only makes room for those rows while the name menu is open.`,
143 `Whole text, printed in the chat, not sent to Claude: \`${showCommand(p, ['r'])}\` (several: \`${showCommand(p, ['r', 'm'])}\`)${hasQuery ? ` · or \`${p}r?\` alone in a message: Enter fills that command, Enter again prints it` : ''} · all: \`/placeholders list\`.`,
144 `Send as typed: \`${p}/\` (or \`${p}\\\`) anywhere in a message turns every placeholder in it off; the marker stays in the text.`,
145 `Plan mode: \`<name>.md\` is sent in every mode; an optional \`<name>.plan.md\` (\`plan: add\`) adds its text in Plan mode (\`${p}m\`, \`${p}+\`), marked \`${PLAN_LABEL.plus}\`. One review per message: \`${p}rr\` wins over \`${p}r\`.`,
146 `Add, change, remove: \`/placeholders <your words, any language>\`; Claude drafts, asks once, saves. E.g. \`/placeholders add ${p}db: use the staging DB\` · \`/placeholders global make ${p}r shorter\` · \`/placeholders удали ${p}db\` · \`/placeholders add a plan-mode part to ${p}db: plan first, then build\`.`,
147 `Remove: \`/placeholders remove ${p}db\` (both parts) · \`/placeholders удали план у ${p}db\` (plan part only) · removing your override brings the built-in back; built-ins cannot be removed.`,
148 `Where: global = all projects, \`${dirs.global}/<name>.md\`; project = this project, \`${dirs.project}/<name>.md\`, wins over global; plugin defaults sit below both. A first word \`global\` or \`project\` decides, else your words do; unclear -> one question, Global first. A change keeps its layer; a remove asks when the name is in both.`,
149 'Files: `<name>.md` = optional front matter (description, insert: context|inline, order, group, priority, header) + the text; `<name>.plan.md` = its Plan mode addition. Edit by hand any time; the next prompt reads it.',
150 `Prefix: \`/config\` -> Placeholder prefix (2-8 punctuation characters, default \`${DEFAULT_PREFIX}\`).`,
151 `Commands: \`/placeholders\` status · \`list\` · \`show ${p}<name> ...\` · \`help\` · anything else goes to Claude. Commands are shortcuts; plain words work too.`,
152 `Docs: ${DOCS_URL}`,
153 `README: ${README_URL}`,
154 ].join('\n')
155}
156
157// A part in its own fence; an empty one says so instead. sent = the length the cap applies to (an added part is sent joined).
158const part = (label: string, text: string, sent: number = text.length): string =>
159 text === '' ? `${label} (empty, sends nothing)` : block(`${label}${sent > MAX_CHARS ? ` (cut at ${MAX_CHARS} chars when sent)` : ''}`, text.split('\n'))
160
161function nameBlock(reg: Registry, r: NameRow, prefix: string, isPlan: boolean): string {
162 const tag = tagOf(r)
163 const head = `\`${prefix}${r.name}\` · ${r.layer}${tag === '' ? '' : ` · ${tag}`}`
164 if (r.inline) {
165 const body = inlineBodies(reg.defs).get(r.name)
166 if (body !== undefined) return [head, part('replaces the token with:', body)].join('\n')
167 // Only a normal inline def with a body expands; any other stays as typed.
168 const d = reg.defs.find((x) => x.name.toLowerCase() === r.name && x.insert === 'inline')
169 return [head, d === undefined || d.body === '' ? `${REASON.staysAsTyped} (empty)` : part(`${REASON.staysAsTyped}; its text:`, d.body, 0)].join('\n')
170 }
171 const p = planParts(reg.defs, r.name, prefix)
172 if (p.kind === 'add') {
173 // Plan mode sends one block: the plan header when it has one, the normal body, then the part.
174 const joined = sentText(r.name, reg.defs, prefix, true).text
175 if (isPlan) return [head, part('normal + plan mode part:', joined)].join('\n')
176 return [head, part('normal:', p.normal), part(PLAN_LABEL.adds, p.plan, joined.length)].join('\n')
177 }
178 // An empty plan part adds nothing, but its header still heads the plan-mode block.
179 return [head, part('normal:', isPlan ? sentText(r.name, reg.defs, prefix, true).text : p.normal)].join('\n')
180}
181
182// show (names) or list (null): one block per name; unknown names are listed at the foot.
183export function fullText(reg: Registry, names: readonly string[] | null, prefix: string = DEFAULT_PREFIX, isPlan = false): string {
184 const rows = nameRows(reg, prefix)
185 const mode = `full text as sent · plan mode ${isPlan ? 'on' : 'off'}`
186 const blocks = (picked: readonly NameRow[]): string[] => picked.map((r) => nameBlock(reg, r, prefix, isPlan))
187 if (names === null) return [`${rows.length} placeholders · ${mode}`, ...blocks(rows), 'Add, change, remove: `/placeholders <your words>`'].join('\n')
188 const keys = names.map((n) => n.toLowerCase())
189 const unknown = keys.filter((k) => !rows.some((r) => r.name === k))
190 const foot = unknown.length === 0 ? [] : [`unknown: ${unknown.map((n) => `\`${prefix}${n}\``).join(', ')} · names: /placeholders list`]
191 return [`${keys.map((k) => prefix + k).join(', ')} · ${mode}`, ...blocks(keys.flatMap((k) => rows.filter((r) => r.name === k))), ...foot].join('\n')
192}
193hooks/lib/inline.ts 79 lines1// Pure helpers: inline expansion of a submitted prompt and the unknown-token list for the toast. Zero I/O.
2
3import type { Compiled } from './compiled'
4import type { Def } from './defs'
5import { scanDraft, type Matchers } from './match'
6
7// Origins whose text is the person's own typed prompt; every other kind (notifications, peers, schedules) is left alone.
8const INLINE_ORIGINS: ReadonlySet<string> = new Set(['composer', 'bridge', 'sdk'])
9
10export type SubmitLike = { origin: { kind: string }; command?: unknown; isMeta?: unknown }
11
12// prompt.submit has no mode: expansion needs a real person's prompt, no slash command, and no isMeta (a rewrite of those prompts is partial or absent).
13export function isInlineSubmit(e: SubmitLike): boolean {
14 return INLINE_ORIGINS.has(e.origin.kind) && e.command === undefined && e.isMeta === undefined
15}
16
17// Lowercase name -> body. Only normal (non-plan) `insert: inline` defs with a non-empty body; first wins per name.
18// A name that also has a normal context def is excluded entirely, so one token can never be inserted twice (inline + context).
19export function inlineBodies(defs: readonly Def[]): Map<string, string> {
20 const contextNames = new Set<string>()
21 for (const d of defs) if (d.insert === 'context' && !d.isPlan) contextNames.add(d.name.toLowerCase())
22 const out = new Map<string, string>()
23 for (const d of defs) {
24 const key = d.name.toLowerCase()
25 if (d.insert !== 'inline' || d.isPlan || d.body === '' || contextNames.has(key) || out.has(key)) continue
26 out.set(key, d.body)
27 }
28 return out
29}
30
31// One pass over the original text (no body re-scan here); the command hook later expands context tokens a body carries, as brewtools did. Null = nothing to change.
32// Plan-part inline defs and empty bodies stay verbatim; inline text has no block header.
33export function expandInline(c: Compiled, text: string): string | null {
34 if (!text.includes(c.prefix)) return null
35 const bodies = inlineBodies(c.defs)
36 if (bodies.size === 0) return null
37 const known = scanDraft(c.matchers, text)
38 .tokens.filter((t) => t.isKnown)
39 .sort((a, b) => a.start - b.start || b.end - a.end)
40
41 let out = ''
42 let at = 0
43 let changed = false
44 for (const t of known) {
45 if (t.start < at) continue
46 const body = bodies.get(t.name)
47 if (body === undefined) continue
48 out += text.slice(at, t.start) + body
49 at = t.end
50 changed = true
51 }
52 return changed ? out + text.slice(at) : null
53}
54
55const MAX_NAMED = 5
56
57const CODE_SPAN = /```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`/g
58const CODE_NEXT = /[;)[\]]/
59
60// Unknown `prefix+word` tokens of a prompt: unique (case-insensitive), first-seen order, original spelling.
61// Code is not a typo: tokens inside fences or backticks, or closed by `;` `)` `[` `]` (`++i)`, `a[++i]`), are left out.
62export function unknownTokens(ms: Matchers, text: string): string[] {
63 const seen = new Set<string>()
64 const out: string[] = []
65 const plain = text.replace(CODE_SPAN, (m) => ' '.repeat(m.length))
66 for (const t of scanDraft(ms, plain).tokens) {
67 if (t.isKnown || seen.has(t.text.toLowerCase()) || CODE_NEXT.test(text.charAt(t.end))) continue
68 seen.add(t.text.toLowerCase())
69 out.push(t.text)
70 }
71 return out
72}
73
74export function unknownMessage(tokens: readonly string[]): string {
75 const shown = tokens.slice(0, MAX_NAMED).join(', ')
76 const more = tokens.length > MAX_NAMED ? ` and ${tokens.length - MAX_NAMED} more` : ''
77 return `unknown ${shown}${more} · sent as typed · names: /placeholders list`
78}
79