A backlog of items needing your attention, parked by you or the orchestrator, kept per session and listed across them

A Claude Code mod that keeps a backlog of things that need your attention, so they don't scroll away during long agentic sessions.
When you orchestrate subagents, the main agent relays job reports full of findings, questions and decisions. You can't deal with all of them as they arrive, and after an unattended run you'd otherwise have to search the transcript for them. With this mod the agent parks each one as it comes up, and you work through them later in a side pane.
park, resolve, list_parked) and a system-prompt section telling it when to use them. Items are either needs attention (a deferred decision, an unanswered question, a blocker, a finding to act on) or FYI (a finished job, a notable finding, an assumption made on your behalf).a in the list accepts the agent's pick on every item that has one. l on an item scrolls the conversation back to where it came up. /parked work tells the agent to go through its own list.u takes back the last thing done in the pane: a done, an answer, a reopen, or every default accepted at once. An answer not yet sent is never sent./park parks that text instead of the last reply.a accepts the agent's pick, and w lets you answer in your own words. Accepting the pick of work already under way sends nothing. Other answers are gathered for three seconds and sent to the main agent as one message./park [note] parks the assistant's last reply./parked opens the backlog: needs attention, FYI, then done. Nothing is deleted; done items can be reopened.📌 2 need attention · 1 FYI./parked chat shows it, and hides it again). Open an item's side thread and ask about it: a subagent starts at once, investigates with tools, and its reply appears as it is written. A briefing made from the main session's context takes longer to write and follows as a message to the subagent; the handover (its instructions and that briefing) is kept on the thread for you to read. The thread stays out of the main transcript, and the main agent cannot read it./resume names the session; v widens the list to every session of the project, then to every session. An answer you give to another session's item is sent to that session's agent when it is next open.This mod uses Claude Code's function-hooks plugin API.
Clone it into your personal skills folder, where Claude Code loads it in every session:
git clone https://github.com/BuddyLim/claude-code-mod-parked ~/.claude/skills/parked
Or clone it anywhere and load it for one session:
claude --plugin-dir /path/to/claude-code-mod-parked
Run /parked. The pane opens with the keyboard: its letters and digits are shortcuts until you press Esc, which closes it. /parked project and /parked all open it on a wider list.
| Key | Does |
|---|---|
j k | move the cursor |
o | open the item |
v | the next scope: this session, this project, every session |
Click the list once and the arrow keys, Enter, → and l work too. Arrow keys only reach a pane's region after a click; that is a limit of the plugin API, not a choice.
An item is one page the pane scrolls: its actions, its options, then two sections of which one is open at a time, the ticket and the side thread.
1–9 answer with that option; a accepts the default; w opens a text field for an answer in your own words (a number typed there picks that option).d done, r reopen, n next, p previous, b back to the list.t opens the side thread in the ticket's place, and the ticket again. The thread's text field is drawn only while the thread is open, so a closed thread takes no keys.i puts the cursor in the thread's text field. Enter sends; Enter on an empty line leaves the field, and the letters are shortcuts again.x shows or hides the handover the thread's subagent was started with.s sends the thread's summary to the main agent, once the subagent has replied.PgUp and PgDn scroll the page. While a reply is being written the page stays at its end, unless you have scrolled up./parked lab switches the list between its keyboard region and a list of standard buttons, where 1–9 open a row.
claude plugin validate . # check the manifest and hooks module
claude plugin test . # run the tests
/parked trace prints what the side threads' plumbing last did (a question's stages, each subagent step's pieces, a scroll that was refused), for when a reply does not show as it is written.
hooks/register.tsx: the hooks module: tools, commands, storage, the pane.hooks/detail.tsx: the list's keyboard region.hooks/backlog.ts: the backlog's logic, free of the engine.types/index.d.ts: the state contract.tests/parked.test.ts: the tests.MIT
hooks/register.tsx 2436 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { ParkedItem, ParkedLive, ParkedMessage } from '../types'
5import { FOLDER_COLOR, STAR_COLOR, refIcon } from './kit/icons'
6import { PAD, cut } from './kit/layout'
7import {
8 EMPTY,
9 ICON,
10 TITLE_ROWS,
11 ageOf,
12 answer,
13 answerOf,
14 answersNote,
15 briefRequest,
16 defaultsOf,
17 describe,
18 digestOf,
19 doneNote,
20 excerptOf,
21 fitTables,
22 BRIEFING,
23 BRIEFING_LATE,
24 callLabel,
25 handoff,
26 handoverOf,
27 inScope,
28 investigationPrompt,
29 isReminderDue,
30 ownOpen,
31 reminderOf,
32 isBacklog,
33 knowSession,
34 markdownOf,
35 mergedRuns,
36 migrate,
37 nextScope,
38 orderOf,
39 park,
40 pathOfRef,
41 restore,
42 placeOfRef,
43 pruned,
44 reopen,
45 reportIn,
46 resolve,
47 resultLine,
48 workPrompt,
49 say,
50 sayOnce,
51 sayReply,
52 sent,
53 sessionLabel,
54 sessionNameOf,
55 statusText,
56 summaryRequest,
57 syncSession,
58 tildeOf,
59 titleOf,
60 unsend,
61 unsentOf,
62} from './backlog'
63import type { Backlog, Here } from './backlog'
64
65const PANE = 'parked'
66// The row every view of the pane leaves clear above it.
67const TOP = 1
68const PARK = 'mcp__parked__park'
69const RESOLVE = 'mcp__parked__resolve'
70const LIST = 'mcp__parked__list_parked'
71
72// Every session's items, and what each session that parked some is called.
73const items = atom({ plugin: 'parked', key: 'items' } as const, [])
74const sessions = atom({ plugin: 'parked', key: 'sessions' } as const, {})
75// Which of them the pane lists: this session's until the user asks for more.
76const scope = atom({ plugin: 'parked', key: 'scope' } as const, 'session')
77// The id of the item the pane shows in full; 0 while it shows the list.
78const selected = atom({ plugin: 'parked', key: 'selected' } as const, 0)
79// The ids of the items whose side thread awaits its subagent's reply.
80const pending = atom({ plugin: 'parked', key: 'pending' } as const, [])
81// What each of those subagents has written so far, by item id.
82const live = atom({ plugin: 'parked', key: 'live' } as const, {})
83// An item's view is two sections of which one is open at a time: the ticket,
84// or the side thread with its composer. A closed thread draws no text field,
85// so nothing takes the keys from the pane's own shortcuts.
86const section = atom({ plugin: 'parked', key: 'section' } as const, 'ticket')
87// Whether an item offers its side thread at all. Off for now: the section,
88// its composer and its shortcuts are not drawn, and nothing reaches `ask`.
89// `/parked chat` switches it. Threads already kept stay in the store.
90const chat = atom({ plugin: 'parked', key: 'chat' } as const, false)
91// Whether a thread's handover to its subagent is shown in full.
92const isBriefOpen = atom({ plugin: 'parked', key: 'isBriefOpen' } as const, false)
93// Whether the list is the keyboard view (a Client region) where the surface has one.
94const lab = atom({ plugin: 'parked', key: 'lab' } as const, true)
95// The last key pressed on one of the list's own letter buttons, and how many
96// have been: the keyboard region answers each new count as a key of its own.
97const nudge = atom({ plugin: 'parked', key: 'nudge' } as const, { key: '', n: 0 })
98// Whether the composer, the pane's own text field, has the focus ring.
99const typing = atom({ plugin: 'parked', key: 'typing' } as const, false)
100// What a letter button has typed for the composer while the text field itself
101// did not get the key; the field is drawn with it.
102const draft = atom({ plugin: 'parked', key: 'draft' } as const, '')
103// What the text field holds as the user types. The field is one line and
104// cuts what does not fit, so a long message is shown whole above it.
105const typedNow = atom({ plugin: 'parked', key: 'typed' } as const, '')
106// The item whose side thread the next prompt typed in Claude Code's own prompt
107// box goes to, instead of to the main agent; 0 while none does. The pane's
108// text field is one line: the prompt box wraps, takes a paste and several
109// lines, and keeps its history.
110const armed = atom({ plugin: 'parked', key: 'armed' } as const, 0)
111// Whether what the composer sends is the user's answer for the main agent,
112// not a question for the side thread's subagent.
113const answering = atom({ plugin: 'parked', key: 'answering' } as const, false)
114// Whether the lens mod is drawing in this pane. A pane cannot hand the
115// keyboard to another, so a file opened from an item is shown here: this pane
116// draws one row, the way back, and lens draws its file view beneath it. Lens
117// reads this value; it is true only where lens is loaded to draw.
118const guest = atom({ plugin: 'parked', key: 'guest' } as const, false)
119// What tells that lens is loaded: its own state, which only it writes.
120const LENS_VIEW = { plugin: 'lens', key: 'view' } as const
121// The file of an item shown in the item itself, so reading a reference needs
122// no other pane; null while none is.
123const peek = atom({ plugin: 'parked', key: 'peek' } as const, null)
124// The place last asked to be shown: the lens mod, where loaded, opens it.
125const jump = atom({ plugin: 'parked', key: 'jump' } as const, null)
126
127// How long after the last answer the batch of them is sent, so several items
128// answered in a row reach the main agent as one message.
129const FLUSH_MS = 3000
130// Whether the main loop is in a turn; a subagent's run raises no `turn.start`.
131let isRunning = false
132// The timer that sends the batch of answers, while one is waiting.
133let flushTimer: { cancel: () => void } | undefined
134
135// The user's home folder, which the pane writes `~`; read once.
136let home: string | undefined
137
138// The assistant's own items it was last reminded of, and the prompts since.
139// Kept by the host, not the module: a reload of the mod must not start the
140// count over, or every reload would bring the reminder again.
141const reminded = atom({ plugin: 'parked', key: 'reminded' } as const, { ids: '', turns: 0 })
142// The colour of what the assistant parked for itself.
143const SELF_COLOR = '#b48ead'
144
145// How often what the subagents have written is passed on to the pane.
146const LIVE_MS = 120
147// What each running subagent has written in the step it is on, by agent id.
148// The module's own: a reload ends the streams it was reading.
149const heard = new Map<string, ParkedLive>()
150// The id of each of those calls, in the same order: a result names its call
151// by id, and is drawn under it.
152const heardIds = new Map<string, string[]>()
153// Which of the open item's files have changed since it was parked.
154const changed = atom({ plugin: 'parked', key: 'changed' } as const, [])
155// The last thing done that can be taken back, with the items as they were.
156const undo = atom({ plugin: 'parked', key: 'undo' } as const, null)
157// The session last told what was waiting for it, so a reload says nothing.
158const greeted = atom({ plugin: 'parked', key: 'greeted' } as const, '')
159// The timer that passes it on, while a thread awaits a reply.
160let liveTimer: { cancel: () => void } | undefined
161let isTelling = false
162// Whether an item's view keeps to the end of a reply as it grows: until the
163// user scrolls up from the end, and again once they are back at it.
164let isFollowing = true
165// The item last shown in full, where the list's cursor waits on the way back.
166let lastShown = 0
167// A subagent hands its report back through a tool call of this name.
168const HANDBACK = /handback/i
169// How many of a run's tool calls are kept with its reply.
170const CALLS_KEPT = 40
171
172// What the side threads' plumbing last did, newest last, for `/parked trace`:
173// a reply that does not show as it is written is traced from here.
174const TRACE_KEPT = 120
175const trace: string[] = []
176const began = Date.now()
177const traced = (line: string) => {
178 trace.push(`${((Date.now() - began) / 1000).toFixed(1)}s ${line}`)
179 trace.splice(0, Math.max(0, trace.length - TRACE_KEPT))
180}
181
182// The thread's input is keyed by how many messages the user has sent, so each
183// send draws a fresh, empty field.
184const askKey = (item: ParkedItem) =>
185 `ask-${item.id}-${(item.thread ?? []).filter(one => one.role === 'you').length}`
186
187const GUIDE = `# Parked items
188
189This session has a backlog of parked items the user reviews later in a pane, often after leaving the session unattended. Keep it current with the ${PARK}, ${RESOLVE} and ${LIST} tools.
190
191Park an item with kind "needs-you" for: a decision you deferred to the user, a question you could not answer, a blocker, or a finding the user must act on.
192Park an item with kind "fyi" for: a completed job worth knowing about, a notable finding, or an assumption you made on the user's behalf.
193Park an item with kind "self" for something you mean to come back to yourself, which the user need not act on: a follow-up you deferred, a check to run again later, cleanup you promised, a problem you noticed outside the task at hand. That list is your own. The user can read it but is not asked to do anything, so never use it for a question or a decision that is theirs. Park the item at the moment you defer the thing, not later from memory. Before you tell the user a piece of work is finished, call ${LIST} and either do each of your own open items or say plainly which is left open and why. You are reminded of them as the session goes on.
194Park one item per distinct thing to address, not one per report. Give each a short title and a body that stands on its own: what is needed from the user and the relevant findings. Do not park routine progress.
195Write the body as Markdown with real line breaks; the pane draws it as it draws a reply. Open with one or two sentences saying what is needed, leave a blank line, then give the findings. Put every bullet and every numbered step on a line of its own, never several run together in one paragraph, and leave a blank line between paragraphs. Put a diagram, a command, a file listing or any text whose spacing matters in a fenced code block, and findings that compare things in a table. Leave the options and the refs out of the body: they are drawn from their own fields.
196When an item is a choice, give "options" (short labels, nine at most) and "default", the number of the one you would pick; the user sees that one listed first, as option 1. Set "blocking" to true only when no remaining work can go on without the answer; otherwise go ahead on your default and leave the item open for the user to accept or overturn. Name the places an item is about in "refs", each a path or path:line.
197The user's answers arrive as a prompt that begins "My answers to parked items", and each answered item is already done: do not resolve it again. An answer that differs from your default replaces it, so revise what you built on the default.
198When the user has addressed an item in conversation, or you have done one of your own, call ${RESOLVE} with its id and a one-line record of the outcome.
199Call ${LIST} when resuming work or when unsure what is open. It lists this session's items; the user may also keep items from other sessions, which are theirs to bring up.`
200
201// Who parked an item, and the ledger task or unit it belongs to ('' for none).
202const parkerOf = (item: ParkedItem) =>
203 item.origin !== undefined ? 'the ledger' : item.parkedBy === 'user' ? 'you' : 'the agent'
204const tagOf = (item: ParkedItem) =>
205 item.origin?.kind === 'review' ? item.origin.unit : (item.task ?? '')
206
207const SUBAGENT_REFUSAL =
208 'Only the main agent parks items. Report this finding to the orchestrator in your final answer instead.'
209
210// One backlog for every session and folder. It was once kept per folder, under
211// a key that moved with the session's working directory.
212const KEY = 'backlog'
213const OLD = 'backlog:'
214
215const hereOf = async ($: EngineInterface): Promise<Here> => ({
216 sessionId: await $.session.id(),
217 project: await $.session
218 .root()
219 .catch(() => $.session.cwd())
220 .catch(() => ''),
221})
222
223const load = async ($: EngineInterface): Promise<Backlog> => {
224 const stored = await $.store.get(KEY)
225
226 if (isBacklog(stored)) {
227 return stored
228 }
229
230 // Nothing kept yet under the one key: what the folders kept is brought in,
231 // and stays where it was.
232 const keys = (await $.store.keys()).filter(key => key.startsWith(OLD))
233 const old = await Promise.all(keys.map(async key => [key.slice(OLD.length), await $.store.get(key)] as const))
234 const kept = old.filter((pair): pair is readonly [string, Backlog] => isBacklog(pair[1]))
235
236 return kept.length === 0 ? EMPTY : migrate(kept)
237}
238
239const show = async ($: EngineInterface, backlog: Backlog) => {
240 const here = await hereOf($)
241
242 await update($, items, () => backlog.items)
243 await update($, sessions, () => backlog.sessions ?? {})
244 // The status row is for this session's own items.
245 $.ui.status(statusText(inScope(backlog.items, 'session', here)))
246}
247
248// Reads the stored backlog, applies the change and writes it back; answers
249// the reason when the change was refused or the store failed.
250const changeNow = async (
251 $: EngineInterface,
252 apply: (backlog: Backlog) => Backlog | string,
253): Promise<{ backlog: Backlog } | { error: string }> => {
254 try {
255 const applied = apply(await load($))
256
257 if (typeof applied === 'string') {
258 return { error: applied }
259 }
260
261 const after = pruned(applied)
262 await $.store.set(KEY, after)
263 await show($, after)
264
265 return { backlog: after }
266 } catch (error) {
267 const reason = `Parked items could not be saved: ${error instanceof Error ? error.message : String(error)}`
268 $.ui.toast(reason)
269
270 return { error: reason }
271 }
272}
273
274// One change at a time. Two hooks recording the same reply would otherwise
275// both read the backlog before either wrote it, and both would add it.
276let changes: Promise<unknown> = Promise.resolve()
277
278const change = (
279 $: EngineInterface,
280 apply: (backlog: Backlog) => Backlog | string,
281): Promise<{ backlog: Backlog } | { error: string }> => {
282 const run = changes.then(() => changeNow($, apply))
283 changes = run.catch(() => undefined)
284
285 return run
286}
287
288// The items the pane lists now, as the scope has them.
289const listed = async ($: EngineInterface) =>
290 inScope(await read($, items), await read($, scope), await hereOf($))
291
292// Finds what /resume calls this session and keeps it with the backlog, so its
293// items are named by it wherever they are listed. The name is read off the
294// session's transcript, whose title rows the engine writes as the name changes.
295const nameSession = async ($: EngineInterface) => {
296 try {
297 const here = await hereOf($)
298 const backlog = await load($)
299
300 // A session is kept track of once it has items.
301 if (!backlog.items.some(one => one.sessionId === here.sessionId)) {
302 return
303 }
304
305 let transcript = backlog.sessions?.[here.sessionId]?.transcript
306
307 if (transcript === undefined) {
308 const home = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${(await $.env.get('HOME')) ?? ''}/.claude`
309 const found = await $.process.run(
310 ['find', `${home}/projects`, '-maxdepth', '2', '-name', `${here.sessionId}.jsonl`],
311 { timeoutMs: 10000 },
312 )
313 transcript = found.stdout.split('\n').find(line => line.trim() !== '')?.trim()
314 }
315
316 const name =
317 transcript === undefined
318 ? ''
319 : sessionNameOf((await $.process.run(['grep', '-o', '-E', TITLE_ROWS, transcript], { timeoutMs: 10000 })).stdout)
320 const seen = { name, project: here.project, ...(transcript !== undefined ? { transcript } : {}) }
321 const now = await $.clock.now()
322
323 if (knowSession(backlog, here.sessionId, seen, now) !== backlog) {
324 await change($, kept => knowSession(kept, here.sessionId, seen, now))
325 }
326 } catch {
327 // No transcript to read, or no way to read it: the session goes by its id.
328 }
329}
330
331// The main session's briefing for an item's subagent: one tool-less question
332// over the session's own transcript, which the main conversation never sees.
333// Empty when the session has nothing to fork or the call fails.
334const briefOf = async ($: EngineInterface, item: ParkedItem): Promise<string> => {
335 try {
336 const reply = await $.model.fork({ prompt: briefRequest(item) })
337
338 return reply.isAnswered ? reply.text.trim() : ''
339 } catch {
340 return ''
341 }
342}
343
344const wordsOf = (text: string) => text.split(/\s+/).filter(Boolean).length
345
346// Keeps an item's view at the end of what is being written, as a transcript
347// stays at the end of a reply, while the user has not scrolled away from it.
348// One move at a time, and nothing waits on it: a move that is slow to land
349// must not hold back the text it follows.
350let isScrolling = false
351
352const follow = ($: EngineInterface) => {
353 if (isScrolling || !isFollowing) {
354 return
355 }
356
357 isScrolling = true
358 void (async () => {
359 if ((await read($, section)) === 'thread' && (await read($, selected)) !== 0) {
360 const moved = await $.ui.scroll({ to: 'end', in: PANE })
361
362 if (moved.deny !== undefined) {
363 traced(`scroll denied: ${moved.deny}`)
364 }
365 }
366 })()
367 .catch(error => traced(`scroll failed: ${error instanceof Error ? error.message : String(error)}`))
368 .finally(() => {
369 isScrolling = false
370 })
371}
372
373// Says what a thread is waiting on before its subagent has written anything.
374const stage = ($: EngineInterface, item: ParkedItem, text: string) => {
375 traced(`#${item.id} ${text}`)
376
377 return update($, live, now => ({ ...now, [String(item.id)]: { text: '', tools: [], stage: text } }))
378}
379
380// Passes on to the pane what each waited-on subagent has written since the
381// last time, and stops once no thread awaits a reply.
382const tell = async ($: EngineInterface) => {
383 const waiting = await read($, pending)
384
385 if (waiting.length === 0) {
386 liveTimer?.cancel()
387 liveTimer = undefined
388 heard.clear()
389 heardIds.clear()
390 await update($, live, () => ({}))
391
392 return
393 }
394
395 const list = await read($, items)
396 const before = await read($, live)
397 const now: Record<string, ParkedLive> = {}
398
399 for (const id of waiting) {
400 const agentId = list.find(one => one.id === id)?.agentId
401 // Until its subagent writes, a thread keeps the stage it was last given.
402 const voice = (agentId === undefined ? undefined : heard.get(agentId)) ?? before[String(id)]
403
404 if (voice !== undefined) {
405 now[String(id)] = voice
406 }
407 }
408
409 if (JSON.stringify(now) !== JSON.stringify(before)) {
410 await update($, live, () => now)
411 follow($)
412 }
413}
414
415// Starts listening to the subagents' streams; `turn.step` reads them only
416// while this runs, so the main loop's own steps pass straight through.
417const listen = ($: EngineInterface) => {
418 liveTimer ??= $.clock.every(LIVE_MS, () => {
419 if (isTelling) {
420 return
421 }
422
423 isTelling = true
424 void tell($)
425 .catch(error => traced(`tell failed: ${error instanceof Error ? error.message : String(error)}`))
426 .finally(() => {
427 isTelling = false
428 })
429 })
430}
431
432// Writes the briefing for a subagent that has already started and sends it on
433// as a message. Writing it is one question put to the main session's model
434// and takes a while, which the subagent spends on what it can check itself.
435// What it was handed is kept on the thread, for the user to read.
436const briefLater = async ($: EngineInterface, item: ParkedItem, text: string, agentId: string) => {
437 const brief = await briefOf($, item)
438 const at = await $.clock.now()
439 await change($, backlog => {
440 const said = say(backlog, item.id, { role: 'brief', text: handoverOf(item, text, brief), at })
441
442 return typeof said === 'string'
443 ? said
444 : { ...said, items: said.items.map(one => (one.id === item.id ? { ...one, brief } : one)) }
445 })
446
447 if (brief === '') {
448 return
449 }
450
451 if ((await read($, pending)).includes(item.id)) {
452 const sent = await $.session
453 .send({ to: { agentId }, text: `${BRIEFING}\n${brief}\n\n${BRIEFING_LATE}` })
454 .catch(() => ({ isDelivered: false }))
455
456 if (sent.isDelivered) {
457 traced(`#${item.id} briefing sent to agent ${agentId}`)
458
459 return
460 }
461 }
462
463 // The subagent had replied by then: waking it for a briefing alone would be
464 // a second reply nobody asked for, so it goes with the user's next message.
465 traced(`#${item.id} briefing kept for the next message`)
466 await change($, backlog => ({
467 ...backlog,
468 items: backlog.items.map(one => (one.id === item.id ? { ...one, owed: brief } : one)),
469 }))
470}
471
472// Sends the user's message to the item's subagent: the one already on the
473// thread while this session still has it, else a fresh one given the thread.
474//
475// Called from the `ui.input` hook, never from the text field's own handler or
476// a timer: the engine passes a subagent's steps to this mod's `turn.step` hook
477// only when the subagent was started inside one of the mod's hooks, and its
478// reply can be shown as it is written only then.
479const ask = async ($: EngineInterface, item: ParkedItem, text: string) => {
480 const settle = () => update($, pending, list => list.filter(id => id !== item.id))
481 const fail = async (reason: string) => {
482 const at = await $.clock.now()
483 await change($, backlog => say(backlog, item.id, { role: 'agent', text: reason, at }))
484 await settle()
485 }
486
487 try {
488 const at = await $.clock.now()
489 const said = await change($, backlog => say(backlog, item.id, { role: 'you', text, at }))
490
491 if ('error' in said) {
492 return
493 }
494
495 isFollowing = true
496 await update($, pending, list => [...list.filter(id => id !== item.id), item.id])
497 listen($)
498 follow($)
499
500 // A subagent started any other way cannot be heard, and is replaced.
501 if (item.agentId !== undefined && item.isStreamed === true) {
502 await stage($, item, 'Passing your message to the side agent…')
503 const owed = item.owed
504 // The subagent may be gone, as after the session was closed and resumed:
505 // a message that cannot reach it starts a fresh one below.
506 const sent = await $.session
507 .send({
508 to: { agentId: item.agentId },
509 text: owed === undefined ? text : `${BRIEFING}\n${owed}\n\nThe user's message: ${text}`,
510 })
511 .catch(() => ({ isDelivered: false }))
512
513 if (sent.isDelivered) {
514 traced(`#${item.id} delivered to agent ${item.agentId}`)
515
516 if (owed !== undefined) {
517 await change($, backlog => ({
518 ...backlog,
519 items: backlog.items.map(one => {
520 const { owed: _o, ...rest } = one
521
522 return one.id === item.id ? rest : one
523 }),
524 }))
525 }
526
527 return
528 }
529 }
530
531 // The briefing is written once for an item. A subagent taking the thread
532 // over later (the first one gone with its session) starts with that one.
533 const kept = item.brief
534 await stage($, item, 'Starting the side agent…')
535 const spawned = await $.agent.spawn({
536 prompt: kept === undefined ? investigationPrompt(item, text, '', true) : investigationPrompt(item, text, kept),
537 description: `Parked #${item.id}: ${item.title}`.slice(0, 60),
538 })
539
540 if (spawned.agentId === undefined) {
541 await fail(`The subagent could not start: ${spawned.deny ?? 'no reason given'}`)
542
543 return
544 }
545
546 const agentId = spawned.agentId
547 traced(`#${item.id} agent ${agentId} started`)
548 await change($, backlog => ({
549 ...backlog,
550 items: backlog.items.map(one => {
551 const { owed: _o, ...rest } = one
552
553 return one.id === item.id ? { ...rest, agentId, isStreamed: true as const } : one
554 }),
555 }))
556
557 if (kept !== undefined) {
558 const noted = await $.clock.now()
559 await change($, backlog =>
560 say(backlog, item.id, {
561 role: 'note',
562 text: 'A fresh side agent took over this thread, with the same handover and the thread so far.',
563 at: noted,
564 }),
565 )
566
567 return
568 }
569
570 void briefLater($, item, text, agentId).catch(error =>
571 traced(`#${item.id} briefing failed: ${error instanceof Error ? error.message : String(error)}`),
572 )
573 } catch (error) {
574 await fail(`The subagent could not be reached: ${error instanceof Error ? error.message : String(error)}`)
575 }
576}
577
578// A subagent's report, read from its own transcript: it hands its report back
579// through a tool call, so its turn can end with no visible answer.
580const reportOf = async ($: EngineInterface, agentId: string): Promise<string> => {
581 const rows = await $.session.messages({ agentId })
582
583 if (!Array.isArray(rows)) {
584 return ''
585 }
586
587 for (const row of [...rows].reverse()) {
588 if (row.role !== 'assistant') {
589 continue
590 }
591
592 const handback = row.toolUses.findLast(use => HANDBACK.test(use.tool))
593 // The report is the hand-back's longest text argument.
594 const report = Object.values(handback?.input ?? {})
595 .filter((value): value is string => typeof value === 'string')
596 .sort((a, b) => b.length - a.length)[0]
597
598 if (report !== undefined && report.trim() !== '') {
599 return report.trim()
600 }
601
602 if (row.text.trim() !== '') {
603 return row.text.trim()
604 }
605 }
606
607 return ''
608}
609
610const goTo = async ($: EngineInterface, id: number) => {
611 isFollowing = true
612 lastShown = id === 0 ? lastShown : id
613 await update($, draft, () => '')
614 await update($, typedNow, () => '')
615 await update($, answering, () => false)
616 await update($, section, () => 'ticket')
617 await update($, isBriefOpen, () => false)
618 await update($, peek, () => null)
619 await update($, guest, () => false)
620 await update($, changed, () => [])
621
622 // A thread waits on the prompt box only while its item is the one shown.
623 if ((await read($, armed)) !== id) {
624 await disarm($)
625 }
626
627 await update($, selected, () => id)
628 // Not waited on: the item is shown at once, and its files are marked as
629 // each is looked at.
630 void markChanged($, id).catch(() => undefined)
631}
632
633// Marks which of an item's files were changed after it was parked, by each
634// file's time of last change: what the item says of such a file may be stale.
635const markChanged = async ($: EngineInterface, id: number) => {
636 const item = (await read($, items)).find(one => one.id === id)
637 const refs = item?.refs ?? []
638
639 if (item === undefined || refs.length === 0) {
640 return
641 }
642
643 home ??= (await $.env.get('HOME').catch(() => undefined)) ?? ''
644 const at = home
645 const stats = await Promise.all(
646 refs.map(ref =>
647 $.fs.stat(pathOfRef(item, ref, at)).then(
648 stat => stat.mtimeMs,
649 () => 0,
650 ),
651 ),
652 )
653 const late = stats.flatMap((time, index) => (time > item.createdAt ? [index] : []))
654
655 // The pane may have moved on to another item meanwhile.
656 if (late.length > 0 && (await read($, selected)) === id) {
657 await update($, changed, () => late)
658 }
659}
660
661// Keeps the items an action is about to change as they are now, so `u` can
662// put them back.
663const remember = async ($: EngineInterface, label: string, ids: readonly number[]) => {
664 const before = (await read($, items)).filter(one => ids.includes(one.id))
665
666 await update($, undo, () => ({ label, items: before }))
667}
668
669// Takes back the last thing done in the pane.
670const takeBack = async ($: EngineInterface) => {
671 const last = await read($, undo)
672
673 if (last === null) {
674 $.ui.toast('Parked: nothing to undo.')
675
676 return
677 }
678
679 let told: number[] = []
680 const changedBack = await change($, backlog => {
681 const restored = restore(backlog, last.items)
682 told = restored.told
683
684 return restored.backlog
685 })
686
687 if ('error' in changedBack) {
688 return
689 }
690
691 await update($, undo, () => null)
692 $.ui.toast(
693 told.length === 0
694 ? `Parked: undid "${last.label}".`
695 : `Parked: undid "${last.label}". The agent had already been told your answer to ${told.map(id => `#${id}`).join(', ')}: tell it if that no longer stands.`,
696 )
697}
698
699// Sets whether Esc closes the pane, where it is open: while a thread waits on
700// the prompt box, Esc must hand the keys to that box and leave the pane up.
701const escCloses = async ($: EngineInterface, isClosing: boolean) => {
702 const isUp = await $.ui.panes().then(
703 panes => panes.some(pane => pane.id === PANE),
704 () => false,
705 )
706
707 if (isUp) {
708 await $.ui
709 .open({ id: PANE, title: 'Parked', holdToasts: true, ...(isClosing ? { closeOnEscape: true as const } : {}) })
710 .catch(() => undefined)
711 }
712}
713
714// Makes an item's side thread the place the next typed prompt goes to.
715const arm = async ($: EngineInterface, item: ParkedItem) => {
716 await update($, section, () => 'thread')
717 await update($, armed, () => item.id)
718 await escCloses($, false)
719}
720
721const disarm = async ($: EngineInterface) => {
722 if ((await read($, armed)) !== 0) {
723 await update($, armed, () => 0)
724 await escCloses($, true)
725 }
726}
727
728// Gives the pane's text field the focus ring, so what is typed lands in it,
729// clicked or not. The field may be about to be drawn (a section opening, an
730// answer starting), so the ring is asked for now and again once it is there.
731const focusComposer = ($: EngineInterface, item: ParkedItem) => {
732 const focus = () => void $.ui.focus({ requestId: PANE, key: askKey(item) }).catch(() => undefined)
733
734 focus()
735 $.clock.after(80, focus)
736 $.clock.after(300, focus)
737}
738
739// Tells the main agent every answer it has not had, as one message. While a
740// turn runs the message goes into the prompt box, where the user's Enter
741// delivers it into that turn; a prompt a plugin submits waits for the turn's end.
742const flush = async ($: EngineInterface) => {
743 // The answers meant for this session are taken and marked sent in one change,
744 // before they are delivered: a second flush that starts while this one waits
745 // on the prompt finds none of them and so cannot send them again.
746 const sessionId = await $.session.id()
747 let list: ParkedItem[] = []
748 await change($, backlog => {
749 list = unsentOf(backlog.items, sessionId)
750
751 return sent(backlog, list.map(one => one.id))
752 })
753
754 if (list.length === 0) {
755 return
756 }
757
758 try {
759 await deliver($, list)
760 } catch (error) {
761 // Not delivered: they are unsent again, for the next flush to take.
762 await change($, backlog => unsend(backlog, list.map(one => one.id)))
763 throw error
764 }
765}
766
767const deliver = async ($: EngineInterface, list: readonly ParkedItem[]) => {
768 const text = answersNote(list)
769 const count = `${list.length} answer${list.length === 1 ? '' : 's'}`
770 let isFilled = false
771
772 if (isRunning) {
773 const box = await $.prompt.read().then(
774 read => read.text,
775 () => '',
776 )
777 const lead = box === '' || box.endsWith('\n') ? '' : '\n'
778 isFilled = await $.prompt.fill({ text: `${lead}${text}\n`, mode: 'append' }).then(
779 filled => filled.isFilled,
780 () => false,
781 )
782 }
783
784 if (!isFilled) {
785 await $.prompt.submit({ text })
786 }
787
788 $.ui.toast(
789 isFilled
790 ? `Parked: ${count} in the prompt box. Press Enter to send into the running turn.`
791 : `Parked: ${count} sent to the main agent.`,
792 )
793}
794
795// Sends the batch of answers once no new one has come for FLUSH_MS.
796const queueFlush = ($: EngineInterface) => {
797 flushTimer?.cancel()
798 flushTimer = $.clock.after(FLUSH_MS, () => {
799 flushTimer = undefined
800 void flush($).catch(() => undefined)
801 })
802}
803
804// Takes the agent's own pick on every listed item that has one, in one go.
805const acceptDefaults = async ($: EngineInterface) => {
806 const list = defaultsOf(await listed($))
807 const sessionId = await $.session.id()
808 const when = await $.clock.now()
809 let isOwed = false
810
811 if (list.length > 0) {
812 await remember($, `accept ${list.length} default${list.length === 1 ? '' : 's'}`, list.map(one => one.id))
813 }
814
815 for (const item of list) {
816 const made = answerOf(item, item.preferred ?? 0)
817 const changed = await change($, backlog => answer(backlog, item.id, item.preferred ?? 0, when, item.sessionId))
818
819 // A blocking item's agent is waiting to hear, default or not.
820 isOwed ||= !('error' in changed) && typeof made !== 'string' && !made.isSilent && item.sessionId === sessionId
821 }
822
823 if (isOwed) {
824 queueFlush($)
825 }
826
827 $.ui.toast(
828 list.length === 0
829 ? 'Parked: no listed item has a default to accept.'
830 : `Parked: accepted the default of ${list.length} item${list.length === 1 ? '' : 's'}.`,
831 )
832}
833
834// Answers the open item for the user: an option by its number, or their words.
835// The answer is for the agent of the session the item was parked in.
836const respond = async ($: EngineInterface, item: ParkedItem, value: number | string, isStaying = false) => {
837 const made = answerOf(item, value)
838
839 if (typeof made === 'string') {
840 $.ui.toast(made)
841
842 return
843 }
844
845 await remember($, `answer #${item.id}`, [item.id])
846
847 const order = orderOf(await listed($))
848 const when = await $.clock.now()
849 const isHere = item.sessionId === (await $.session.id())
850 const changed = await change($, backlog => answer(backlog, item.id, value, when, item.sessionId))
851
852 if ('error' in changed) {
853 $.ui.toast(changed.error)
854
855 return
856 }
857
858 if (made.isSilent) {
859 $.ui.toast(`Parked #${item.id}: default accepted. The agent already went that way.`)
860 } else if (isHere) {
861 $.ui.toast(`Parked #${item.id}: answer queued for the main agent.`)
862 queueFlush($)
863 } else {
864 const name = sessionLabel(changed.backlog.sessions, item.sessionId)
865 $.ui.toast(`Parked #${item.id}: answer kept for "${cut(name, 40)}". Its agent is told when that session is next open.`)
866 }
867
868 // Answered from the band above the prompt, the pane stays where it is.
869 if (isStaying) {
870 return
871 }
872
873 // On to the next open item, or back to the list when none is left.
874 const following = order.find(one => one.status === 'open' && one.id !== item.id)
875 await goTo($, following?.id ?? 0)
876}
877
878// A side thread in a few lines, written by a small model. Empty when the call
879// fails, and the hand-off then falls back to the start of the last reply.
880const summaryOf = async ($: EngineInterface, item: ParkedItem): Promise<string> => {
881 try {
882 const reply = await $.model.complete({
883 model: 'haiku',
884 prompt: summaryRequest(item),
885 maxTokens: 400,
886 timeoutMs: 30000,
887 })
888
889 return reply.isAnswered ? reply.text.trim() : ''
890 } catch {
891 return ''
892 }
893}
894
895// Runs one action on the open item.
896const perform = async ($: EngineInterface, item: ParkedItem, act: string) => {
897 const order = orderOf(await listed($))
898 const at = order.findIndex(one => one.id === item.id)
899
900 if (act === 'prev' || act === 'next') {
901 const to = order[at + (act === 'next' ? 1 : -1)]
902
903 if (to !== undefined) {
904 await goTo($, to.id)
905 }
906 } else if (act === 'host-back') {
907 await update($, guest, () => false)
908 } else if (act === 'undo') {
909 await takeBack($)
910 } else if (act === 'done' && item.status === 'open') {
911 await remember($, `done #${item.id}`, [item.id])
912 const when = await $.clock.now()
913 await change($, backlog => resolve(backlog, item.id, doneNote(item), 'user', when))
914 // On to the next open item, or back to the list when none is left.
915 const following = order.find(one => one.status === 'open' && one.id !== item.id)
916 await goTo($, following?.id ?? 0)
917 } else if (act === 'accept' && item.status === 'open' && item.preferred !== undefined) {
918 await respond($, item, item.preferred)
919 } else if (/^pick-[1-9]$/.test(act) && item.status === 'open') {
920 await respond($, item, Number(act.slice(5)))
921 } else if (/^go-\d+$/.test(act) && (item.refs ?? []).length > 0) {
922 // A file pressed in the item's list is shown in this pane.
923 const refs = item.refs ?? []
924 const shown = await read($, peek)
925 const at = Number(act.slice(3)) % refs.length
926 const named = placeOfRef(refs[at] ?? '')
927 home ??= (await $.env.get('HOME').catch(() => undefined)) ?? ''
928 const path = pathOfRef(item, refs[at] ?? '', home)
929
930 // Where lens is loaded, it opens in lens's own viewer, drawn here.
931 // Without lens, its lines are shown in the item instead.
932 const hasLens = await $.state.get(LENS_VIEW as never).then(
933 got => (got as { value?: unknown }).value !== undefined,
934 () => false,
935 )
936
937 if (hasLens) {
938 // Said first: lens reads it as it takes the place, and leaves its own
939 // pane shut when it is to draw here.
940 await update($, guest, () => true)
941 await update($, jump, last => ({ path, line: named.line, n: (last?.n ?? 0) + 1 }))
942
943 return
944 }
945
946 // Pressed again, the file shown is put away.
947 if (shown?.at === at) {
948 await update($, peek, () => null)
949
950 return
951 }
952
953 const text = await $.fs.read(path).then(
954 read => (typeof read === 'string' ? read : undefined),
955 () => undefined,
956 )
957 await update($, peek, () => ({
958 at,
959 path,
960 line: named.line,
961 ...(text === undefined
962 ? { start: 1, source: '', error: 'This file could not be read.' }
963 : excerptOf(text, named.line)),
964 }))
965 } else if (act === 'where' && item.source !== undefined) {
966 // The conversation is scrolled to the row the item came up at. A row that
967 // is not in this conversation (another session's, one compacted away) is
968 // not found.
969 const moved = await $.ui.scroll({ to: { requestId: item.source }, block: 'center' }).catch(() => ({ deny: 'no such row' }))
970
971 $.ui.toast(
972 moved.deny === undefined
973 ? `Parked #${item.id}: the conversation is at where this came up.`
974 : `Parked #${item.id}: where this came up is not in this conversation any more.`,
975 )
976 } else if (act === 'write' && item.status === 'open') {
977 await update($, answering, () => true)
978 focusComposer($, item)
979 } else if ((act === 'thread' || act === 'arm' || act === 'type' || act === 'send') && !(await read($, chat))) {
980 // The side thread is switched off: its shortcuts do nothing.
981 } else if (act === 'thread') {
982 // The two sections take turns: opening one closes the other.
983 isFollowing = true
984 await update($, section, now => (now === 'thread' ? 'ticket' : 'thread'))
985 follow($)
986 } else if (act === 'ticket') {
987 await update($, section, () => 'ticket')
988 } else if (act === 'arm') {
989 if ((await read($, armed)) === item.id) {
990 await disarm($)
991 } else {
992 await arm($, item)
993 }
994 } else if (act === 'type') {
995 await update($, section, () => 'thread')
996 focusComposer($, item)
997 } else if (act === 'brief') {
998 await update($, isBriefOpen, now => !now)
999 } else if (act === 'reopen') {
1000 await remember($, `reopen #${item.id}`, [item.id])
1001 await change($, backlog => reopen(backlog, item.id))
1002 } else if (act === 'send' && (item.thread ?? []).some(one => one.role === 'agent')) {
1003 $.ui.toast(`Parked #${item.id}: summarising the thread for the main agent…`)
1004 await $.prompt.submit({ text: handoff(item, await summaryOf($, item)) })
1005 $.ui.toast(`Parked #${item.id}: findings sent to the main agent.`)
1006 } else if (act === 'back') {
1007 await goTo($, 0)
1008 }
1009}
1010
1011// How many of a thread's messages are drawn: the newest, so a long thread
1012// stays a tree the pane can draw.
1013const THREAD_SHOWN = 12
1014
1015
1016export const register: Register = on => {
1017 on('session.start', async ($, e, next) => {
1018 // Answers a reload or a restart left unsent go out with the next batch, as
1019 // do those given to this session's items while it was closed.
1020 queueFlush($)
1021
1022 await $.command.register({
1023 name: 'park',
1024 description: "Park a note, or the assistant's last reply: /park <note> · /park · /park + <note> for both",
1025 })
1026 await $.command.register({
1027 name: 'parked',
1028 description:
1029 'Show parked items in a pane: this session’s, or /parked project · /parked all. /parked work hands the assistant its own list',
1030 })
1031 await $.tool.register({
1032 name: 'park',
1033 description:
1034 'Park an item for the user to review later, or for yourself. Use kind "needs-you" for decisions, unanswered questions, blockers and findings the user must act on; "fyi" for completed jobs, notable findings and assumptions made on their behalf; "self" for something you mean to come back to yourself, which the user need not act on.',
1035 inputSchema: {
1036 type: 'object',
1037 properties: {
1038 kind: { type: 'string', enum: ['needs-you', 'fyi', 'self'] },
1039 title: { type: 'string', description: 'One line naming the item' },
1040 body: {
1041 type: 'string',
1042 description:
1043 'What is needed from the user and the relevant findings; must stand on its own. Markdown with real line breaks: a short lead, a blank line, then the findings, each bullet on a line of its own; a fenced code block for a diagram, a command or anything whose spacing matters',
1044 },
1045 options: {
1046 type: 'array',
1047 items: { type: 'string' },
1048 maxItems: 9,
1049 description: 'For a choice: a short label per option, which the user picks by number',
1050 },
1051 default: {
1052 type: 'integer',
1053 description: 'The number of the option you would pick, 1 for the first',
1054 },
1055 blocking: {
1056 type: 'boolean',
1057 description:
1058 'True only when no remaining work can go on without the answer; otherwise proceed on your default',
1059 },
1060 refs: {
1061 type: 'array',
1062 items: { type: 'string' },
1063 description: 'The places the item is about, each a path or path:line',
1064 },
1065 task: {
1066 type: 'string',
1067 description: 'The id of the ledger task the item belongs to, when the ledger has a run',
1068 },
1069 },
1070 required: ['kind', 'title', 'body'],
1071 },
1072 })
1073 await $.tool.register({
1074 name: 'resolve',
1075 description: 'Mark a parked item done once the user has addressed it, or you have done one of your own.',
1076 inputSchema: {
1077 type: 'object',
1078 properties: {
1079 id: { type: 'number' },
1080 resolution: { type: 'string', description: 'One line on how it was addressed' },
1081 },
1082 required: ['id', 'resolution'],
1083 },
1084 })
1085 await $.tool.register({
1086 name: 'list_parked',
1087 description:
1088 'List the parked items of this session: open ones, and done ones if asked. With scope "project" or "all", those of other sessions too.',
1089 inputSchema: {
1090 type: 'object',
1091 properties: {
1092 includeDone: { type: 'boolean' },
1093 scope: { type: 'string', enum: ['session', 'project', 'all'] },
1094 },
1095 },
1096 })
1097
1098 try {
1099 await show($, await load($))
1100 } catch {
1101 $.ui.toast('Parked items could not be loaded.')
1102 }
1103
1104 // A session that opens with items of its own waiting is told so, once:
1105 // not again on a reload of the mod.
1106 try {
1107 const here = await hereOf($)
1108
1109 if ((await read($, greeted)) !== here.sessionId) {
1110 await update($, greeted, () => here.sessionId)
1111 const digest = digestOf(inScope((await load($)).items, 'session', here), await $.clock.now())
1112
1113 if (digest !== undefined) {
1114 $.ui.toast(digest, { timeoutMs: 8000 })
1115 }
1116 }
1117 } catch {
1118 // Nothing to say.
1119 }
1120
1121 // A reload while a thread awaited its reply: go on listening for it.
1122 if ((await read($, pending)).length > 0) {
1123 listen($)
1124 }
1125
1126 void nameSession($)
1127
1128 return next(e)
1129 })
1130
1131 on('prompt.compose', async ($, e, next) => {
1132 const composed = await next(e)
1133
1134 return {
1135 sections: [
1136 ...composed.sections,
1137 { id: 'parked:guide', text: GUIDE, scope: 'session' },
1138 ],
1139 }
1140 })
1141
1142 on('tool.call', { tool: PARK }, async ($, e) => {
1143 if (e.agentId !== undefined) {
1144 return { deny: SUBAGENT_REFUSAL }
1145 }
1146
1147 const { kind, title, body } = e
1148
1149 if (
1150 (kind !== 'needs-you' && kind !== 'fyi' && kind !== 'self') ||
1151 typeof title !== 'string' ||
1152 typeof body !== 'string' ||
1153 title.trim() === ''
1154 ) {
1155 return { deny: 'park needs kind ("needs-you", "fyi" or "self"), a title and a body.' }
1156 }
1157
1158 const texts = (value: unknown) =>
1159 Array.isArray(value) && value.every(one => typeof one === 'string' && one.trim() !== '')
1160 ? value.map(one => String(one).trim())
1161 : undefined
1162 const options = e.options === undefined ? [] : texts(e.options)
1163 const refs = e.refs === undefined ? [] : texts(e.refs)
1164 const preferred = e.default
1165
1166 if (options === undefined || options.length > 9 || refs === undefined) {
1167 return { deny: 'park takes options as at most nine short labels, and refs as paths or path:line.' }
1168 }
1169
1170 if (
1171 preferred !== undefined &&
1172 (typeof preferred !== 'number' || !Number.isInteger(preferred) || preferred < 1 || preferred > options.length)
1173 ) {
1174 return { deny: `park takes default as the number of one of its ${options.length} options, 1 for the first.` }
1175 }
1176
1177 const here = await hereOf($)
1178 const now = await $.clock.now()
1179 const changed = await change($, backlog =>
1180 park(backlog, {
1181 kind,
1182 title: title.trim(),
1183 body,
1184 options,
1185 ...(typeof preferred === 'number' ? { preferred } : {}),
1186 isBlocking: e.blocking === true,
1187 ...(typeof e.task === 'string' && e.task.trim() !== '' ? { task: e.task.trim() } : {}),
1188 refs,
1189 // The call's own row in the transcript is where the item came up.
1190 source: e.tool_use_id,
1191 parkedBy: 'model',
1192 ...here,
1193 now,
1194 }),
1195 )
1196
1197 if ('error' in changed) {
1198 return { deny: changed.error }
1199 }
1200hooks/kit/icons.ts 60 lines1// Shared by the lens, parked and ledger mods. The source is the mod-kit folder;
2// each mod carries a copy under hooks/kit, written there by sync.sh. Edit the
3// source and sync, never a copy.
4
5export type Icon = { glyph: string; color: string }
6
7// Nerd Font glyphs, as a terminal file tree draws them, in each language's
8// usual colour. They need a Nerd Font, or a terminal that ships the symbols.
9export const FILE_ICONS: readonly (readonly [pattern: RegExp, glyph: string, color: string])[] = [
10 [/\.pyi?$/, '\u{e73c}', '#ffd43b'],
11 [/\.[cm]?[tj]sx$/, '\u{e7ba}', '#20c2e3'],
12 [/\.[cm]?ts$/, '\u{e628}', '#519aba'],
13 [/\.[cm]?js$/, '\u{e74e}', '#cbcb41'],
14 [/\.json$/, '\u{e60b}', '#cbcb41'],
15 [/\.(tf|tfvars)$/, '\u{e69a}', '#7b42bc'],
16 [/\.(ya?ml|toml|ini|cfg|env)$/, '\u{e615}', '#6d8086'],
17 [/\.(md|mdx)$/, '\u{e73e}', '#dddddd'],
18 [/\.(sh|bash|zsh)$/, '\u{e795}', '#4d5a5e'],
19 [/\.(css|scss|less)$/, '\u{e749}', '#42a5f5'],
20 [/\.html?$/, '\u{e736}', '#e44d26'],
21 [/\.sql$/, '\u{e706}', '#dad8d8'],
22 [/\.(png|jpe?g|gif|svg|webp|ico)$/, '\u{f1c5}', '#a074c4'],
23 [/(^|\/)Dockerfile$/, '\u{f308}', '#458ee6'],
24 [/(^|\/)\.git(ignore|attributes)$/, '\u{e702}', '#f54d27'],
25 [/\.lock$/, '\u{f023}', '#bbbbbb'],
26]
27
28// The glyphs the mods draw for their own things, one name each.
29export const ICON = {
30 file: '\u{f15b}',
31 folder: '\u{f07b}',
32 folderOpen: '\u{f07c}',
33 needs: '\u{f059}',
34 blocking: '\u{f071}',
35 fyi: '\u{f05a}',
36 done: '\u{f058}',
37 failed: '\u{f057}',
38 running: '\u{f110}',
39 todo: '\u{f10c}',
40 thread: '\u{f075}',
41 options: '\u{f0cb}',
42 preferred: '\u{f005}',
43 tasks: '\u{f0ae}',
44 agents: '\u{f085}',
45 finding: '\u{f188}',
46} as const
47
48export const FILE_COLOR = '#6d8086'
49export const FOLDER_COLOR = '#dcb67a'
50export const STAR_COLOR = '#ffd43b'
51
52export const iconOf = (path: string): Icon => {
53 const hit = FILE_ICONS.find(([pattern]) => pattern.test(path))
54
55 return hit === undefined ? { glyph: ICON.file, color: FILE_COLOR } : { glyph: hit[1], color: hit[2] }
56}
57
58// The icon of a ref's file type; a ref is a path, or path:line.
59export const refIcon = (ref: string): Icon => iconOf(ref.replace(/:\d+(?::\d+)?$/, ''))
60hooks/kit/layout.ts 24 lines1// Shared by the lens, parked and ledger mods. The source is the mod-kit folder;
2// each mod carries a copy under hooks/kit, written there by sync.sh. Edit the
3// source and sync, never a copy.
4
5// The cells a pane leaves clear at each side.
6export const PAD = 2
7
8// Text no longer than `most`, an ellipsis standing for what was cut.
9export const cut = (text: string, most: number): string =>
10 text.length > most ? `${text.slice(0, Math.max(0, most - 1))}…` : text
11
12// How long ago `then` was, as one short word: minutes, hours, then days.
13export const ageOf = (then: number, now: number): string => {
14 const minutes = Math.max(0, Math.round((now - then) / 60000))
15
16 if (minutes < 60) {
17 return `${minutes}m`
18 }
19
20 const hours = Math.round(minutes / 60)
21
22 return hours < 48 ? `${hours}h` : `${Math.round(hours / 24)}d`
23}
24hooks/backlog.ts 1132 lines1import type { ParkedItem, ParkedKind, ParkedMessage, ParkedScope, ParkedSession } from '../types'
2import type { LedgerFindingSeen, LedgerRunSeen } from '../types/ledger'
3import { ICON, refIcon } from './kit/icons'
4
5// What of the ledger's run has already been turned into items: the tasks whose
6// gate stood failed, and the findings a review item has carried. An item is
7// made when one of these changes, so one the user closed is not made again.
8export type LedgerSeen = { gates: string[]; findings: number[] }
9
10// One backlog holds every session's items. `seen` is what the ledger's run has
11// been through in the one session a call is about; `ledger` keeps it for each
12// session, and `sessions` is what the pane names each session by.
13export type Backlog = {
14 nextId: number
15 items: ParkedItem[]
16 seen?: LedgerSeen
17 ledger?: Record<string, LedgerSeen>
18 sessions?: Record<string, ParkedSession>
19}
20
21export const EMPTY: Backlog = { nextId: 1, items: [] }
22
23export type NewItem = {
24 kind: ParkedKind
25 title: string
26 body: string
27 note?: string
28 options?: string[]
29 preferred?: number
30 isBlocking?: boolean
31 refs?: string[]
32 task?: string
33 origin?: ParkedItem['origin']
34 parkedBy: 'model' | 'user'
35 sessionId: string
36 project?: string
37 source?: string
38 now: number
39}
40
41export const isBacklog = (value: unknown): value is Backlog =>
42 typeof value === 'object' &&
43 value !== null &&
44 typeof (value as Backlog).nextId === 'number' &&
45 Array.isArray((value as Backlog).items)
46
47// The glyphs and their colours are the kit's, shared with lens and ledger.
48export { ICON }
49
50// The glyph of a ref's file type; a ref is a path, or path:line.
51export const fileIcon = (ref: string): string => refIcon(ref).glyph
52
53// The options with the preferred one first, so the default is always option 1.
54const defaultFirst = (options: readonly string[], preferred: number | undefined): string[] =>
55 preferred === undefined
56 ? [...options]
57 : [...options.slice(preferred - 1, preferred), ...options.slice(0, preferred - 1), ...options.slice(preferred)]
58
59export const park = (backlog: Backlog, item: NewItem): Backlog => ({
60 ...backlog,
61 nextId: backlog.nextId + 1,
62 items: [
63 ...backlog.items,
64 {
65 id: backlog.nextId,
66 kind: item.kind,
67 title: item.title,
68 body: tidyBody(item.body),
69 ...(item.note ? { note: item.note } : {}),
70 ...(item.options !== undefined && item.options.length > 0
71 ? { options: defaultFirst(item.options, item.preferred) }
72 : {}),
73 ...(item.preferred !== undefined ? { preferred: 1 } : {}),
74 ...(item.isBlocking === true ? { isBlocking: true as const } : {}),
75 ...(item.refs !== undefined && item.refs.length > 0 ? { refs: item.refs } : {}),
76 ...(item.task ? { task: item.task } : {}),
77 ...(item.origin !== undefined ? { origin: item.origin } : {}),
78 parkedBy: item.parkedBy,
79 sessionId: item.sessionId,
80 ...(item.project ? { project: item.project } : {}),
81 createdAt: item.now,
82 ...(item.source ? { source: item.source } : {}),
83 status: 'open',
84 },
85 ],
86})
87
88// A string answer is the reason the change was refused.
89export const resolve = (
90 backlog: Backlog,
91 id: number,
92 resolution: string,
93 resolvedBy: 'model' | 'user',
94 now: number,
95): Backlog | string => {
96 const item = backlog.items.find(one => one.id === id)
97
98 if (item === undefined) {
99 return `No parked item #${id}.`
100 }
101
102 if (item.status === 'done') {
103 return `Parked item #${id} is already done.`
104 }
105
106 return {
107 ...backlog,
108 items: backlog.items.map(one =>
109 one.id === id
110 ? { ...one, status: 'done', resolution, resolvedBy, resolvedAt: now }
111 : one,
112 ),
113 }
114}
115
116export const reopen = (backlog: Backlog, id: number): Backlog | string => {
117 const item = backlog.items.find(one => one.id === id)
118
119 if (item === undefined) {
120 return `No parked item #${id}.`
121 }
122
123 const { resolution: _r, resolvedBy: _b, resolvedAt: _a, answer: _w, answeredIn: _s, isUnsent: _u, ...rest } = item
124
125 return {
126 ...backlog,
127 items: backlog.items.map(one =>
128 one.id === id ? { ...rest, status: 'open' } : one,
129 ),
130 }
131}
132
133export const statusText = (items: readonly ParkedItem[]): string | undefined => {
134 const open = items.filter(one => one.status === 'open')
135 const needs = open.filter(one => one.kind === 'needs-you').length
136 const blocking = open.filter(one => one.kind === 'needs-you' && one.isBlocking === true).length
137 const fyi = open.filter(one => one.kind === 'fyi').length
138 const parts = [
139 needs > 0 ? `${needs} need${needs === 1 ? 's' : ''} attention${blocking > 0 ? ` (${blocking} blocking)` : ''}` : '',
140 fyi > 0 ? `${fyi} FYI` : '',
141 ].filter(Boolean)
142
143 // The row is for what waits on the person: FYIs alone are not worth one,
144 // and ride along only when something does need them.
145 return needs === 0 ? undefined : `📌 ${parts.join(' · ')}`
146}
147
148export const titleOf = (note: string, reply: string): string => {
149 const first =
150 note.trim() ||
151 (reply.split('\n').find(line => line.trim() !== '') ?? '').replace(/^[#>*\-\s]+/, '').trim()
152
153 return first.length > 80 ? `${first.slice(0, 79)}…` : first
154}
155
156import { ageOf } from './kit/layout'
157
158export { ageOf }
159
160// `from` names the session an item of another session was parked in.
161export const describe = (item: ParkedItem, from = ''): string =>
162 [
163 `#${item.id} [${item.kind}] ${item.title}${item.status === 'done' ? ' (done)' : ''}${from === '' ? '' : ` (parked in ${from})`}`,
164 item.note ? `Note: ${item.note}` : '',
165 item.isBlocking === true && item.status === 'open' ? 'Blocking: work is waiting on the user.' : '',
166 item.body,
167 item.options !== undefined
168 ? `Options: ${item.options.map((label, at) => `${at + 1}) ${label}`).join(' ')}${item.preferred !== undefined ? ` (default ${item.preferred})` : ''}`
169 : '',
170 item.refs !== undefined ? `Files: ${item.refs.join(', ')}` : '',
171 item.resolution ? `Resolution: ${item.resolution}` : '',
172 ]
173 .filter(Boolean)
174 .join('\n')
175
176// Adds a message to an item's side thread, and names the subagent answering it.
177export const say = (
178 backlog: Backlog,
179 id: number,
180 message: ParkedMessage,
181 agentId?: string,
182): Backlog | string => {
183 if (!backlog.items.some(one => one.id === id)) {
184 return `No parked item #${id}.`
185 }
186
187 return {
188 ...backlog,
189 items: backlog.items.map(one =>
190 one.id === id
191 ? {
192 ...one,
193 thread: [...(one.thread ?? []), message],
194 ...(agentId !== undefined ? { agentId } : {}),
195 }
196 : one,
197 ),
198 }
199}
200
201const lastOf = (item: ParkedItem, role: ParkedMessage['role']) =>
202 (item.thread ?? []).findLast(one => one.role === role)
203
204// What the user and the subagent said in a thread: the mod's own notes and the
205// handover it keeps there are not part of the conversation.
206const spoken = (item: ParkedItem) =>
207 (item.thread ?? []).filter(one => one.role === 'you' || one.role === 'agent')
208
209const INVESTIGATE = [
210 'You are helping the user look into one parked item from a long orchestration session, in a side thread the main agent does not see.',
211 'Investigate with your tools as far as the question needs, then answer the user directly and concisely. Do not change any files unless the user asks you to.',
212]
213
214// What a fresh subagent is told: the item, the thread so far and the new message.
215// The line a briefing sent on its own, after the subagent started, opens with.
216export const BRIEFING = 'Briefing from the main session, written for you from its full context:'
217
218// With `isBriefComing`, the briefing is still being written and follows as a
219// message: the subagent starts at once on what it can check itself.
220export const investigationPrompt = (item: ParkedItem, text: string, brief = '', isBriefComing = false): string =>
221 [
222 ...INVESTIGATE,
223 ...(isBriefComing
224 ? [
225 'A briefing from the main session, written from its full context, will reach you as a message within about half a minute. Start now with what you can check yourself, and take the briefing into account when it arrives.',
226 ]
227 : []),
228 '',
229 `Parked item #${item.id} [${item.kind}]: ${item.title}`,
230 item.body,
231 item.note ? `The user's note: ${item.note}` : '',
232 ...(brief.trim() !== '' ? ['', BRIEFING, brief.trim()] : []),
233 ...(spoken(item).length > 0
234 ? ['', 'Earlier in this thread:', ...spoken(item).map(one => `${one.role === 'you' ? 'User' : 'You'}: ${one.text}`)]
235 : []),
236 '',
237 `The user's message: ${text}`,
238 ]
239 .filter((line, index, all) => line !== '' || all[index - 1] !== '')
240 .join('\n')
241
242// The one message "Send to agent" posts to the main conversation.
243const cut = (text: string, most: number) => (text.length > most ? `${text.slice(0, most - 1)}…` : text)
244
245// What a small model is asked, to turn a side thread into the few lines the
246// main agent needs: the thread itself stays out of the main conversation.
247export const summaryRequest = (item: ParkedItem): string =>
248 [
249 'Below is a parked item from a coding session and a side thread in which the user and a subagent looked into it.',
250 'Summarise the thread for the main agent in at most 120 words: what was found, what the user decided or wants, and what the main agent should do next, if anything.',
251 'Plain text, no preamble, no headings. State only what the thread supports. If it reached no conclusion, say so in one line.',
252 '',
253 `Parked item #${item.id} [${item.kind}]: ${item.title}`,
254 cut(item.body, 4000),
255 '',
256 'Side thread:',
257 // The newest part of a long thread is the part that holds its conclusion.
258 spoken(item)
259 .map(one => `${one.role === 'you' ? 'User' : 'Subagent'}: ${one.text}`)
260 .join('\n\n')
261 .slice(-12000),
262 ].join('\n')
263
264// The one message "Send" posts to the main conversation: the thread's summary,
265// or, when none could be made, the start of the subagent's last reply.
266export const handoff = (item: ParkedItem, summary = ''): string => {
267 const finding = lastOf(item, 'agent')
268 const said = lastOf(item, 'you')
269
270 return [
271 `About parked item #${item.id}: ${item.title}`,
272 '',
273 ...(summary.trim() !== ''
274 ? ['Summary of a side thread I held with a subagent on this:', summary.trim()]
275 : [
276 'I looked into this in a side thread with a subagent. The start of its latest findings:',
277 cut(finding?.text ?? '(none yet)', 600),
278 ...(said !== undefined ? ['', `My last message there: ${cut(said.text, 300)}`] : []),
279 ]),
280 ].join('\n')
281}
282
283export const doneNote = (item: ParkedItem): string => {
284 const finding = lastOf(item, 'agent')
285
286 if (finding === undefined) {
287 return 'Marked done by you.'
288 }
289
290 const line = finding.text.replace(/\s+/g, ' ').trim()
291
292 return `Marked done by you after a side thread. Last finding: ${line.length > 140 ? `${line.slice(0, 139)}…` : line}`
293}
294
295// What the main session is asked, in a fork of its own context, so a thread's
296// subagent starts with the background an orchestrator would hand it.
297export const briefRequest = (item: ParkedItem): string =>
298 [
299 'This is a request for a handover, not a continuation of your work. Do not act on it or call tools.',
300 'A separate subagent is about to help the user look into the parked item below. It knows nothing about this session.',
301 'Write the briefing you would give it: the goal of the work this item came from; what was done and found that bears on it; the files, commands and names it will need; decisions already made; and what is still unknown.',
302 'Be specific and brief, in plain text with no preamble. If nothing in this session bears on the item, say so in one line.',
303 '',
304 `Parked item #${item.id} [${item.kind}]: ${item.title}`,
305 item.body,
306 ].join('\n')
307
308// The order the pane lists items in, which Next and Prev walk: open items that
309// need the user (those blocking work first), then open FYIs, then what the
310// assistant parked for itself, then the ten most recently parked done items.
311export const orderOf = (items: readonly ParkedItem[]): ParkedItem[] => {
312 const open = items.filter(one => one.status === 'open')
313
314 return [
315 ...open.filter(one => one.kind === 'needs-you' && one.isBlocking === true),
316 ...open.filter(one => one.kind === 'needs-you' && one.isBlocking !== true),
317 ...open.filter(one => one.kind === 'fyi'),
318 ...open.filter(one => one.kind === 'self'),
319 ...items.filter(one => one.status === 'done').slice(-10).reverse(),
320 ]
321}
322
323// A reply's text with spacing and Markdown marks removed, cut short: two
324// routes deliver the same report with different escaping and indentation.
325const gist = (text: string) => text.replace(/[\s\\*`_>#-]/g, '').slice(0, 80)
326
327// Adds a subagent's reply unless the thread already holds it since the user's
328// last message: its turn's end and its hand-back both carry the same report.
329export const sayOnce = (backlog: Backlog, id: number, message: ParkedMessage): Backlog | string => {
330 const thread = backlog.items.find(one => one.id === id)?.thread ?? []
331 const since = thread.slice(thread.findLastIndex(one => one.role === 'you') + 1)
332
333 return since.some(one => one.role === 'agent' && gist(one.text) === gist(message.text))
334 ? backlog
335 : say(backlog, id, message)
336}
337
338const optionText = (item: ParkedItem, at: number) => `option ${at}, ${item.options?.[at - 1] ?? ''}`
339
340// `text` is the answer as the main agent reads it. A silent answer is not sent
341// at all: the user took the default of an item the agent had gone ahead on.
342// What a subagent answers when a briefing that reached it after its reply
343// changes nothing.
344const NO_CHANGE = /^\W*no change\W*$/i
345
346// What a briefing sent after the subagent started asks of it, should it reach
347// the subagent once its answer is already given: one answer, not two.
348export const BRIEFING_LATE =
349 'If you had already given your answer when this reached you: give the whole answer again only if this briefing changes it, and otherwise reply with just the words NO CHANGE.'
350
351// Adds a subagent's reply to a thread. A second reply to the same message of
352// the user's is the first one thought again (a briefing reached the subagent
353// after it had answered): it takes the first one's place, or is dropped when
354// the subagent says nothing changed. The same reply arriving twice is kept once.
355export const sayReply = (backlog: Backlog, id: number, message: ParkedMessage): Backlog | string => {
356 const thread = backlog.items.find(one => one.id === id)?.thread ?? []
357 const from = thread.findLastIndex(one => one.role === 'you') + 1
358 const earlier = thread.findLastIndex((one, at) => at >= from && one.role === 'agent')
359
360 if (earlier === -1) {
361 return sayOnce(backlog, id, message)
362 }
363
364 if (NO_CHANGE.test(message.text) || gist(thread[earlier]?.text ?? '') === gist(message.text)) {
365 return backlog
366 }
367
368 return {
369 ...backlog,
370 items: backlog.items.map(one =>
371 one.id === id
372 ? {
373 ...one,
374 thread: (one.thread ?? []).map((said, at) =>
375 at === earlier ? { ...message, tools: [...(said.tools ?? []), ...(message.tools ?? [])] } : said,
376 ),
377 }
378 : one,
379 ),
380 }
381}
382
383export type ParkedAnswer = { text: string; isSilent: boolean }
384
385// The user's answer to an item: an option by its number (a typed number names
386// one too, where the item has options), or their own words. A string answer
387// is the reason it was refused.
388export const answerOf = (item: ParkedItem, reply: number | string): ParkedAnswer | string => {
389 const typed = typeof reply === 'string' ? reply.trim() : ''
390 const at =
391 typeof reply === 'number'
392 ? reply
393 : item.options !== undefined && /^[1-9]$/.test(typed)
394 ? Number(typed)
395 : undefined
396
397 if (at === undefined) {
398 return typed === '' ? `Parked item #${item.id} needs an answer.` : { text: typed, isSilent: false }
399 }
400
401 if (!Number.isInteger(at) || at < 1 || at > (item.options?.length ?? 0)) {
402 return `Parked item #${item.id} has no option ${at}.`
403 }
404
405 return { text: optionText(item, at), isSilent: item.isBlocking !== true && at === item.preferred }
406}
407
408// Marks an item done with the user's answer, to be sent to the main agent
409// unless it is silent.
410export const answer = (
411 backlog: Backlog,
412 id: number,
413 reply: number | string,
414 now: number,
415 sessionId?: string,
416): Backlog | string => {
417 const item = backlog.items.find(one => one.id === id)
418
419 if (item === undefined) {
420 return `No parked item #${id}.`
421 }
422
423 if (item.status === 'done') {
424 return `Parked item #${id} is already done.`
425 }
426
427 const made = answerOf(item, reply)
428
429 if (typeof made === 'string') {
430 return made
431 }
432
433 const line = made.text.replace(/\s+/g, ' ')
434 const resolution = made.isSilent
435 ? `You accepted the default: ${line}`
436 : `You answered: ${line.length > 140 ? `${line.slice(0, 139)}…` : line}`
437
438 return {
439 ...backlog,
440 items: backlog.items.map(one =>
441 one.id === id
442 ? {
443 ...one,
444 status: 'done',
445 resolution,
446 resolvedBy: 'user',
447 resolvedAt: now,
448 answer: made.text,
449 ...(sessionId !== undefined ? { answeredIn: sessionId } : {}),
450 ...(made.isSilent ? {} : { isUnsent: true as const }),
451 }
452 : one,
453 ),
454 }
455}
456
457// The answers the main agent has not been told yet. Given a session, only the
458// ones answered in it: another session's agent has no use for them.
459export const unsentOf = (items: readonly ParkedItem[], sessionId?: string): ParkedItem[] =>
460 items.filter(
461 one =>
462 one.isUnsent === true &&
463 one.answer !== undefined &&
464 (sessionId === undefined || one.answeredIn === sessionId),
465 )
466
467// Puts answers back among the unsent, when sending them failed.
468export const unsend = (backlog: Backlog, ids: readonly number[]): Backlog => ({
469 ...backlog,
470 items: backlog.items.map(one =>
471 ids.includes(one.id) && one.answer !== undefined ? { ...one, isUnsent: true as const } : one,
472 ),
473})
474
475export const sent = (backlog: Backlog, ids: readonly number[]): Backlog => ({
476 ...backlog,
477 items: backlog.items.map(one => {
478 if (!ids.includes(one.id)) {
479 return one
480 }
481
482 const { isUnsent: _u, ...rest } = one
483
484 return rest
485 }),
486})
487
488// The one message that carries the user's answers to the main agent. Where an
489// answer departs from the default the agent went ahead on, it says so.
490export const answersNote = (items: readonly ParkedItem[]): string =>
491 [
492 'My answers to parked items:',
493 ...items.map(one => {
494 const isOverride =
495 one.isBlocking !== true &&
496 one.preferred !== undefined &&
497 one.answer !== optionText(one, one.preferred)
498
499 return `- #${one.id} ${one.title}: ${one.answer ?? ''}${isOverride ? ` (not your default, ${optionText(one, one.preferred ?? 0)}: revise what was built on it)` : ''}`
500 }),
501 ].join('\n')
502
503// The unit findings with no task of the run are reviewed under.
504const NO_UNIT = 'Other changes'
505
506const placeOf = (finding: LedgerFindingSeen) =>
507 finding.line === undefined ? finding.path : `${finding.path}:${finding.line}`
508
509const many = (count: number, one: string) => `${count} ${one}${count === 1 ? '' : 's'}`
510
511// What a unit's review item says of its open findings.
512const reviewOf = (unit: string, open: readonly LedgerFindingSeen[]) => {
513 const errors = open.filter(one => one.severity === 'error').length
514
515 return {
516 kind: (errors > 0 ? 'needs-you' : 'fyi') as ParkedKind,
517 title: `Review of ${unit}: ${many(open.length, 'finding')}${errors > 0 ? ` (${many(errors, 'error')})` : ''}`,
518 body: open
519 .map(one => `- ${one.severity} ${placeOf(one)} ${one.summary}${one.task ? ` (${one.task})` : ''}`)
520 .join('\n'),
521 refs: [...new Set(open.map(placeOf))],
522 }
523}
524
525const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
526
527// Brings the backlog in step with the ledger mod's run, where that mod is
528// loaded: a task whose gate fails gets an FYI that closes when it leaves that
529// state, and each unit with open findings gets one item listing them, which
530// closes when all are fixed. Answers the same backlog when nothing changed.
531export const syncLedger = (
532 backlog: Backlog,
533 run: LedgerRunSeen | null | undefined,
534 now: number,
535 sessionId: string,
536): Backlog => {
537 const seen = backlog.seen ?? { gates: [], findings: [] }
538 const tasks = run?.tasks ?? []
539 const findings = run?.findings ?? []
540 let next: Backlog = backlog
541
542 const close = (isOurs: (item: ParkedItem) => boolean, resolution: string) => {
543 if (next.items.some(one => one.status === 'open' && isOurs(one))) {
544 next = {
545 ...next,
546 items: next.items.map(one =>
547 one.status === 'open' && isOurs(one)
548 ? { ...one, status: 'done', resolution, resolvedBy: 'model', resolvedAt: now }
549 : one,
550 ),
551 }
552 }
553 }
554
555 // Gates: an item as a task's gate starts failing, closed as it stops.
556 const failed = tasks.filter(one => one.status === 'gate-failed')
557
558 for (const task of failed.filter(one => !seen.gates.includes(one.id))) {
559 next = park(next, {
560 kind: 'fyi',
561 title: `Gate failed: ${task.id} ${task.title}`,
562 body: `${task.note ?? 'The gate failed; no note was given.'}\n\nThe agent is expected to fix this and run the gate again. This item closes by itself when it does.`,
563 task: task.id,
564 origin: { kind: 'gate', task: task.id },
565 parkedBy: 'model',
566 sessionId,
567 now,
568 })
569 }
570
571 for (const id of seen.gates.filter(one => !failed.some(task => task.id === one))) {
572 const status = tasks.find(one => one.id === id)?.status
573
574 close(
575 item => item.origin?.kind === 'gate' && item.origin.task === id,
576 status === 'done'
577 ? 'The gate passed.'
578 : status === undefined
579 ? 'The run was cleared or planned again.'
580 : 'The task is being reworked.',
581 )
582 }
583
584 // Reviews: one item per unit that has open findings.
585 const unitOf = (finding: LedgerFindingSeen) =>
586 tasks.find(one => one.id === finding.task)?.unit ?? NO_UNIT
587 const open = findings.filter(one => one.status === 'open')
588 const units = new Set([
589 ...open.map(unitOf),
590 ...next.items.flatMap(one =>
591 one.status === 'open' && one.origin?.kind === 'review' ? [one.origin.unit] : [],
592 ),
593 ])
594
595 for (const unit of units) {
596 const mine = open.filter(one => unitOf(one) === unit)
597 const item = next.items.find(
598 one => one.status === 'open' && one.origin?.kind === 'review' && one.origin.unit === unit,
599 )
600
601 if (mine.length === 0) {
602 close(
603 one => one.origin?.kind === 'review' && one.origin.unit === unit,
604 run ? 'Every finding is fixed.' : 'The run was cleared.',
605 )
606 } else if (item !== undefined) {
607 const { refs, ...said } = reviewOf(unit, mine)
608 const updated: ParkedItem = { ...item, ...said, refs }
609
610 if (!same(updated, item)) {
611 next = { ...next, items: next.items.map(one => (one.id === item.id ? updated : one)) }
612 }
613 } else if (mine.some(one => !seen.findings.includes(one.id))) {
614 next = park(next, {
615 ...reviewOf(unit, mine),
616 origin: { kind: 'review', unit },
617 parkedBy: 'model',
618 sessionId,
619 now,
620 })
621 }
622 }
623
624 const after: LedgerSeen = {
625 gates: failed.map(one => one.id),
626 findings: run ? [...new Set([...seen.findings, ...findings.map(one => one.id)])] : [],
627 }
628
629 return same(after, seen) && next === backlog ? backlog : { ...next, seen: after }
630}
631
632// Every run the ledger keeps, as the one view `syncLedger` reads: the tasks of
633// the runs under way, and the findings of all. A task id names one task among
634// the runs under way and a finding's number one finding, so nothing clashes.
635// With no run at all there is nothing: undefined when the ledger is not there.
636export const mergedRuns = (
637 runs: readonly LedgerRunSeen[] | null | undefined,
638): LedgerRunSeen | null | undefined =>
639 runs === null || runs === undefined
640 ? undefined
641 : runs.length === 0
642 ? null
643 : {
644 goal: '',
645 tasks: runs.filter(one => one.doneAt === undefined).flatMap(one => one.tasks),
646 findings: runs.flatMap(one => one.findings),
647 }
648
649// A file reference as a place to show: its path, and its line (0 when the
650// reference names the file alone). A column after the line is left out.
651export const placeOfRef = (ref: string): { path: string; line: number } => {
652 const at = /^(.*?):(\d+)(?::\d+)?$/.exec(ref.trim())
653
654 return at === null ? { path: ref.trim(), line: 0 } : { path: at[1] ?? '', line: Number(at[2]) }
655}
656
657// How many lines of a file an item shows above and below the one referred to.
658const PEEK_BEFORE = 6
659const PEEK_AFTER = 30
660
661// The part of a file an item shows for a reference: the lines around the one
662// referred to, or its first lines when the reference names the file alone,
663// within what one Code element draws.
664export const excerptOf = (text: string, line: number): { start: number; source: string } => {
665 const lines = text.replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '').split('\n')
666 const start = Math.max(1, Math.min(line - PEEK_BEFORE, lines.length))
667 const taken: string[] = []
668 let size = 0
669
670 for (const one of lines.slice(start - 1, start - 1 + PEEK_BEFORE + PEEK_AFTER + 1)) {
671 // A line longer than the pane is wide is cut: a minified file is one line.
672 const cut = one.length > 400 ? `${one.slice(0, 399)}…` : one
673
674 if (size + cut.length + 1 > 9000) {
675 break
676 }
677
678 taken.push(cut)
679 size += cut.length + 1
680 }
681
682 return { start, source: taken.join('\n') }
683}
684
685// A text with the user's home folder written `~`, as a shell prompt has it.
686// Only a whole folder name counts: `/Users/kim` is not shortened in
687// `/Users/kimberly`.
688export const tildeOf = (text: string, home: string): string =>
689 home === '' || home === '/'
690 ? text
691 : text.split(home).reduce((joined, part) => `${joined}${/^[\w.-]/.test(part) ? home : '~'}${part}`)
692
693// A body as the Markdown the pane draws. A model sometimes sends the two
694// characters `\n` where it meant a line break: a body with no line break at
695// all that holds them is read that way.
696export const tidyBody = (body: string): string => {
697 const text = body.replace(/\r\n?/g, '\n')
698 const isEscaped = !text.includes('\n') && text.includes('\\n')
699
700 return (isEscaped ? text.replace(/\\n/g, '\n').replace(/\\t/g, ' ') : text).trim()
701}
702
703const TABLE_RULE = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/
704
705// A table row's cells, without the bars at its ends.
706const cellsOf = (row: string): string[] =>
707 row
708 .trim()
709 .replace(/^\|/, '')
710 .replace(/\|$/, '')
711 .split(/(?<!\\)\|/)
712 .map(cell => cell.trim().replace(/\\\|/g, '|'))
713
714// A cell as plain text, for a table drawn in fixed columns.
715const plain = (cell: string) => cell.replace(/\*\*(.+?)\*\*/g, '$1').replace(/`([^`]*)`/g, '$1')
716
717// Markdown with its tables made to fit a pane. The Markdown element lays a
718// table out for a width of its own, not the pane's, so in a narrow pane every
719// row wraps and the grid is lost. A table that fits `width` is drawn here in
720// fixed columns inside a code fence, where spacing is kept; one that does not
721// becomes a list, each row an entry and each further cell a line named by its
722// column. Tables inside a code fence are left alone.
723export const fitTables = (text: string, width: number): string => {
724 const lines = text.split('\n')
725 const out: string[] = []
726 let isFenced = false
727
728 for (let at = 0; at < lines.length; at += 1) {
729 const line = lines[at] ?? ''
730
731 if (/^\s*(```|~~~)/.test(line)) {
732 isFenced = !isFenced
733 }
734
735 const rule = lines[at + 1] ?? ''
736
737 if (isFenced || !line.includes('|') || !rule.includes('-') || !TABLE_RULE.test(rule)) {
738 out.push(line)
739
740 continue
741 }
742
743 const head = cellsOf(line)
744 const rows: string[][] = []
745 let end = at + 2
746
747 for (; end < lines.length && (lines[end] ?? '').includes('|') && (lines[end] ?? '').trim() !== ''; end += 1) {
748 rows.push(cellsOf(lines[end] ?? ''))
749 }
750
751 const all = [head, ...rows].map(row => head.map((_, column) => plain(row[column] ?? '')))
752 const widths = head.map((_, column) => Math.max(...all.map(row => (row[column] ?? '').length)))
753 const fits = widths.reduce((sum, one) => sum + one, 0) + 3 * (head.length - 1) <= width
754
755 if (fits) {
756 const drawn = all.map(row => row.map((cell, column) => cell.padEnd(widths[column] ?? 0)).join(' │ ').trimEnd())
757
758 out.push('```', drawn[0] ?? '', widths.map(one => '─'.repeat(one)).join('─┼─'), ...drawn.slice(1), '```')
759 } else {
760 for (const row of rows) {
761 out.push(`- **${row[0] ?? ''}**`)
762 out.push(
763 ...head.flatMap((name, column) =>
764 column === 0 || (row[column] ?? '') === '' ? [] : [` - ${name === '' ? '' : `${name}: `}${row[column]}`],
765 ),
766 )
767 }
768 }
769
770 at = end - 1
771 }
772
773 return out.join('\n')
774}
775
776// The most one Markdown element draws is 10000 characters.
777const MARKDOWN_MOST = 9000
778
779// A text as the pieces Markdown elements draw, one each: cut at a blank line
780// where there is one, else at a line's end, and free of the control characters
781// an element refuses.
782export const markdownOf = (text: string, most = MARKDOWN_MOST): string[] => {
783 const chunks: string[] = []
784 let rest = text.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '')
785
786 while (rest.length > most) {
787 const blank = rest.lastIndexOf('\n\n', most)
788 const line = rest.lastIndexOf('\n', most)
789 const at = blank > most / 2 ? blank : line > most / 2 ? line : most
790
791 chunks.push(rest.slice(0, at))
792 rest = rest.slice(at).replace(/^\n+/, '')
793 }
794
795 return rest.trim() === '' ? chunks : [...chunks, rest]
796}
797
798// Where a session is and what it is asking about: its id and its project root.
799export type Here = { sessionId: string; project: string }
800
801// The items a scope lists: this session's, those of every session in this
802// project, or all of them.
803export const inScope = (items: readonly ParkedItem[], scope: ParkedScope, here: Here): ParkedItem[] =>
804 items.filter(
805 one =>
806 scope === 'all' ||
807 one.sessionId === here.sessionId ||
808 (scope === 'project' && one.project !== undefined && one.project === here.project),
809 )
810
811const SCOPES: readonly ParkedScope[] = ['session', 'project', 'all']
812
813export const nextScope = (scope: ParkedScope): ParkedScope =>
814 SCOPES[(SCOPES.indexOf(scope) + 1) % SCOPES.length] ?? 'session'
815
816// What the pane calls a session: the name /resume lists it under, or the start
817// of its id while it has none.
818export const sessionLabel = (
819 sessions: Readonly<Record<string, ParkedSession>> | undefined,
820 sessionId: string,
821): string => {
822 const name = sessions?.[sessionId]?.name ?? ''
823
824 return name !== '' ? name : `session ${sessionId.slice(0, 8)}`
825}
826
827// Records what a session is called and where it runs. Answers the same backlog
828// when it already says so.
829export const knowSession = (
830 backlog: Backlog,
831 sessionId: string,
832 seen: { name: string; project: string; transcript?: string },
833 now: number,
834): Backlog => {
835 const known = backlog.sessions?.[sessionId]
836 // A name once found is kept when a later look finds none.
837 const name = seen.name !== '' ? seen.name : (known?.name ?? '')
838 const transcript = seen.transcript ?? known?.transcript
839
840 if (known !== undefined && known.name === name && known.project === seen.project && known.transcript === transcript) {
841 return backlog
842 }
843
844 return {
845 ...backlog,
846 sessions: {
847 ...backlog.sessions,
848 [sessionId]: { name, project: seen.project, ...(transcript !== undefined ? { transcript } : {}), seenAt: now },
849 },
850 }
851}
852
853// What `grep -o -E` is given to find a transcript's title rows, and the name
854// they give a session: the one the user set, else the one Claude Code made.
855export const TITLE_ROWS = '"type":"(custom-title|agent-name|ai-title)","[A-Za-z]+":"([^"\\\\]|\\\\.)*"'
856
857export const sessionNameOf = (found: string): string => {
858 const names: Record<string, string> = {}
859
860 for (const line of found.split('\n')) {
861 try {
862 const row: Record<string, unknown> = JSON.parse(`{${line}}`)
863 const name = Object.entries(row).find(([key]) => key !== 'type')?.[1]
864
865 if (typeof row.type === 'string' && typeof name === 'string' && name.trim() !== '') {
866 names[row.type] = name.trim()
867 }
868 } catch {
869 // Not a title row.
870 }
871 }
872
873 return names['custom-title'] ?? names['agent-name'] ?? names['ai-title'] ?? ''
874}
875
876// The backlog before this one was kept per folder. Those are joined into one,
877// oldest item first and numbered afresh, each item keeping its folder as its
878// project and each session what the ledger had been through.
879export const migrate = (old: readonly (readonly [project: string, backlog: Backlog])[]): Backlog => {
880 const items = old
881 .flatMap(([project, backlog]) => backlog.items.map(one => ({ ...one, project: one.project ?? project })))
882 .sort((a, b) => a.createdAt - b.createdAt)
883 .map((one, at) => {
884 // A subagent belongs to the session that started it, long over.
885 const { agentId: _a, ...rest } = one
886
887 return { ...rest, id: at + 1 }
888 })
889 const ledger = Object.fromEntries(
890 old.flatMap(([, backlog]) => {
891 const seen = backlog.seen
892
893 return seen === undefined ? [] : backlog.items.map(one => [one.sessionId, seen] as const)
894 }),
895 )
896
897 return { nextId: items.length + 1, items, ...(Object.keys(ledger).length > 0 ? { ledger } : {}) }
898}
899
900// `syncLedger` for the one session whose ledger changed: its items alone are
901// brought in step, and every other session's are left as they are.
902export const syncSession = (
903 backlog: Backlog,
904 run: LedgerRunSeen | null | undefined,
905 now: number,
906 here: Here,
907): Backlog => {
908 const seen = backlog.ledger?.[here.sessionId]
909 const mine: Backlog = {
910 nextId: backlog.nextId,
911 items: backlog.items.filter(one => one.sessionId === here.sessionId),
912 ...(seen !== undefined ? { seen } : {}),
913 }
914 const after = syncLedger(mine, run, now, here.sessionId)
915
916 if (after === mine) {
917 return backlog
918 }
919
920 return {
921 ...backlog,
922 nextId: after.nextId,
923 items: [
924 ...backlog.items.filter(one => one.sessionId !== here.sessionId),
925 ...after.items.map(one => (one.project === undefined && here.project !== '' ? { ...one, project: here.project } : one)),
926 ].sort((a, b) => a.id - b.id),
927 ...(after.seen !== undefined ? { ledger: { ...backlog.ledger, [here.sessionId]: after.seen } } : {}),
928 }
929}
930
931// A reference as the file it names: a path that is not absolute is from the
932// project the item was parked in, which need not be the folder the session is
933// in now, and `~` is the user's home.
934export const pathOfRef = (item: ParkedItem, ref: string, home: string): string => {
935 const named = placeOfRef(ref).path
936 const isFromProject = item.project !== undefined && !/^[/~]/.test(named)
937
938 return (isFromProject ? `${item.project}/${named}` : named).replace(/^~(?=\/|$)/, home)
939}
940
941// Puts items back as they were before something was done to them, by id.
942// Answers which of them had an answer the agent has already been told: taking
943// the item back does not take that back.
944export const restore = (
945 backlog: Backlog,
946 before: readonly ParkedItem[],
947): { backlog: Backlog; told: number[] } => {
948 const was = new Map(before.map(one => [one.id, one]))
949 const told = backlog.items
950 .filter(one => was.has(one.id) && one.answer !== undefined && one.isUnsent !== true && !/^You accepted the default/.test(one.resolution ?? ''))
951 .map(one => one.id)
952
953 return { backlog: { ...backlog, items: backlog.items.map(one => was.get(one.id) ?? one) }, told }
954}
955
956// The open items whose answer can be the agent's own pick: a choice with a
957// default. Taking them all is one press after a run left unattended.
958export const defaultsOf = (items: readonly ParkedItem[]): ParkedItem[] =>
959 items.filter(one => one.status === 'open' && one.kind === 'needs-you' && one.preferred !== undefined)
960
961// What a session is told as it opens with items of its own waiting: how many
962// need the user, and how long the oldest has waited. Nothing when none does.
963export const digestOf = (items: readonly ParkedItem[], now: number): string | undefined => {
964 const needs = items.filter(one => one.status === 'open' && one.kind === 'needs-you')
965 const blocking = needs.filter(one => one.isBlocking === true).length
966
967 if (needs.length === 0) {
968 return undefined
969 }
970
971 const oldest = Math.min(...needs.map(one => one.createdAt))
972
973 return `Parked: ${needs.length} need${needs.length === 1 ? 's' : ''} your attention${blocking > 0 ? `, ${blocking} blocking` : ''}, the oldest for ${ageOf(oldest, now)}. /parked shows them.`
974}
975
976// What the agent is asked when the user hands it its own list to work through.
977export const workPrompt = (own: readonly ParkedItem[]): string =>
978 [
979 `Go through the ${own.length === 1 ? 'item' : `${own.length} items`} you parked for yourself, now:`,
980 ...own.map(one => `- #${one.id} ${one.title}`),
981 'Read each in full with the list tool first. Do the ones you can and resolve each as it is done. For one you cannot do yet, say what it is waiting on and leave it open.',
982 ].join('\n')
983
984// What a tool call gave back, as the one line a thread shows under the call:
985// its first line, and how many more there were. The result is a tool_result's
986// content: text, or blocks of which the text ones count.
987export const resultLine = (content: unknown): string => {
988 const text =
989 typeof content === 'string'
990 ? content
991 : Array.isArray(content)
992 ? content
993 .map(block => (typeof block === 'object' && block !== null && 'text' in block ? String(block.text) : ''))
994 .join('\n')
995 : ''
996 const lines = text
997 .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '')
998 .split('\n')
999 .filter(line => line.trim() !== '')
1000 const first = (lines[0] ?? '').trim()
1001
1002 if (first === '') {
1003 return '(nothing)'
1004 }
1005
1006 return `${first.length > 90 ? `${first.slice(0, 89)}…` : first}${lines.length > 1 ? ` (+${lines.length - 1} lines)` : ''}`
1007}
1008
1009// What the assistant parked for itself in a session and has not done.
1010export const ownOpen = (items: readonly ParkedItem[], sessionId: string): ParkedItem[] =>
1011 items.filter(one => one.kind === 'self' && one.status === 'open' && one.sessionId === sessionId)
1012
1013// How many prompts may pass before the assistant is reminded of them again.
1014const REMIND_EVERY = 6
1015
1016// Whether a turn should open with a reminder: when the list is not the one
1017// last reminded of, or enough prompts have passed since.
1018export const isReminderDue = (
1019 own: readonly ParkedItem[],
1020 last: { ids: string; turns: number },
1021): boolean => own.length > 0 && (own.map(one => one.id).join(',') !== last.ids || last.turns >= REMIND_EVERY)
1022
1023// The reminder itself, a note only the assistant reads.
1024export const reminderOf = (own: readonly ParkedItem[]): string =>
1025 [
1026 `You parked ${own.length === 1 ? 'this' : 'these'} for yourself and ${own.length === 1 ? 'it is' : 'they are'} still open:`,
1027 ...own.map(one => `- #${one.id} ${one.title}`),
1028 'This is a reminder, not a request from the user. Come back to them when the current work allows, resolve each one as it is done, and do not report the work finished while one is open without saying so.',
1029 ].join('\n')
1030
1031// How many done items are kept; the pane lists the newest ten.
1032const DONE_KEPT = 200
1033
1034// Drops the done items closed longest ago once there are more than are kept,
1035// so the store, which holds every session's, stays small.
1036export const pruned = (backlog: Backlog): Backlog => {
1037 const done = backlog.items.filter(one => one.status === 'done')
1038
1039 if (done.length <= DONE_KEPT) {
1040 return backlog
1041 }
1042
1043 const dropped = new Set(
1044 done
1045 .sort((a, b) => (a.resolvedAt ?? a.createdAt) - (b.resolvedAt ?? b.createdAt))
1046 .slice(0, done.length - DONE_KEPT)
1047 .map(one => one.id),
1048 )
1049
1050 return { ...backlog, items: backlog.items.filter(one => !dropped.has(one.id)) }
1051}
1052
1053// The handover a thread's subagent starts with, as the user reads it in the
1054// thread: its instructions, the briefing and their message. The ticket itself
1055// is in view above, so it is named and not repeated.
1056export const handoverOf = (item: ParkedItem, text: string, brief: string): string =>
1057 [
1058 ...INVESTIGATE,
1059 '',
1060 `**Ticket:** #${item.id} ${item.title}, with its full text${item.note ? ' and your note' : ''}.`,
1061 '',
1062 '**Briefing from the main session**, sent to the subagent as a follow-up once it was written:',
1063 '',
1064 brief.trim() !== ''
1065 ? brief.trim()
1066 : '_None: the main session had no context to give, so the subagent has the ticket only._',
1067 ...((item.thread ?? []).some(one => one.role === 'agent') ? ['', '**Earlier in this thread:** every message so far.'] : []),
1068 '',
1069 `**Your message:** ${text}`,
1070 ].join('\n')
1071
1072const ESCAPES: Record<string, string> = { n: '\n', t: '\t', r: '', b: '', f: '' }
1073
1074// The string values in a piece of JSON that may stop anywhere, each decoded;
1075// the last may be unfinished. A tool call's arguments arrive that way, and a
1076// subagent's report is one of them.
1077export const stringsIn = (json: string): string[] => {
1078 const found: string[] = []
1079 let at = 0
1080
1081 while (at < json.length) {
1082 if (json[at] !== '"') {
1083 at += 1
1084
1085 continue
1086 }
1087
1088 let end = at + 1
1089 let text = ''
1090
1091 for (; end < json.length && json[end] !== '"'; end += 1) {
1092 const mark = json[end + 1]
1093
1094 if (json[end] !== '\\') {
1095 text += json[end]
1096 } else if (mark === undefined || (mark === 'u' && end + 6 > json.length)) {
1097 // An escape cut short: the text stops before it.
1098 end = json.length
1099 } else if (mark === 'u') {
1100 text += String.fromCharCode(Number.parseInt(json.slice(end + 2, end + 6), 16))
1101 end += 5
1102 } else {
1103 text += ESCAPES[mark] ?? mark
1104 end += 1
1105 }
1106 }
1107
1108 // A value follows a colon; any other string is a key.
1109 if (json.slice(Math.max(0, at - 8), at).trimEnd().endsWith(':')) {
1110 found.push(text)
1111 }
1112
1113 at = end + 1
1114 }
1115
1116 return found
1117}
1118
1119// A tool call as a thread's row names it, as the transcript does: the tool and
1120// the first of its arguments, `Read(src/queue.ts)`. The arguments may still be
1121// arriving. A plugin's or a server's tool goes by its own name.
1122export const callLabel = (name: string, json: string): string => {
1123 const first = (stringsIn(json)[0] ?? '').replace(/\s+/g, ' ').trim()
1124 const tool = name.replace(/^mcp__(.+?)__/, '$1: ')
1125
1126 return first === '' ? tool : `${tool}(${first.length > 70 ? `${first.slice(0, 69)}…` : first})`
1127}
1128
1129// The report in a hand-back call's arguments so far: its longest text.
1130export const reportIn = (json: string): string =>
1131 stringsIn(json).reduce((longest, one) => (one.length > longest.length ? one : longest), '')
1132hooks/detail.tsx 166 lines1import type { ClientModule, ClientSurface } from 'claude-code'
2
3// One row of the list: a section heading, or an item.
4type Entry = {
5 kind: 'head' | 'row'
6 id: number
7 glyph: string
8 tone: string
9 text: string
10 meta: string
11 isDone: boolean
12}
13
14// A key pressed on one of the pane's own letter buttons, which need no click:
15// the hooks module counts them, and a new count is a key to answer.
16type Nudge = { key: string; n: number }
17
18type Props = {
19 columns: number
20 rows: number
21 summary: string
22 entries: Entry[]
23 // The item last shown in full (0 for none): the cursor starts on its row.
24 from: number
25 nudge: Nudge
26}
27
28// `cursor` is the list row the keyboard is on; -1 until a key or a click has
29// moved it, while it rests on the row of the item last shown.
30type State = { cursor: number }
31
32const clamp = (value: number, low: number, high: number) => Math.min(high, Math.max(low, value))
33
34// The vim keys, as the arrows and Enter they stand for.
35const VIM: Record<string, string> = { h: 'left', j: 'down', k: 'up', l: 'right', o: 'return' }
36
37// The last nudge answered (-1 before the first drawing), and the last ↑ or ↓
38// that came as a real key: the pane may report the same press again as a
39// scroll, which the hooks module turns into a nudge.
40let seen = -1
41let lastArrow = { key: '', at: 0 }
42
43// Hands the key handler both routes: the region's own keys, once it is
44// clicked, and the nudges from the pane's letter buttons.
45const listen = (surface: ClientSurface<State>, nudge: Nudge, onKey: (key: string) => void) => {
46 surface.onKey(event => {
47 if (event.key === 'up' || event.key === 'down') {
48 lastArrow = { key: event.key, at: Date.now() }
49 }
50
51 onKey(event.key)
52 })
53
54 if (seen === -1) {
55 seen = nudge.n
56 } else if (nudge.n !== seen) {
57 seen = nudge.n
58
59 if (!(nudge.key === lastArrow.key && Date.now() - lastArrow.at < 80)) {
60 onKey(nudge.key)
61 }
62 }
63}
64
65// The backlog as a list the keyboard walks: ↑ and ↓ move, Enter or → opens,
66// v asks for the next scope. An item itself is drawn by the hooks module.
67const List: ClientModule<Props, State> = (props, surface) => {
68 const { Box, Text } = surface.elements
69 const rows = props.entries.filter(entry => entry.kind === 'row')
70 const last = Math.max(0, rows.length - 1)
71 // Coming back from an item, the cursor is on that item's row.
72 const came = rows.findIndex(entry => entry.id === props.from)
73 const kept = surface.state?.cursor ?? -1
74 const cursor = clamp(kept >= 0 ? kept : came, 0, last)
75 const move = (to: number) => surface.setState({ cursor: clamp(to, 0, last) })
76 const open = (at: number) => {
77 const entry = rows[at]
78
79 if (entry !== undefined) {
80 surface.setState({ cursor: at })
81 surface.post({ open: entry.id })
82 }
83 }
84
85 // The window of entries that fits, kept around the cursor's row.
86 const height = Math.max(3, props.rows - 4)
87 const here = rows[cursor]
88 const cursorAt = here === undefined ? 0 : props.entries.indexOf(here)
89 const start = clamp(cursorAt - Math.floor(height / 2), 0, Math.max(0, props.entries.length - height))
90 const shown = props.entries.slice(start, start + height)
91
92 listen(surface, props.nudge, raw => {
93 const key = VIM[raw] ?? raw
94
95 if (key === 'up') {
96 move(cursor - 1)
97 } else if (key === 'down' || key === 'tab') {
98 move(cursor + 1)
99 } else if (key === 'pageup') {
100 move(cursor - height)
101 } else if (key === 'pagedown') {
102 move(cursor + height)
103 } else if (key === 'return' || key === 'right') {
104 open(cursor)
105 } else if (key === 'v') {
106 surface.post({ scope: true })
107 } else if (key === 'a') {
108 surface.post({ defaults: true })
109 } else if (key === 'u') {
110 surface.post({ undo: true })
111 }
112 })
113
114 surface.onPointer(event => {
115 // Two rows sit above the entries: the summary and a rule.
116 const entry = event.type === 'down' ? shown[event.y - 2] : undefined
117
118 if (entry !== undefined && entry.kind === 'row') {
119 open(rows.indexOf(entry))
120 }
121 })
122
123 return (
124 <Box flexDirection="column">
125 <Text bold wrap="truncate-end">
126 📌 Parked{props.summary === '' ? '' : ` · ${props.summary}`}
127 </Text>
128 <Text dimColor>{'─'.repeat(props.columns)}</Text>
129 <Box flexDirection="column" height={height} overflow="hidden">
130 {rows.length === 0 && <Text dimColor>Nothing parked here yet. /park [note] parks the last reply.</Text>}
131 {shown.map(entry => {
132 if (entry.kind === 'head') {
133 return (
134 <Text color={entry.tone} bold>
135 {entry.text}
136 </Text>
137 )
138 }
139
140 const isHere = rows.indexOf(entry) === cursor
141
142 return (
143 <Box justifyContent="space-between">
144 <Text wrap="truncate-end">
145 <Text color="cyan">{isHere ? '▸ ' : ' '}</Text>
146 <Text color={entry.tone}>{entry.glyph} </Text>
147 <Text dimColor>#{entry.id} </Text>
148 <Text inverse={isHere} dimColor={entry.isDone && !isHere}>
149 {entry.text}
150 </Text>
151 </Text>
152 <Text dimColor>{entry.meta}</Text>
153 </Box>
154 )
155 })}
156 </Box>
157 <Text dimColor>{'─'.repeat(props.columns)}</Text>
158 <Text dimColor wrap="truncate-end">
159 click once for keys · ↑↓ or j k move · enter, → or l opens · v scope · esc releases
160 </Text>
161 </Box>
162 )
163}
164
165export default List
166types/index.d.ts 128 lines1// 'needs-you' and 'fyi' are for the user. 'self' is the assistant's own: a
2// thing it means to come back to, which the user is not asked to act on.
3export type ParkedKind = 'needs-you' | 'fyi' | 'self'
4
5// 'note' is a line the mod itself adds to a thread; 'brief' is the handover the
6// thread's subagent was started with, kept so the user can read it. A reply
7// keeps the tool calls its subagent made on the way, each as the row drawn.
8export type ParkedMessage = {
9 role: 'you' | 'agent' | 'note' | 'brief'
10 text: string
11 at: number
12 tools?: string[]
13}
14
15export type ParkedItem = {
16 id: number
17 kind: ParkedKind
18 title: string
19 body: string
20 note?: string
21 parkedBy: 'model' | 'user'
22 // The session the item was parked in, and that session's project root.
23 sessionId: string
24 project?: string
25 createdAt: number
26 // The transcript row the item came up at, where there is one to go back to:
27 // the agent's call that parked it, or the row the user's selection lay in.
28 source?: string
29 status: 'open' | 'done'
30 resolution?: string
31 resolvedBy?: 'model' | 'user'
32 resolvedAt?: number
33 // The choices a decision offers, and the one (counted from 1) the agent
34 // would pick: it proceeds on that one unless the item is blocking.
35 options?: string[]
36 preferred?: number
37 // Set when no remaining work can go on until the user answers.
38 isBlocking?: true
39 // The places the item is about, each a path or path:line.
40 refs?: string[]
41 // The ledger task the item belongs to, where the ledger mod has a run.
42 task?: string
43 // Set on an item parked from the ledger's run, not by the agent or the user:
44 // a task's failed gate, or the open findings of a unit's review.
45 origin?: { kind: 'gate'; task: string } | { kind: 'review'; unit: string }
46 // What the user answered, and whether the main agent is still to be told.
47 answer?: string
48 // The session whose agent is to be told: the one the item was parked in.
49 answeredIn?: string
50 isUnsent?: true
51 // The side conversation held in the pane; the main agent never reads it.
52 thread?: ParkedMessage[]
53 // The subagent answering the thread, while this session still has it, and
54 // whether it was started so that its replies can be shown as it writes them.
55 agentId?: string
56 isStreamed?: true
57 // A briefing written after the subagent had already replied: it goes with
58 // the user's next message to it.
59 owed?: string
60 // The briefing the main session wrote for this item's thread. It is written
61 // once: a subagent that later takes the thread over starts with it.
62 brief?: string
63}
64
65// A session that has parked items, as the pane names it: the name /resume
66// lists it under, its project root, and where its transcript is kept.
67export type ParkedSession = { name: string; project: string; transcript?: string; seenAt: number }
68
69// Which items the pane lists: this session's, this project's, or all of them.
70export type ParkedScope = 'session' | 'project' | 'all'
71
72// A thread's reply while its subagent writes it: the tools it has called and
73// the text so far. Before the subagent has written anything, `stage` says what
74// is being waited on.
75export type ParkedLive = { text: string; tools: string[]; stage?: string }
76
77// One of an item's files shown in the item itself: which of its references,
78// the file's full path, the line referred to (0 for the file as a whole), the
79// lines read around it and the number of the first, or why it could not be read.
80export type ParkedPeek = { at: number; path: string; line: number; start: number; source: string; error?: string }
81
82// A place parked asks to be shown, which the lens mod opens where it is loaded:
83// a path from the session's folder (or absolute), a line (0 for the file as a
84// whole), and a count of the asks, so the same place asked twice is two asks.
85export type ParkedJump = { path: string; line: number; n: number }
86
87declare module 'claude-code' {
88 interface PluginState {
89 parked: {
90 jump: ParkedJump | null
91 nudge: { key: string; n: number }
92 typing: boolean
93 draft: string
94 // What the composer holds as the user types, for the pane to show whole.
95 typed: string
96 // The item whose side thread takes the next prompt typed in Claude Code's
97 // own prompt box; 0 while none does.
98 armed: number
99 answering: boolean
100 items: ParkedItem[]
101 sessions: Record<string, ParkedSession>
102 scope: ParkedScope
103 selected: number
104 pending: number[]
105 live: Record<string, ParkedLive>
106 section: 'ticket' | 'thread'
107 // Whether an item offers its side thread; `/parked chat` switches it.
108 chat: boolean
109 isBriefOpen: boolean
110 // The assistant's own items it was last reminded of, and the prompts since.
111 reminded: { ids: string; turns: number }
112 peek: ParkedPeek | null
113 // Whether the pane is showing the lens mod's screens in place of its own:
114 // a file of an item, opened where the item was. Lens reads this.
115 guest: boolean
116 // Which of the open item's files (by place in its list) have been changed
117 // since it was parked: what it says of them may no longer hold.
118 changed: number[]
119 // The last thing done in the pane that can be taken back: what it was,
120 // and the items it touched as they were before.
121 undo: { label: string; items: ParkedItem[] } | null
122 // The session last told what was waiting for it, so a reload says nothing.
123 greeted: string
124 lab: boolean
125 }
126 }
127}
128