/pane-peek or %word in the prompt: search panes of every herdr workspace, insert a [herdr-id:...] chip for the chosen one, and read marked panes for Claude…

A Claude Code mod for people who run their sessions inside herdr. Type /pane-peek, search the panes of every workspace, press Enter, and a [herdr-id:w1E:p4] marker for that pane lands in your prompt, so you can tell Claude exactly which pane to look at or act on. Already halfway through a prompt? Type % and pick the pane from the typeahead instead.
https://github.com/user-attachments/assets/6443c4ac-5dab-417b-83a4-4331b475ced6
In a Claude Code terminal session:
/plugin install pane-peek --marketplace arthurseredaa/herdr-pane-peek
Answer y to add the marketplace, then pick a scope (user scope makes it available in every session).
| Key | Does |
|---|---|
/pane-peek | opens the picker; the search field has the keyboard |
| type | filters panes; every word must match the workspace, tab, folder, agent kind, status, session title, pane id or path (~/…) (career claude finds Claude sessions in a workspace called career-ops); a pane the words name is listed before one that only mentions them in its session title or path |
| Enter in the search field | inserts the row marked ❯ (the first match until you move) |
| ↑ ↓ / Tab, then Enter | pick another row and insert it |
| Esc | closes without inserting |
The pane lands in the prompt at the cursor as a marker with a trailing space: [herdr-id:w1E:p4] . Keep typing around it: "[herdr-id:w1E:p4] why do the tests fail there?". The marker is drawn as a chip in your theme's suggestion colors, and Backspace or Delete next to it removes the whole marker. A toast says where the pane lives (workspace/tab · ~/path). If the prompt cannot take text, the marker is copied to the clipboard instead.
Panes are grouped under their workspace. Each row is ● tab · claude idle · my-project — session title: the dot is green for done, yellow for idle, blue for working, red for blocked and grey for a plain shell, and agents that are blocked or working are listed first inside their workspace. The session title is drawn dim, and where a tab is split into several panes the row says which one: tab/p4, the pane part of its id. The counter beside the search field shows matches/total. The pane you are in is left out of the list; type this to find it (it is marked (this)). The list refreshes every 5 seconds while the picker is open; if herdr stops answering, the picker says why and offers no panes until it answers again.
Type % anywhere in a prompt and the panes are listed in the typeahead, the way files are for @: "compare this with %car". What follows the % filters as the picker's search does; a token cannot hold a space, so separate words with commas (%career,claude). Tab inserts the first row, ↓ ↑ then Enter another, and the %word becomes the marker. Enter with no row highlighted sends the prompt as it stands. The list holds eight panes at most and is read again from herdr once it is 5 seconds old. If the picker is open when you type the %, it closes: the typeahead takes over. The marker gets its chip colors at your next keystroke.
When you send a prompt that contains markers, the mod reads each marked pane first (herdr pane read, the last 120 lines, at most 3 panes) and hands the snapshot to Claude beside your message, with where the pane lives: its workspace, tab and cwd, and what runs in it. A pane that could not be read, or a marker past the third, is named to Claude and a toast tells you. Claude answers from it in one step instead of loading a skill and running the command itself, which is much faster. The snapshot is taken when you press Enter, and it goes to the model, so keep that in mind for panes that show secrets. To act in a pane (send input, run something) Claude still uses the herdr skill below.
Reading works on its own: the mod attaches the pane to your message and says what the marker refers to. To let Claude do things in a pane (send input, run a command, prompt the agent running there), install the official herdr skill, which explains herdr panes and the herdr CLI. The word herdr in the marker is what makes Claude load it. Install it once:
npx skills add herdrdev/herdr --skill herdr -g -a claude-code
-a claude-code (add -y to skip the confirmations). Without -g it installs into the current project only.herdr --skill prints the copy that ships with it (the copy on GitHub can be newer).Optional: herdr integration install claude adds a hook that lets herdr see Claude's state precisely, so the statuses in the picker are more accurate. It changes your Claude Code hooks, so it is not done for you.
herdr CLI on PATH; HERDR_PANE_ID is how the mod marks your own pane).git clone git@github.com:arthurseredaa/herdr-pane-peek.git
cd herdr-pane-peek
claude --plugin-dir . # load it from the folder; saving a file reloads the mod
claude plugin validate . # manifest, marketplace and hooks
claude plugin test . # the *.test.ts files
hooks/register.tsx: the hooks (command, pane drawing, focus tracking, pick, the % typeahead).hooks/peek.ts: pure helpers (herdr api snapshot parsing, filtering, row labels, the marker and its chip behaviour).types/index.d.ts: the $.state contract.tsconfig.json extends a file Claude Code writes into .claude-plugin/types/ the first time it loads the mod, so tsc -p . works after one load.MIT
hooks/register.tsx 278 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { PeekPane } from '../types'
5import {
6 MAX_PANES,
7 READ_LINES,
8 decorate,
9 describeOrigin,
10 effective,
11 expandDeletion,
12 filterPanes,
13 formatToken,
14 herdrError,
15 layoutRows,
16 notRun,
17 paneContext,
18 paneUnreadable,
19 panesSkipped,
20 parseSnapshot,
21 rowParts,
22 statusColor,
23 suggestRow,
24 tokenIds,
25 tokenQuery,
26} from './peek'
27
28const PANE = 'pane-peek'
29const REFRESH_MS = 5_000
30const PANE_ROWS = 20
31const SUGGEST_ROWS = 8
32
33const panes = atom({ plugin: 'pane-peek', key: 'panes' } as const, [])
34const query = atom({ plugin: 'pane-peek', key: 'query' } as const, '')
35const selected = atom({ plugin: 'pane-peek', key: 'selected' } as const, null)
36const error = atom({ plugin: 'pane-peek', key: 'error' } as const, null)
37const isLoaded = atom({ plugin: 'pane-peek', key: 'isLoaded' } as const, false)
38
39function said(failure: unknown): string {
40 return failure instanceof Error ? failure.message : String(failure)
41}
42
43/** Every pane herdr has; throws with what went wrong, worded for the picker's error line. */
44async function snapshot($: EngineInterface): Promise<PeekPane[]> {
45 const got = await $.process.run(['herdr', 'api', 'snapshot'], { timeoutMs: 5000 }).catch(failure => {
46 throw new Error(notRun(said(failure)))
47 })
48 if (got.exitCode !== 0) throw new Error(`herdr: ${herdrError(got.stderr, got.exitCode)}`)
49 const [thisPane, home] = [await $.env.get('HERDR_PANE_ID'), await $.env.get('HOME')]
50 try {
51 return parseSnapshot(got.stdout, thisPane, home)
52 } catch (failure) {
53 throw new Error(`herdr: its snapshot could not be read (${said(failure)})`)
54 }
55}
56
57async function refresh($: EngineInterface) {
58 try {
59 const found = await snapshot($)
60 await update($, panes, () => found)
61 await update($, error, () => null)
62 await update($, isLoaded, () => true)
63 } catch (failure) {
64 await update($, error, () => said(failure))
65
66 return
67 }
68}
69
70/** One marked pane's recent output, or why herdr gave none: a pane that fails costs only itself. */
71async function readPane($: EngineInterface, paneId: string): Promise<{ output: string } | { problem: string }> {
72 try {
73 const got = await $.process.run(
74 ['herdr', 'pane', 'read', paneId, '--source', 'recent-unwrapped', '--lines', String(READ_LINES)],
75 { timeoutMs: 5000 },
76 )
77
78 return got.exitCode === 0 ? { output: got.stdout } : { problem: herdrError(got.stderr, got.exitCode) }
79 } catch (failure) {
80 return { problem: notRun(said(failure)) }
81 }
82}
83
84async function setQuery($: EngineInterface, value: string) {
85 await update($, query, () => value)
86 await update($, selected, () => null)
87}
88
89async function highlight($: EngineInterface, paneId: string) {
90 await update($, selected, () => paneId)
91}
92
93/** Closes the pane first: while it holds the keys the prompt box refuses a fill. */
94async function pick($: EngineInterface, paneId: string) {
95 await $.ui.close({ id: PANE })
96 const token = formatToken(paneId)
97 const found = (await read($, panes)).find(p => p.paneId === paneId)
98 const from = found === undefined ? paneId : describeOrigin(found)
99 const filled = await $.prompt.fill({ text: `${token} `, mode: 'insert', decorations: decorate(token) })
100 if (filled.isFilled) {
101 $.ui.toast(`inserted pane from ${from}`)
102 } else {
103 await $.ui.copy({ text: token })
104 $.ui.toast(`copied pane from ${from} (the prompt would not take it)`)
105 }
106}
107
108async function pickFirst($: EngineInterface) {
109 // the rows are not drawn while herdr does not answer: Enter has nothing to act on
110 if ((await read($, error)) !== null) return
111 const list = filterPanes(await read($, panes), await read($, query))
112 const target = effective(list, await read($, selected))
113 if (target !== undefined) await pick($, target.paneId)
114}
115
116export const register: Register = on => {
117 let isOpen = false
118 let suggestedAt: number | null = null
119
120 on('session.start', async ($, e, next) => {
121 await $.command.register({
122 name: 'pane-peek',
123 description: 'Pick a herdr pane from any workspace and put its id in the prompt',
124 immediate: true,
125 })
126 $.clock.every(REFRESH_MS, () => {
127 if (isOpen) void refresh($)
128 })
129
130 return next(e)
131 })
132
133 on('command.run', { command: 'pane-peek' }, async $ => {
134 isOpen = true
135 await update($, query, () => '')
136 await update($, selected, () => null)
137 await $.ui.open({ id: PANE, title: 'herdr panes', focus: true, closeOnEscape: true, rows: PANE_ROWS })
138 await refresh($)
139
140 return {}
141 })
142
143 // The chips live in the draft as plain text: repaint them after every edit and
144 // let a deletion that touches one take the whole of it.
145 on('prompt.edit', async ($, e, next) => {
146 const done = await next(e)
147 const widened = e.inputText === '' ? expandDeletion(e.text, e.start, e.end) : null
148 const text = widened?.text ?? done.text
149 const cursor = widened?.cursor ?? done.cursor
150
151 return { ...done, text, cursor, decorations: [...(done.decorations ?? []), ...decorate(text)] }
152 }).catch(($, e, next) => next(e))
153
154 // `%word` anywhere in the draft: the picker's search without leaving the prompt box.
155 on('prompt.autocomplete', { token: /^%/ }, async ($, e, next) => {
156 const rest = await next(e)
157 // the person is choosing in the prompt box now: one list of panes, not two
158 if (isOpen) {
159 await $.ui.close({ id: PANE })
160 isOpen = false
161 }
162 const now = await $.clock.now()
163 if (suggestedAt === null || now - suggestedAt >= REFRESH_MS) {
164 await refresh($)
165 suggestedAt = now
166 }
167 if ((await read($, error)) !== null) return rest
168 const rows = filterPanes(await read($, panes), tokenQuery(e.token)).slice(0, SUGGEST_ROWS).map(suggestRow)
169
170 return { suggestions: [...rest.suggestions, ...rows] }
171 }).catch(($, e, next) => next(e))
172
173 // A marked pane is read here, once, so the model answers from the snapshot
174 // instead of loading the skill and running `herdr pane read` itself.
175 on('prompt.submit', async ($, e, next) => {
176 const ids = tokenIds(e.text)
177 if (ids.length === 0) return next(e)
178
179 const known = await snapshot($).catch((): PeekPane[] => [])
180 const blocks: string[] = []
181 const unread: string[] = []
182 for (const id of ids.slice(0, MAX_PANES)) {
183 const got = await readPane($, id)
184 if ('output' in got) {
185 blocks.push(paneContext(id, got.output, known.find(p => p.paneId === id)))
186 } else {
187 blocks.push(paneUnreadable(id, got.problem))
188 unread.push(`${id} (${got.problem})`)
189 }
190 }
191 const skipped = ids.slice(MAX_PANES)
192 if (skipped.length > 0) blocks.push(panesSkipped(skipped))
193 // The model is told in its context; the person sent the prompt believing the panes went with it.
194 const told = [
195 ...(unread.length > 0 ? [`could not read ${unread.join(', ')}`] : []),
196 ...(skipped.length > 0 ? [`read the first ${MAX_PANES} panes, not ${skipped.join(', ')}`] : []),
197 ]
198 if (told.length > 0) $.ui.toast(`pane-peek: ${told.join('; ')}`)
199
200 return next({ ...e, context: [...(e.context ?? []), ...blocks] })
201 }).catch(($, e, next) => next(e))
202
203 on('ui.close', async ($, e, next) => {
204 if (e.id === PANE) isOpen = false
205
206 return next(e)
207 })
208
209 on('ui.focus', async ($, e, next) => {
210 const moved = await next(e)
211 if (e.requestId === PANE && e.element?.startsWith('row:') === true && moved.deny === undefined) {
212 await highlight($, e.element.slice('row:'.length))
213 }
214
215 return moved
216 })
217
218 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
219 // herdr is a terminal tool; the mobile surface has no text field to draw.
220 if (e.surface === 'mobile') return next(e)
221 const { Box, Button, Input, Text } = $.ui.resolve(e)
222 const all = await read($, panes)
223 const q = await read($, query)
224 const problem = await read($, error)
225 const isReading = problem === null && !(await read($, isLoaded))
226 const columns = e.props.bodyColumns ?? 80
227 // what herdr last listed is not offered once it stops answering: those panes may be gone
228 const list = problem === null ? filterPanes(all, q) : []
229 const total = Math.max(list.length, all.filter(p => !p.isThis).length)
230 const target = effective(list, await read($, selected))
231 // lines the rows and headings may take: all but the search line, the hint and a "more" line
232 const { groups, hidden } = layoutRows(list, Math.max(3, (e.viewport?.rows ?? PANE_ROWS) - 3))
233
234 return (
235 <Box flexDirection="column">
236 <Box>
237 <Box flexGrow={1}>
238 <Input
239 key="q"
240 autoFocus
241 placeholder="search…"
242 value={q}
243 submitLabel="insert"
244 onInput={value => setQuery($, value)}
245 onSubmit={() => pickFirst($)}
246 />
247 </Box>
248 {problem === null && !isReading && <Text dimColor>{` ${list.length}/${total}`}</Text>}
249 </Box>
250 {problem !== null && <Text color="error">{problem}</Text>}
251 {isReading && <Text color="inactive">Reading herdr…</Text>}
252 {problem === null && !isReading && list.length === 0 && <Text color="inactive">No panes found.</Text>}
253 {groups.map(g => (
254 <Box key={`ws:${g.workspaceId}`} flexDirection="column">
255 <Text bold color="claude">{g.workspace}</Text>
256 {g.panes.map(p => {
257 const { name, title } = rowParts(p, columns - 4)
258
259 return (
260 <Box key={`pane:${p.paneId}`}>
261 <Text color="claude">{p.paneId === target?.paneId ? '❯' : ' '}</Text>
262 <Text color={statusColor(p.status)}>● </Text>
263 <Button plain key={`row:${p.paneId}`} onPress={() => pick($, p.paneId)}>
264 {name}
265 <Text dimColor>{title}</Text>
266 </Button>
267 </Box>
268 )
269 })}
270 </Box>
271 ))}
272 {hidden > 0 && <Text color="inactive">{`… ${hidden} more, narrow the search`}</Text>}
273 <Text color="inactive">↑↓ choose · ⏎ insert · esc close</Text>
274 </Box>
275 )
276 })
277}
278hooks/peek.ts 308 lines1import type { PromptAutocompleteSuggestion, PromptDecoration } from 'claude-code'
2
3import type { PeekPane } from '../types'
4
5type Snapshot = {
6 result?: {
7 snapshot?: {
8 workspaces?: { workspace_id: string; label?: string; number?: number }[]
9 tabs?: { tab_id: string; label?: string; number?: number }[]
10 panes?: {
11 pane_id: string
12 workspace_id: string
13 tab_id: string
14 cwd?: string
15 terminal_title_stripped?: string
16 }[]
17 agents?: { pane_id: string; agent?: string; agent_status?: string; terminal_title_stripped?: string }[]
18 }
19 }
20}
21
22/** `cwd` with the home folder written `~`, where it lies inside it. */
23export function tilde(cwd: string, home: string | undefined): string {
24 const root = (home ?? '').replace(/\/+$/, '')
25 if (root === '') return cwd
26 if (cwd === root) return '~'
27
28 return cwd.startsWith(`${root}/`) ? `~${cwd.slice(root.length)}` : cwd
29}
30
31/** `herdr api snapshot` -> every pane of every workspace, in sidebar order. */
32export function parseSnapshot(json: string, thisPane: string | undefined, home?: string): PeekPane[] {
33 const snap = (JSON.parse(json) as Snapshot).result?.snapshot ?? {}
34 const workspaces = new Map((snap.workspaces ?? []).map(w => [w.workspace_id, w]))
35 const tabs = new Map((snap.tabs ?? []).map(t => [t.tab_id, t]))
36 const agents = new Map((snap.agents ?? []).map(a => [a.pane_id, a]))
37 const tabSizes = new Map<string, number>()
38 for (const p of snap.panes ?? []) tabSizes.set(p.tab_id, (tabSizes.get(p.tab_id) ?? 0) + 1)
39
40 const panes = (snap.panes ?? []).map((p): PeekPane => {
41 const ws = workspaces.get(p.workspace_id)
42 const tab = tabs.get(p.tab_id)
43 const agent = agents.get(p.pane_id)
44
45 return {
46 paneId: p.pane_id,
47 workspaceId: p.workspace_id,
48 workspace: ws?.label ?? p.workspace_id,
49 workspaceNo: ws?.number ?? 0,
50 tab: tab?.label ?? p.tab_id,
51 tabNo: tab?.number ?? 0,
52 isSplit: (tabSizes.get(p.tab_id) ?? 0) > 1,
53 agent: agent?.agent ?? null,
54 status: agent?.agent_status ?? 'shell',
55 title: agent?.terminal_title_stripped ?? p.terminal_title_stripped ?? '',
56 cwd: p.cwd ?? '',
57 path: tilde(p.cwd ?? '', home),
58 isThis: p.pane_id === thisPane,
59 }
60 })
61
62 // Array.prototype.sort is stable: panes keep herdr's order among equals.
63 return panes.sort((a, b) => a.workspaceNo - b.workspaceNo || attention(a) - attention(b) || a.tabNo - b.tabNo)
64}
65
66/** Within a workspace the agents that need a look come first: blocked, working, other agents, shells. */
67function attention(p: PeekPane): number {
68 if (p.agent === null) return 3
69 if (p.status === 'blocked') return 0
70 if (p.status === 'working') return 1
71
72 return 2
73}
74
75export function base(cwd: string): string {
76 return cwd.split('/').filter(Boolean).pop() ?? cwd
77}
78
79/**
80 * Every word of `query` must occur in what the pane's row shows, its id or its path.
81 * A pane the words name (workspace, tab, kind, folder, id) comes before one that only
82 * mentions them (session title, path), its workspace's panes staying together.
83 * The pane you are in is left out of an empty search and found by the word "this".
84 */
85export function filterPanes(panes: PeekPane[], query: string): PeekPane[] {
86 const words = query.toLowerCase().split(/\s+/).filter(Boolean)
87 const wantsThis = words.includes('this')
88 const pool = wantsThis ? panes : panes.filter(p => !p.isThis)
89 if (words.length === 0) return pool
90
91 const found = pool.flatMap(p => {
92 const name = [p.paneId, p.workspace, p.tab, kindOf(p), base(p.cwd), p.isThis ? 'this' : ''].join(' ').toLowerCase()
93 const mention = `${sessionTitle(p)} ${p.path}`.toLowerCase()
94 const unnamed = words.filter(w => !name.includes(w))
95
96 return unnamed.every(w => mention.includes(w)) ? [{ pane: p, unnamed: unnamed.length }] : []
97 })
98 // a workspace stands where its best pane does, then in list order
99 const places = new Map<string, { best: number; order: number }>()
100 for (const { pane, unnamed } of found) {
101 const place = places.get(pane.workspaceId)
102 places.set(pane.workspaceId, { best: Math.min(place?.best ?? unnamed, unnamed), order: place?.order ?? places.size })
103 }
104 const at = (id: string) => places.get(id)!
105
106 // Array.prototype.sort is stable: panes keep the list's order among equals.
107 return found
108 .sort((a, b) => {
109 const [wa, wb] = [at(a.pane.workspaceId), at(b.pane.workspaceId)]
110
111 return wa.best - wb.best || wa.order - wb.order || a.unnamed - b.unnamed
112 })
113 .map(f => f.pane)
114}
115
116export function clip(line: string, columns: number): string {
117 return line.length > columns ? `${line.slice(0, Math.max(1, columns - 1))}…` : line
118}
119
120function kindOf(p: PeekPane): string {
121 return p.agent === null ? 'shell' : `${p.agent} ${p.status}`
122}
123
124/** `tab · kind · folder`, what a pane is called inside its workspace; in a split tab, `tab/p4`: the pane part of its id. */
125function paneName(p: PeekPane): string {
126 const tab = p.isSplit ? `${p.tab}/${p.paneId.split(':').pop()}` : p.tab
127
128 return `${tab} · ${kindOf(p)} · ${base(p.cwd)}${p.isThis ? ' (this)' : ''}`
129}
130
131/** An agent's session title; a shell's title only repeats its cwd. */
132function sessionTitle(p: PeekPane): string {
133 return p.agent !== null ? p.title : ''
134}
135
136/**
137 * The row's text in two parts, the title drawn dim after the name; it gives way first where the row is narrow.
138 * The workspace is the group heading above and the status dot is drawn beside.
139 */
140export function rowParts(p: PeekPane, columns: number): { name: string; title: string } {
141 const name = clip(paneName(p), columns)
142 const title = sessionTitle(p)
143 const room = columns - name.length
144
145 // less than ` — a…` says nothing
146 return { name, title: title === '' || room < 5 ? '' : clip(` — ${title}`, room) }
147}
148
149/** The search a `%word,word` token asks for: a token holds no spaces, so commas stand in for them. */
150export function tokenQuery(token: string): string {
151 return token.slice(1).replaceAll(',', ' ')
152}
153
154/** The typeahead row for a pane: taking it writes the marker over the token. */
155export function suggestRow(p: PeekPane): PromptAutocompleteSuggestion {
156 const title = sessionTitle(p)
157
158 return {
159 text: `${formatToken(p.paneId)} `,
160 label: `${p.workspace} · ${paneName(p)}`,
161 ...(title === '' ? {} : { description: title }),
162 }
163}
164
165/** Theme keys, so the dots follow the person's theme. */
166export function statusColor(status: string): 'ide' | 'warning' | 'success' | 'error' | 'inactive' {
167 if (status === 'working') return 'ide'
168 if (status === 'blocked') return 'error'
169 if (status === 'idle') return 'warning'
170 if (status === 'done') return 'success'
171
172 return 'inactive'
173}
174
175export type Group = { workspaceId: string; workspace: string; panes: PeekPane[] }
176
177/** Panes grouped by workspace in list order, cut to `room` lines (a heading costs one); `hidden` counts the panes cut. */
178export function layoutRows(list: PeekPane[], room: number): { groups: Group[]; hidden: number } {
179 const groups: Group[] = []
180 let used = 0
181 let shown = 0
182 for (const p of list) {
183 const last = groups[groups.length - 1]
184 const opens = last?.workspaceId !== p.workspaceId
185 if (used + (opens ? 2 : 1) > room) break
186 if (opens) groups.push({ workspaceId: p.workspaceId, workspace: p.workspace, panes: [p] })
187 else last.panes.push(p)
188 used += opens ? 2 : 1
189 shown += 1
190 }
191
192 return { groups, hidden: list.length - shown }
193}
194
195/** The pane Enter acts on: the ring's row if it is still listed, else the first. */
196export function effective(list: PeekPane[], selected: string | null): PeekPane | undefined {
197 return list.find(p => p.paneId === selected) ?? list[0]
198}
199
200/** What the prompt gets for a picked pane: a marker the herdr skill can recognise. */
201export function formatToken(paneId: string): string {
202 return `[herdr-id:${paneId}]`
203}
204
205export type Span = { start: number; end: number }
206
207const MARKER = /\[herdr-id:([^\]\s]+)\]/g
208
209export function findTokens(text: string): Span[] {
210 return [...text.matchAll(MARKER)].map(m => ({ start: m.index, end: m.index + m[0].length }))
211}
212
213/** Theme keys, so the chip follows the person's theme: Claude's suggestion accent behind inverse text. */
214const CHIP = { color: 'inverseText', backgroundColor: 'suggestion', bold: true } as const
215
216export function decorate(text: string): PromptDecoration[] {
217 return findTokens(text).map(span => ({ ...span, ...CHIP }))
218}
219
220/**
221 * A deletion that touches a token takes the whole token with it, like a placeholder chip.
222 * `[start, end)` is the span the edit removed from `text`, the draft before the edit.
223 * Returns the draft and cursor after the widened deletion, or null when no token is touched.
224 */
225export function expandDeletion(text: string, start: number, end: number): { text: string; cursor: number } | null {
226 let from = start
227 let to = end
228 for (const t of findTokens(text)) {
229 if (t.start < to && t.end > from) {
230 from = Math.min(from, t.start)
231 to = Math.max(to, t.end)
232 }
233 }
234 if (from === start && to === end) return null
235
236 return { text: text.slice(0, from) + text.slice(to), cursor: from }
237}
238
239/** Where a pane lives, for the toast: `workspace/tab · ~/path`. */
240export function describeOrigin(p: PeekPane): string {
241 return `${p.workspace}/${p.tab} · ${p.path}`
242}
243
244export const READ_LINES = 120
245export const MAX_PANES = 3
246const MAX_CHARS = 20_000
247
248/** The distinct pane ids named by `[herdr-id:...]` markers in `text`, in order; the first MAX_PANES are read. */
249export function tokenIds(text: string): string[] {
250 return [...new Set([...text.matchAll(MARKER)].map(m => m[1]!))]
251}
252
253/** What herdr said went wrong: the message of its JSON error, else its words as written, else the exit code. */
254export function herdrError(stderr: string, exitCode: number): string {
255 const text = stderr.trim()
256 try {
257 const message = (JSON.parse(text) as { error?: { message?: unknown } }).error?.message
258 if (typeof message === 'string' && message !== '') return message
259 } catch {
260 // not JSON: plain words, or nothing
261 }
262
263 return text || `exit ${exitCode}`
264}
265
266/** Why a herdr command never ran: said in one line when herdr is not installed, as the engine worded it otherwise. */
267export function notRun(reason: string): string {
268 return reason.includes('ENOENT') ? 'herdr is not on PATH; is this session inside herdr?' : reason
269}
270
271/** Where a marked pane lives and what runs in it; the cwd in full, so the model can open what the output names. */
272function placeOf(p: PeekPane): string {
273 const session = p.title === '' ? '' : `, session "${p.title}"`
274 const runs = p.agent === null ? 'a plain shell' : `running ${p.agent} (${p.status})${session}`
275
276 return `It is in workspace "${p.workspace}", tab "${p.tab}", cwd ${p.cwd}, ${runs}.`
277}
278
279/** A fence the output cannot close: longer than any run of backticks in it. */
280function fenceFor(body: string): string {
281 const longest = Math.max(0, ...[...body.matchAll(/`+/g)].map(m => m[0].length))
282
283 return '`'.repeat(Math.max(3, longest + 1))
284}
285
286/** What the model reads beside the prompt for one marked pane; `pane` is herdr's record of it, when it has one. */
287export function paneContext(paneId: string, output: string, pane?: PeekPane): string {
288 const body = output.trim() === '' ? '(the pane is empty)' : output.trimEnd().slice(-MAX_CHARS)
289 const fence = fenceFor(body)
290 const place = pane === undefined ? '' : ` ${placeOf(pane)}`
291
292 return [
293 `Contents of herdr pane ${paneId}, read when the prompt was sent (\`herdr pane read ${paneId} --source recent-unwrapped --lines ${READ_LINES}\`); a snapshot, not live. The user's marker [herdr-id:${paneId}] refers to this pane.${place} To act in a pane (send input, run commands) use the herdr skill.`,
294 fence,
295 body,
296 fence,
297 ].join('\n')
298}
299
300export function paneUnreadable(paneId: string, detail: string): string {
301 return `The user marked herdr pane ${paneId} but it could not be read (${detail}). Use the herdr skill to find out why if it matters.`
302}
303
304/** The markers past MAX_PANES: named, so the model knows they are there and were not read. */
305export function panesSkipped(paneIds: string[]): string {
306 return `The user also marked herdr ${paneIds.length === 1 ? 'pane' : 'panes'} ${paneIds.join(', ')}, not read: only the first ${MAX_PANES} marked panes are. Use the herdr skill to read one if it matters.`
307}
308types/index.d.ts 33 lines1export type PeekPane = {
2 paneId: string
3 workspaceId: string
4 workspace: string
5 workspaceNo: number
6 tab: string
7 tabNo: number
8 /** Its tab holds other panes too: the row then names the pane as well. */
9 isSplit: boolean
10 /** Agent kind (`claude`) when herdr recognises one, else null: a plain shell. */
11 agent: string | null
12 status: string
13 title: string
14 cwd: string
15 /** `cwd` with the home folder written `~`: what the toast shows and the search reads. */
16 path: string
17 isThis: boolean
18}
19
20declare module 'claude-code' {
21 interface PluginState {
22 'pane-peek': {
23 panes: PeekPane[]
24 query: string
25 /** The row the focus ring last stood on; Enter in the search field picks it. */
26 selected: string | null
27 error: string | null
28 /** herdr has answered at least once: an empty list then means no panes, not none read yet. */
29 isLoaded: boolean
30 }
31 }
32}
33