Git-native project plans and agent workflows for any repository

Projector is a Git-native framework for getting work done in any repository. It gives every project a permanent plan under docs/projects/, derives status and priority views from frontmatter, and supplies one CLI for people and coding agents.
Projects never move when their status or priority changes. Two branches working on different projects therefore edit different files instead of contending on a shared now.md, next.md, or later.md queue.
One command installs the project command from the newest release and the plugin for Claude Code and Codex, whichever you have. It needs Python 3.11 or newer, and no git:
curl -fsSL https://projector.bot/install.sh | bash
project upgrade moves everything to the newest release later, and every project command warns you when a newer release is out. To install only the CLI, pin a release, or install each plugin yourself, see Install Projector.
Run init from anywhere inside a Git repository:
project init
project create cool-new-feature --status ready --priority next --no-edit
project check
init writes the convention to docs/projects/README.md and Projector's conventions into AGENTS.md, linked as CLAUDE.md, so every agent session in the repository follows them. Run at a terminal, it adds rules to your own Claude Code settings, ~/.claude/settings.json, and to your Codex rules, ~/.codex/rules/projector.rules, that let an agent run project commands, such as publishing a review or a pull request summary, without being asked or refused. project init, project upgrade, project config set, and a site build that runs a --prepare command still ask. It sets those up outside a repository too. When origin is on GitHub, it also sets up the Projector site. create writes the plan at docs/projects/cool-new-feature/readme.md. A project can hold supporting documents and nested projects:
docs/projects/cool-new-feature/
├── readme.md
├── design.md
└── sub-feature/
└── readme.md
Each project entry point carries two independent fields. status is the lifecycle: draft, ready, in-progress, or completed. priority is the schedule: now, next, or later. Run project list to group projects at query time. Projector never writes a tracked status index.
The plugin gives Claude Code and Codex the same skills: spec, implement, and finish a project, where implement also builds a small change from a description; review-pr to review a pull request once; fix-pr to fix its findings and merge conflicts once; start-review-loop and start-watch-loop to run those two on every pull request continuously; summarize-pr, which summarizes a pull request's changes as a guided review page; write, which writes any prose so that it follows Projector's writing guide; and rewrite, which revises existing text by that guide and writes it back where it lives. Claude invokes a skill as /projector:<skill> and Codex as $<skill>. See Install Projector for how the skills work together.
In Claude Code, the plugin also shows Projector's panel above the prompt. It lists your loops' pull requests and your inbox: the questions and notices that agents post with the ask and tell tools or with project inbox. See Read your inbox in Projector's panel and Use the inbox.
Every repository can serve a site on GitHub Pages with its projects, its pull request summaries, and its docs. project init sets it up, and project site serve shows it locally without Pages. See Set up the Projector site.
project list [--status <status>] [--priority now|next|later]
project show <project>
project create <project> [--status draft] [--priority later]
project status <project> draft|ready|in-progress|completed
project priority <project> now|next|later
project done <project>
project check
project upgrade
Add --json when an agent or script consumes output. See the CLI reference for every command, and the project convention for how plans are laid out.
See Develop Projector for running the CLI from a clone, trying unreleased skills, the validation gate, and releases.
hooks/register.tsx 1766 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, FsEntry, Register, RenderChildren } from 'claude-code'
3
4import type {
5 Checks,
6 Item,
7 LoopKind,
8 Notice,
9 PullRequest,
10 Question,
11 Row,
12 SeenLoop,
13 Sending,
14 Snapshot,
15 Thread,
16} from './types'
17import { buildQuery, buildThreadsQuery, parseResponse, parseThreads, type Fetched } from './github'
18import { findWatchers, keyOf, parseTracked, type Env, type TrackedPr } from './parse'
19import {
20 ASK_DESCRIPTION,
21 ASK_SCHEMA,
22 askArguments,
23 forMainLoop,
24 isShownAt,
25 isSnoozedAt,
26 letterAt,
27 liveAgent,
28 needsDelivery,
29 proposalOf,
30 quoteOf,
31 readPrompt,
32 relayNote,
33 replyNote,
34 RESTORE_DESCRIPTION,
35 RESTORE_SCHEMA,
36 restoreArguments,
37 REVISE_DESCRIPTION,
38 REVISE_SCHEMA,
39 reviseArguments,
40 signatureOf,
41 span,
42 storeOf,
43 TELL_DESCRIPTION,
44 TELL_SCHEMA,
45 tellArguments,
46 typedLetter,
47 WITHDRAW_DESCRIPTION,
48 WITHDRAW_SCHEMA,
49 withdrawArguments,
50 wokeBetween,
51 type Proposal,
52} from './inbox'
53
54type Engine = EngineInterface
55type Ran = { exitCode: number; stdout: string; stderr: string }
56
57const TICK_MS = 5_000
58const POLL_MS = 30_000
59const EMPTY: Snapshot = { rows: [], viewer: null, fetchedAt: null, error: null }
60const ASK_TOOL = 'mcp__projector__ask'
61const TELL_TOOL = 'mcp__projector__tell'
62const WITHDRAW_TOOL = 'mcp__projector__withdraw'
63const REVISE_TOOL = 'mcp__projector__revise'
64const RESTORE_TOOL = 'mcp__projector__restore'
65const TAGLINE = 'Our minds are projectors, casting ideas onto the world.'
66
67// Watching first: a pull request both loops track is listed once, where its
68// watch loop puts it.
69const KINDS: readonly LoopKind[] = ['watching', 'reviewing']
70
71const CHECK_COLORS: Record<Checks, 'success' | 'error' | 'warning'> = {
72 passing: 'success',
73 failing: 'error',
74 pending: 'warning',
75}
76
77/**
78 * The theme color of an open question's line: the one Claude Code gives its
79 * own permission prompts, since an agent's question usually asks leave to do
80 * something.
81 */
82const QUESTION_COLOR = 'permission'
83
84/**
85 * The color of an open notice's line: the theme's mid gray, which stays
86 * apart from the `subtle` of a resolved or snoozed item. A plain `gray` would
87 * draw in the default color.
88 */
89const NOTICE_COLOR = 'inactive'
90
91/**
92 * The color of a pull request's branch on its drawer's facts line: the
93 * terminal palette's own cyan, slot 6, so it follows the person's palette as
94 * a named color would. Claude Code draws a plain name such as `cyan` in the
95 * default color and refuses `ansi:cyan` on a plugin's Text, but takes
96 * `ansi256()`.
97 */
98const BRANCH_COLOR = 'ansi256(6)'
99
100/**
101 * The color of what a loop does with a pull request, on its drawer's facts
102 * line: watching in the terminal palette's blue, slot 4, in the same form as
103 * `BRANCH_COLOR`, and reviewing in the theme's `claude` orange.
104 */
105const LOOP_COLORS: Record<LoopKind, string> = { watching: 'ansi256(4)', reviewing: 'claude' }
106
107/** The key that closes an open item's drawer, from its line at the drawer's top. */
108const CLOSE_HOTKEY = '0'
109
110/**
111 * How far an open item's drawer is indented: the width of the `0: ` the
112 * engine draws before the item's line, so the drawer's lines start under the
113 * item's text.
114 */
115const DRAWER_INDENT = `${CLOSE_HOTKEY}: `.length
116
117/**
118 * In a terminal the panel is inset `PANEL_INSET` columns in the terminal's
119 * own background, then padded `PANEL_PADDING` columns at each side in its
120 * own, where its header and key hint start. The lines between them, the pull
121 * requests, the items and their drawers, sit `LINE_PADDING` columns further
122 * in at each side.
123 */
124const PANEL_INSET = 1
125const PANEL_PADDING = 1
126const LINE_PADDING = 1
127
128/**
129 * The panel's last line names its keys, at its right, so it ends where the
130 * ages do: the chord that takes the keyboard into the panel, and once the
131 * panel has it, the keys that work there. The arrows stay out, because which
132 * of them moves between lines depends on whether the panel scrolls.
133 */
134const FOCUS_HINT = 'ctrl+x tab to focus'
135const FOCUSED_HINT = 'esc to return · enter to open'
136
137/** What the panel's header starts with, at its left: the command that shows and hides the panel. */
138const HEADER_NAME = '/projector'
139
140/**
141 * The panel's background by Claude Code theme: a step darker than the
142 * terminal's own, so the panel reads as a sunken surface. Any other theme,
143 * an ANSI one included, takes `OTHER_BACKGROUND`.
144 */
145const THEME_BACKGROUNDS: Record<string, string> = {
146 dark: 'rgb(20,20,20)',
147 'dark-daltonized': 'rgb(20,20,20)',
148 light: 'rgb(240,240,240)',
149 'light-daltonized': 'rgb(240,240,240)',
150}
151const OTHER_BACKGROUND = 'inverseText'
152
153/** The setting that colors the panel, and its value that leaves the color to the theme. */
154const BACKGROUND_KEY = 'panel.background'
155const AUTO = 'auto'
156
157/**
158 * The names `panel.background` takes besides `auto` and a literal color, and
159 * what each draws. Claude Code draws any theme key by name, but the panel
160 * refuses the others by choice: most are text colors that look wrong as a
161 * background, and a misspelled name, which is no key, draws nothing at all.
162 * `subtle` is refused too, as the color of the panel's own muted text, which
163 * would vanish on it. `black` and `white` are literal colors: `inverseText`
164 * flips between the two with the theme, and `ansi256(0)` is the terminal
165 * palette's black, often the terminal's own background, which would make the
166 * panel vanish.
167 */
168const BACKGROUND_ALIASES = new Map([
169 ['sidebar', 'composerSidebarBackground'],
170 ['black', 'rgb(0,0,0)'],
171 ['white', 'rgb(255,255,255)'],
172])
173
174/**
175 * The literal colors `panel.background` takes, written as Claude Code reads
176 * them: `#rgb` or `#rrggbb`, and `rgb(r,g,b)` or `ansi256(n)`, with a space
177 * allowed after `(`, each comma, and before `)`. Each number is at most 255.
178 */
179const HEX_COLOR = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i
180const NUMBERED_COLORS = [/^rgb\( ?(\d{1,3}), ?(\d{1,3}), ?(\d{1,3}) ?\)$/, /^ansi256\( ?(\d{1,3}) ?\)$/]
181
182/** What the panel draws for a `panel.background` value other than `auto`, or undefined when it takes none. */
183function backgroundFor(value: string): string | undefined {
184 const alias = BACKGROUND_ALIASES.get(value)
185 if (alias !== undefined) return alias
186 if (HEX_COLOR.test(value)) return value
187 const numbers = NUMBERED_COLORS.map(pattern => pattern.exec(value)).find(match => match !== null)
188 return numbers?.slice(1).every(number => Number(number) <= 255) === true ? value : undefined
189}
190
191/** The lengths a drawer offers to snooze an item for, within the CLI's cap of a day. */
192const SNOOZES = [
193 { label: '15 min', minutes: 15 },
194 { label: '1 hour', minutes: 60 },
195 { label: '4 hours', minutes: 240 },
196 { label: '1 day', minutes: 1440 },
197] as const
198
199const seen = atom({ plugin: 'projector', key: 'seenLoops' } as const, [])
200const snapshot = atom({ plugin: 'projector', key: 'panelSnapshot' } as const, EMPTY)
201const now = atom({ plugin: 'projector', key: 'panelNow' } as const, 0)
202const isShown = atom({ plugin: 'projector', key: 'isPanelShown' } as const, false)
203const drawer = atom({ plugin: 'projector', key: 'panelDrawer' } as const, null)
204const asked = atom({ plugin: 'projector', key: 'panelAsked' } as const, null)
205const drawerThreads = atom({ plugin: 'projector', key: 'panelThreads' } as const, null)
206const items = atom({ plugin: 'projector', key: 'panelInbox' } as const, [])
207const sending = atom({ plugin: 'projector', key: 'panelSending' } as const, {})
208const themeBackground = atom({ plugin: 'projector', key: 'panelThemeBackground' } as const, OTHER_BACKGROUND)
209const background = atom({ plugin: 'projector', key: 'panelBackground' } as const, AUTO)
210const isFocused = atom({ plugin: 'projector', key: 'isPanelFocused' } as const, false)
211/**
212 * The deliveries the release before the panel's rename recorded, under the
213 * key it gave them. A submit it made can still wait behind a running turn
214 * when the session updates, so the panel takes them over rather than letting
215 * their claims lapse and delivering those answers a second time.
216 */
217const oldSending = atom({ plugin: 'projector', key: 'bandSending' } as const, {})
218
219// The session keeps its state across a reload or an update of the plugin,
220// so a value an earlier version wrote can have another shape.
221const isKind = (kind: unknown): kind is LoopKind => KINDS.some(one => one === kind)
222const current = (value: Snapshot): Snapshot =>
223 Array.isArray(value.rows) ? { ...value, viewer: value.viewer ?? null } : EMPTY
224
225const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error))
226
227let envLoad: Promise<Env> | undefined
228let inFlight: Promise<void> | undefined
229let isQueued = false
230let attemptedAt = 0
231const unreadable = new Set<string>()
232
233/** The store's directory as the panel last read it, so it reads again only after a change. */
234let listed: string | undefined
235let isChecking = false
236/** The answers this copy of the module is claiming or delivering, by reference. */
237const delivering = new Set<string>()
238/** The items and pull requests the panel is dismissing or snoozing, so a second press does nothing. */
239const acting = new Set<string>()
240/** When the last tick ran, so an item whose snooze ends between two ticks wakes once. */
241let tickedAt: number | undefined
242/**
243 * The answers questions' drawers put in the prompt, oldest first, so a sent
244 * quote answers the question you chose when another shares its text. A
245 * revision marks its question's proposals stale, so an answer chosen from the
246 * old text answers nothing. A proposal lasts until a prompt you send quotes
247 * its question or holds the quote it was chosen under.
248 */
249let proposed: Proposal[] = []
250/**
251 * Where the panel's focus ring last landed, as `ui.focus` reported it: the
252 * panel's site, and the key of the panel's element under the ring, absent when
253 * the ring is on none of them. The engine says nothing when the panel hands
254 * the keyboard back, so the ring can be stale, and the engine refuses a move
255 * once the panel no longer holds the keyboard.
256 */
257let ring: { requestId: string; key: string | undefined } | undefined
258
259/**
260 * Records what a question's drawer put in the prompt: an option, or an empty
261 * answer for discuss. It takes the place of the question's last fresh pick,
262 * and of any stale pick that put the same text in the prompt, since a sent
263 * prompt cannot tell the two apart.
264 */
265function propose(question: Question, answer: string): void {
266 const quote = quoteOf(question)
267 const isKept = (one: Proposal) =>
268 one.isStale === true ? one.quote !== quote || one.answer !== answer : one.ref !== question.ref
269 proposed = [...proposed.filter(isKept), { ref: question.ref, quote, answer }]
270}
271
272/** The few variables the panel's paths are written with, read once per load. */
273function envOf($: Engine): Promise<Env> {
274 envLoad ??= (async () => {
275 const values: Record<string, string | undefined> = {
276 HOME: await $.env.get('HOME'),
277 TMPDIR: await $.env.get('TMPDIR'),
278 XDG_CONFIG_HOME: await $.env.get('XDG_CONFIG_HOME'),
279 XDG_DATA_HOME: await $.env.get('XDG_DATA_HOME'),
280 XDG_STATE_HOME: await $.env.get('XDG_STATE_HOME'),
281 CLAUDE_CONFIG_DIR: await $.env.get('CLAUDE_CONFIG_DIR'),
282 }
283 return (name: string) => (values[name] === '' ? undefined : values[name])
284 })()
285 return envLoad
286}
287
288async function canonical($: Engine, path: string): Promise<string | undefined> {
289 try {
290 const stat = await $.fs.stat(path, { resolve: true })
291 return stat.realPath ?? path
292 } catch {
293 return undefined
294 }
295}
296
297/** Runs the `project` CLI; rejects when it cannot start or is still running at the 15-second timeout. */
298const project = ($: Engine, args: readonly string[]): Promise<Ran> =>
299 $.process.run(['project', ...args], { timeoutMs: 15_000 })
300
301/** The CLI's error, as its last line of standard error says it. */
302const errorOf = (ran: Ran) =>
303 (ran.stderr.trim().split('\n').pop() ?? '').replace(/^project: /, '') || `project exited ${ran.exitCode}`
304
305/**
306 * Records a loop, answering whether the session had not seen it before. An
307 * entry an earlier version kept with no kind gives way to the watcher's.
308 */
309async function remember($: Engine, loop: SeenLoop): Promise<boolean> {
310 let isNew = false
311 await update($, seen, list => {
312 isNew = !list.some(one => one.tracked === loop.tracked && isKind(one.kind))
313 return isNew ? [...list.filter(one => one.tracked !== loop.tracked), loop] : list
314 })
315 return isNew
316}
317
318/**
319 * Records the tracked file of each watcher a command starts, and shows the
320 * panel when one is new. A loop restarts its watcher with the same command,
321 * as a Monitor does each time it expires, so a known one shows nothing and
322 * a path it cannot read is said once.
323 */
324async function adopt($: Engine, command: string): Promise<void> {
325 if (!command.includes('watch-')) return
326 const env = await envOf($)
327 let isAdded = false
328 for (const watcher of findWatchers(command, env)) {
329 if (watcher.tracked === undefined) {
330 if (!unreadable.has(watcher.written)) {
331 unreadable.add(watcher.written)
332 $.ui.toast(`projector: cannot tell which file ${watcher.written} names, so the panel does not list that loop`)
333 }
334 continue
335 }
336 const tracked = (await canonical($, watcher.tracked)) ?? watcher.tracked
337 isAdded = (await remember($, { kind: watcher.kind, tracked })) || isAdded
338 }
339 if (isAdded) show($)
340}
341
342async function fetchPrs($: Engine, prs: readonly TrackedPr[]): Promise<Fetched> {
343 if (prs.length === 0) return { prs: new Map(), viewer: null, error: null }
344 const query = buildQuery(prs)
345 try {
346 const result = await $.process.run(['gh', 'api', 'graphql', '-f', `query=${query.text}`], {
347 timeoutMs: 30_000,
348 })
349 return parseResponse(query, result)
350 } catch (error) {
351 return { prs: new Map(), viewer: null, error: messageOf(error) }
352 }
353}
354
355/** One pull request's unresolved threads, or null when GitHub cannot say. */
356async function fetchThreads($: Engine, pr: TrackedPr): Promise<Thread[] | null> {
357 const query = buildThreadsQuery(pr)
358 try {
359 const result = await $.process.run(['gh', 'api', 'graphql', '-f', `query=${query.text}`], {
360 timeoutMs: 30_000,
361 })
362 return parseThreads(query, result)
363 } catch {
364 return null
365 }
366}
367
368/**
369 * Reads the threads of the pull request whose drawer is open, for the drawer
370 * to list: when the drawer opens, and on each poll while it stays open. Each
371 * read costs a point of the account's GraphQL quota, so the panel reads only
372 * the open drawer's threads, and none when the poll counted none. When GitHub
373 * cannot say, the drawer keeps what it listed.
374 */
375async function loadThreads($: Engine): Promise<void> {
376 const opened = await read($, drawer)
377 const row = current(await read($, snapshot)).rows.find(one => keyOf(one.pr) === opened)
378 if (opened === null || row === undefined) return
379 const found = row.pr.openThreads === 0 ? [] : await fetchThreads($, row.pr)
380 // Another drawer may have opened while GitHub answered.
381 if (found === null || (await read($, drawer)) !== opened) return
382 await update($, drawerThreads, () => ({ drawer: opened, threads: found }))
383}
384
385/**
386 * The panel's background for a Claude Code theme: by the theme's name, or
387 * for a custom theme, `custom:<slug>`, by the theme its file builds on,
388 * `dark` unless its `base` says otherwise. A custom theme whose file cannot
389 * be read takes `OTHER_BACKGROUND`.
390 */
391async function backgroundOf($: Engine, theme: unknown): Promise<string> {
392 if (typeof theme !== 'string') return OTHER_BACKGROUND
393 if (!theme.startsWith('custom:')) return THEME_BACKGROUNDS[theme] ?? OTHER_BACKGROUND
394 const env = await envOf($)
395 const home = env('HOME')
396 const config = env('CLAUDE_CONFIG_DIR') ?? (home === undefined ? undefined : `${home}/.claude`)
397 if (config === undefined) return OTHER_BACKGROUND
398 try {
399 const path = `${config}/themes/${theme.slice('custom:'.length)}.json`
400 const base = (JSON.parse(await $.fs.read(path)) as { base?: unknown }).base ?? 'dark'
401 return typeof base === 'string' ? (THEME_BACKGROUNDS[base] ?? OTHER_BACKGROUND) : OTHER_BACKGROUND
402 } catch {
403 return OTHER_BACKGROUND
404 }
405}
406
407/** Colors the panel for a theme ahead of the render, which then waits on no read. */
408async function paint($: Engine, theme: unknown): Promise<void> {
409 const color = await backgroundOf($, theme)
410 await update($, themeBackground, () => color)
411}
412
413/** The `panel.background` values the panel said it does not take, so it says so once for each. */
414const unpaintable = new Set<string>()
415
416/**
417 * Reads `panel.background` through the CLI, which merges the `.projector.toml`
418 * files. The panel alone decides which values it takes, so the CLI stores any
419 * string. A value it does not take leaves the color to the theme, and the
420 * panel says so once. A read that fails keeps the value the panel last read,
421 * and the next reload reads it again.
422 */
423async function readBackground($: Engine): Promise<void> {
424 try {
425 const ran = await project($, ['config', 'get', BACKGROUND_KEY, '--default', AUTO, '--json'])
426 if (ran.exitCode !== 0) return
427 const value = (JSON.parse(ran.stdout) as { value?: unknown }).value ?? AUTO
428 const color = value === AUTO ? AUTO : typeof value === 'string' ? backgroundFor(value) : undefined
429 const written = JSON.stringify(value)
430 if (color === undefined && !unpaintable.has(written)) {
431 unpaintable.add(written)
432 void $.ui.toast(
433 `projector: ${BACKGROUND_KEY} is ${written}, which is not rgb(r,g,b), #rrggbb, ansi256(n), sidebar, black or white, so the panel takes its color from the theme`,
434 )
435 }
436 await update($, background, () => color ?? AUTO)
437 } catch {
438 // The next reload reads it again.
439 }
440}
441
442/** The session's own loops, the watchers it started, each with the pull requests its tracked file lists. */
443async function trackedSets($: Engine): Promise<(SeenLoop & { entries: TrackedPr[] })[]> {
444 const loops = (await read($, seen)).filter(loop => isKind(loop.kind))
445 // A tracked file that is gone belongs to a loop that ended.
446 return Promise.all(
447 loops.map(async loop => ({
448 ...loop,
449 entries: await $.fs.read(loop.tracked).then(parseTracked, () => [] as TrackedPr[]),
450 })),
451 )
452}
453
454async function load($: Engine): Promise<void> {
455 const sets = await trackedSets($)
456
457 const kindsOf = new Map<string, LoopKind[]>()
458 const tracked = new Map<string, TrackedPr>()
459 for (const kind of KINDS) {
460 for (const entry of sets.filter(set => set.kind === kind).flatMap(set => set.entries)) {
461 const key = keyOf(entry)
462 tracked.set(key, tracked.get(key) ?? entry)
463 const kinds = kindsOf.get(key) ?? []
464 if (!kinds.includes(kind)) kindsOf.set(key, [...kinds, kind])
465 }
466 }
467
468 // Each reload reads the panel's setting too, so an edit to it shows without a restart.
469 const [fetched] = await Promise.all([fetchPrs($, [...tracked.values()]), readBackground($)])
470
471 // When GitHub cannot be reached, keep drawing what it said last time.
472 const last = current(await read($, snapshot))
473 const previous = new Map(last.rows.map(row => [keyOf(row.pr), row.pr]))
474 const isFetched = fetched.error === null
475
476 const rows: Row[] = [...kindsOf].flatMap(([key, kinds]) => {
477 const pr = fetched.prs.get(key) ?? (isFetched ? undefined : previous.get(key))
478 return pr !== undefined && pr.state === 'OPEN' ? [{ pr, kinds }] : []
479 })
480
481 const time = await $.clock.now()
482 await update($, snapshot, () => ({
483 rows,
484 viewer: fetched.viewer ?? last.viewer,
485 fetchedAt: isFetched ? time : last.fetchedAt,
486 error: fetched.error,
487 }))
488 await update($, now, () => time)
489 await closeLeftDrawer($, time)
490 await loadThreads($)
491}
492
493/**
494 * Reloads the loops and their pull requests, only while the panel is shown
495 * unless forced. A request that arrives mid-load runs once more after it,
496 * so a change it was told about is never missed.
497 */
498function refresh($: Engine, isForced = false): Promise<void> {
499 if (inFlight !== undefined) {
500 isQueued = true
501 return inFlight
502 }
503 inFlight = (async () => {
504 try {
505 if (isForced || (await read($, isShown))) {
506 attemptedAt = await $.clock.now()
507 await load($)
508 }
509 } catch (error) {
510 const message = messageOf(error)
511 await update($, snapshot, last => ({ ...current(last), error: message })).catch(() => undefined)
512 }
513 })().finally(() => {
514 inFlight = undefined
515 if (isQueued) {
516 isQueued = false
517 void refresh($)
518 }
519 })
520 return inFlight
521}
522
523/** Puts an item the CLI just changed in the panel's list, in place of what it showed. */
524async function replace($: Engine, item: Item): Promise<void> {
525 await update($, items, list => list.map(one => (one.ref === item.ref && one.session === item.session ? item : one)))
526 await forgetAsked($, [item])
527}
528
529/**
530 * Forgets what an item's drawer was asking once the question no longer fits
531 * the item, wherever that happened: either question once the item is
532 * resolved, and how long to snooze once it is snoozed. The drawer then opens
533 * on its actions when the item comes back. A snoozed item can still be
534 * dismissed, so its dismiss confirmation stands.
535 */
536async function forgetAsked($: Engine, changed: readonly Item[]): Promise<void> {
537 const was = await read($, asked)
538 const item = changed.find(one => `item:${one.ref}` === was?.drawer)
539 if (was === null || item === undefined) return
540 const isMoot =
541 item.answer !== undefined || (was.about === 'snooze' && isSnoozedAt(item, await $.clock.now()))
542 if (!isMoot) return
543 await update($, asked, now => (now?.drawer === was.drawer && now.about === was.about ? null : now))
544}
545
546/** Closes a drawer when it is the one open, and with it anything the drawer was asking. */
547async function closeDrawer($: Engine, key: string): Promise<void> {
548 await update($, drawer, was => (was === key ? null : was))
549 await update($, asked, was => (was?.drawer === key ? null : was))
550}
551
552/**
553 * Closes the open drawer once its line has left the panel, so it does not
554 * open again by itself when the line comes back: a pull request a loop
555 * tracks again, or an item restored or woken from its snooze.
556 */
557async function closeLeftDrawer($: Engine, time: number): Promise<void> {
558 const opened = await read($, drawer)
559 if (opened === null) return
560 const isListed = opened.startsWith('item:')
561 ? (await read($, items)).some(item => `item:${item.ref}` === opened && isShownAt(item, time))
562 : current(await read($, snapshot)).rows.some(row => keyOf(row.pr) === opened)
563 if (!isListed) await closeDrawer($, opened)
564}
565
566/**
567 * An item as the CLI prints it, without the session the panel adds. Each kind
568 * is its own `Omit`, because one over the union would merge their `kind`s.
569 */
570type Printed = Omit<Question, 'session'> | Omit<Notice, 'session'>
571
572/** The item a CLI command printed with `--json`, in the session it belongs to. */
573const itemOf = (stdout: string, session: string): Item => ({
574 ...(JSON.parse(stdout) as { item: Printed }).item,
575 session,
576})
577
578/**
579 * Takes the panel's list from the store, and shows the panel for an item that
580 * is open and not snoozed when the panel last held it otherwise: a new item,
581 * or one restored or unsnoozed since.
582 */
583async function setItems($: Engine, list: Item[]): Promise<void> {
584 const time = await $.clock.now()
585 let isNew = false
586 await update($, items, before => {
587 const isAwake = (item: Item) => item.answer === undefined && !isSnoozedAt(item, time)
588 const awake = new Set(before.filter(isAwake).map(one => one.ref))
589 isNew = list.some(one => isAwake(one) && !awake.has(one.ref))
590 return list
591 })
592 await forgetAsked($, list)
593 if (isNew && !(await read($, isShown))) show($)
594}
595
596/**
597 * Reads the session's inbox when the store's directory changed since the
598 * last read that succeeded. Listing a directory starts no process, so an idle
599 * session, panel shown or hidden, starts none. The signature is recorded only
600 * once the read succeeds, so a read that fails runs again on the next tick.
601 */
602async function readStore($: Engine, session: string): Promise<void> {
603 const store = storeOf(await envOf($), session)
604 if (store === undefined) return
605 const entries = await $.fs.list(store).catch(() => [] as FsEntry[])
606 const files = signatureOf(entries, new Set(Object.keys(await read($, sending))))
607 const signature = `${session}\n${files}`
608 if (signature === listed) return
609 if (files === '') {
610 await setItems($, [])
611 } else {
612 const ran = await project($, ['inbox', 'list', '--all', '--json', '--session', session])
613 if (ran.exitCode !== 0) return
614 const { items: list } = JSON.parse(ran.stdout) as { items: Item[] }
615 await setItems($, list)
616 }
617 listed = signature
618}
619
620/** Remembers an answer the panel is delivering, in the session's state so a reloaded module finds it. */
621const track = ($: Engine, entry: Sending) => update($, sending, all => ({ ...all, [entry.ref]: entry }))
622
623/**
624 * Ends a delivery: marks the answer delivered, or reopens its question and
625 * says why. Whichever of the submit's own answer and the prompt hook comes
626 * first takes the delivery out of the state, and the other finds it gone.
627 */
628async function settle($: Engine, ref: string, outcome: 'delivered' | 'reopen', reason?: string): Promise<void> {
629 let entry: Sending | undefined
630 await update($, sending, all => {
631 entry = all[ref]
632 return Object.fromEntries(Object.entries(all).filter(([key]) => key !== ref))
633 })
634 if (entry === undefined) return
635 const { session, token, text } = entry
636 const ran = await project($, ['inbox', outcome, ref, '--claim', token, '--session', session, '--json']).catch(
637 () => undefined,
638 )
639 if (ran?.exitCode === 0) await replace($, itemOf(ran.stdout, session))
640 if (outcome === 'reopen') {
641 // You never see an item's number, so the toast names the question by its
642 // subject. A restore's line is not sent again, and its question stays open.
643 const question = (await read($, items)).find(one => one.ref === ref && one.session === session)
644 const quoted = question === undefined ? undefined : quoteOf(question)
645 const why = reason ? ` (${reason})` : ''
646 void $.ui.toast(
647 text.startsWith('RESTORED ')
648 ? `projector: word that ${quoted ?? 'a question'} is open again did not reach its agent${why}`
649 : `projector: ${quoted === undefined ? 'an answer' : `the answer to ${quoted}`} did not reach its agent${why}; answer it again`,
650 )
651 }
652}
653
654/**
655 * Claims a recorded answer and delivers it: to the subagent that asked while
656 * it can still read a message, otherwise to the main loop as a prompt of its
657 * own, which waits for the session to be idle.
658 */
659async function deliver($: Engine, question: Question): Promise<void> {
660 const { ref, session } = question
661 delivering.add(ref)
662 try {
663 const ran = await project($, ['inbox', 'claim', ref, '--session', session, '--json'])
664 // Another deliverer holds it, or it was delivered since the panel read the store.
665 if (ran.exitCode !== 0) return
666 const claimed = JSON.parse(ran.stdout) as { token: string; text: string }
667 await replace($, itemOf(ran.stdout, session))
668
669 const agents = question.agentId === undefined ? [] : await $.agent.list().catch(() => [])
670 const agentId = liveAgent(question, agents)
671 if (agentId !== undefined) {
672 await track($, { ref, session, token: claimed.token, route: 'send', text: claimed.text })
673 const sent = await $.session.send({ to: { agentId }, text: claimed.text }).catch(() => undefined)
674 if (sent?.isDelivered === true) return await settle($, ref, 'delivered')
675 }
676
677 const text = forMainLoop(claimed.text, question, agents)
678 await track($, { ref, session, token: claimed.token, route: 'submit', text })
679 const submitted = await $.prompt.submit({ text }).catch((error: unknown) => ({ drop: messageOf(error) }))
680 await settle($, ref, submitted.drop === undefined ? 'delivered' : 'reopen', submitted.drop)
681 } catch (error) {
682 await settle($, ref, 'reopen', messageOf(error))
683 } finally {
684 delivering.delete(ref)
685 }
686}
687
688/** The panel's takeover of `oldSending`, which runs once per load of the module. */
689let adoption: Promise<void> | undefined
690
691/** Moves the deliveries under `oldSending` into `sending`, once per load, and again after a failure. */
692function adoptOldSending($: Engine): Promise<void> {
693 adoption ??= (async () => {
694 const old = await read($, oldSending)
695 if (Object.keys(old).length === 0) return
696 await update($, sending, all => ({ ...old, ...all }))
697 await update($, oldSending, () => ({}))
698 })().catch(() => {
699 adoption = undefined
700 })
701 return adoption
702}
703
704/**
705 * Keeps each delivery's claim live while it waits, as a submit behind a long
706 * turn does. A submit that an earlier copy of the module made still waits in
707 * the session's queue, so its claim is kept until the prompt hook sees it
708 * arrive. A send settles at once, so one an earlier copy left is let go, and
709 * its claim lapses for the panel to deliver again.
710 */
711async function renewClaims($: Engine): Promise<void> {
712 await adoptOldSending($)
713 for (const entry of Object.values(await read($, sending))) {
714 if (entry.route === 'send' && !delivering.has(entry.ref)) {
715 await update($, sending, all => Object.fromEntries(Object.entries(all).filter(([key]) => key !== entry.ref)))
716 continue
717 }
718 await project($, ['inbox', 'claim', entry.ref, '--renew', entry.token, '--session', entry.session]).catch(
719 () => undefined,
720 )
721 }
722}
723
724/**
725 * Reads the store when it changed, renews the panel's claims, and delivers
726 * each answer nobody is delivering. A store read that fails, as one still
727 * running at the CLI's timeout does, skips nothing after it, so a waiting
728 * answer's claim never lapses because of it.
729 */
730async function checkInbox($: Engine): Promise<void> {
731 if (isChecking) return
732 isChecking = true
733 try {
734 const session = await $.session.id()
735 await readStore($, session).catch(() => undefined)
736 await renewClaims($)
737 const time = await $.clock.now()
738 const pending = await read($, sending)
739 for (const item of await read($, items)) {
740 if (item.session !== session || delivering.has(item.ref) || item.ref in pending) continue
741 if (needsDelivery(item, time)) void deliver($, item)
742 }
743 } catch {
744 // The next tick tries again.
745 } finally {
746 isChecking = false
747 }
748}
749
750/** Checks the inbox now rather than at the next tick. */
751const checkSoon = ($: Engine) => $.clock.after(1, () => void checkInbox($))
752
753/**
754 * Dismisses, snoozes for `minutes`, or restores an item from the panel; a
755 * second press finds it changed and does nothing. Dismissing or snoozing
756 * closes the item's drawer, and the item stays listed, muted, for 30 seconds,
757 * so its line opens the drawer again to restore it. Restoring keeps the
758 * drawer open on the item, open again.
759 */
760async function act(
761 $: Engine,
762 item: Item,
763 command: 'dismiss' | 'snooze' | 'restore',
764 minutes?: number,
765): Promise<void> {
766 const { ref, session } = item
767 if (acting.has(ref)) return
768 acting.add(ref)
769 try {
770 const length = minutes === undefined ? [] : ['--for', String(minutes)]
771 const ran = await project($, ['inbox', command, ref, ...length, '--session', session, '--json'])
772 if (ran.exitCode === 0) {
773 await replace($, itemOf(ran.stdout, session))
774 if (command !== 'restore') await closeDrawer($, `item:${ref}`)
775 } else if (ran.exitCode === 65) {
776 // Resolved elsewhere since the panel read the store: read it again.
777 listed = undefined
778 } else {
779 void $.ui.toast(`projector: ${errorOf(ran)}`)
780 }
781 checkSoon($)
782 } catch (error) {
783 void $.ui.toast(`projector: ${messageOf(error)}`)
784 } finally {
785 acting.delete(ref)
786 }
787}
788
789/**
790 * Dismisses a pull request from the session's loops: `project loop drop`
791 * keeps it out of each tracked file that lists it, and the panel reloads
792 * without it. A failure says why, and the line stays.
793 */
794async function dismissPr($: Engine, pr: PullRequest): Promise<void> {
795 const key = keyOf(pr)
796 const named = `${pr.repo}#${pr.number}`
797 if (acting.has(key)) return
798 acting.add(key)
799 const stopped: LoopKind[] = []
800 try {
801 for (const loop of await trackedSets($)) {
802 if (!loop.entries.some(entry => keyOf(entry) === key)) continue
803 const ran = await project($, ['loop', 'drop', named, '--tracked', loop.tracked])
804 if (ran.exitCode !== 0) {
805 void $.ui.toast(`projector: ${errorOf(ran)}`)
806 return
807 }
808 stopped.push(loop.kind)
809 }
810 await closeDrawer($, key)
811 } catch (error) {
812 void $.ui.toast(`projector: ${messageOf(error)}`)
813 } finally {
814 acting.delete(key)
815 const kinds = KINDS.filter(kind => stopped.includes(kind))
816 if (kinds.length > 0) void $.ui.toast(`projector: stopped ${kinds.join(' and ')} ${named}`)
817 await refresh($)
818 }
819}
820
821/**
822 * Records an answer a sent prompt gave and marks it delivered, because the
823 * prompt itself carries it to the main loop. The panel's own deliverer leaves
824 * the question alone meanwhile, so the agent hears the answer once.
825 */
826async function answerFromPrompt($: Engine, question: Question, letter: string): Promise<void> {
827 const { ref, session } = question
828 delivering.add(ref)
829 try {
830 const answered = await project($, ['inbox', 'answer', `${ref}.${letter}`, '--session', session, '--json'])
831 if (answered.exitCode !== 0) return
832 const claimed = await project($, ['inbox', 'claim', ref, '--session', session, '--json'])
833 if (claimed.exitCode !== 0) return
834 const { token } = JSON.parse(claimed.stdout) as { token: string }
835 const ran = await project($, ['inbox', 'delivered', ref, '--claim', token, '--session', session, '--json'])
836 if (ran.exitCode === 0) await replace($, itemOf(ran.stdout, session))
837 } catch {
838 // An answer recorded but not marked delivered is the panel's to deliver on a later tick.
839 } finally {
840 delivering.delete(ref)
841 }
842}
843
844/**
845 * Reads the inbox whether or not the panel is shown, closes the drawer of an
846 * item that left the panel, and brings a hidden panel back for an item whose
847 * snooze ended since the last tick. A shown panel moves
848 * its clock on, which returns that item to the list, and polls GitHub once
849 * the last load is old enough.
850 */
851async function tick($: Engine): Promise<void> {
852 // Read before the store, so a snooze that ends while the store is read
853 // falls in the next tick's window.
854 const time = await $.clock.now()
855 await checkInbox($)
856 await closeLeftDrawer($, time).catch(() => undefined)
857 const since = tickedAt ?? time
858 tickedAt = time
859 if (!(await read($, isShown))) {
860 if (wokeBetween(await read($, items), since, time).length > 0) show($)
861 return
862 }
863 await update($, now, () => time)
864 if (time - attemptedAt >= POLL_MS) await refresh($)
865}
866
867/**
868 * Shows the panel and loads it, from a timer so no hook waits on GitHub. The
869 * panel's clock moves on before it shows, so an item whose snooze ended while
870 * it was hidden is drawn at once rather than after GitHub answers.
871 */
872function show($: Engine): void {
873 $.clock.after(1, () => {
874 void $.clock
875 .now()
876 .then(time => update($, now, () => time))
877 .then(() => update($, isShown, () => true))
878 .then(() => refresh($, true))
879 })
880}
881
882/**
883 * Puts the panel's key hint back on the chord into the panel once the prompt
884 * has the keyboard again. Only a change of hint redraws the panel.
885 */
886async function unfocus($: Engine): Promise<void> {
887 if (!(await read($, isFocused))) return
888 await update($, isFocused, () => false)
889 $.ui.invalidate('ui.render')
890}
891
892/**
893 * Moves the panel's focus ring onto one of its elements, which the engine
894 * waits for when the panel has yet to draw it, and writes why the ring stayed
895 * to the debug log when the engine refuses the move.
896 */
897async function focusOn($: Engine, requestId: string, key: string): Promise<void> {
898 const moved = await $.ui.focus({ requestId, key }).catch((error: unknown) => ({ deny: messageOf(error) }))
899 if (moved.deny !== undefined) $.ui.log(`projector: the focus stayed off ${key}: ${moved.deny}`, { to: 'debug' })
900}
901
902/** Refreshes soon, from a timer so the hook that noticed a change returns at once. */
903const soon = ($: Engine) => $.clock.after(1, () => void refresh($))
904
905/**
906 * Names a pull request for the prompt: `#12` when the panel shows one
907 * repository, `owner/repo#12` otherwise, so the reference is never ambiguous.
908 */
909function referencer(prs: readonly PullRequest[]): (pr: PullRequest) => string {
910 const isOneRepo = new Set(prs.map(pr => pr.repo)).size <= 1
911 return pr => (isOneRepo ? `#${pr.number}` : `${pr.repo}#${pr.number}`)
912}
913
914type Note = { text: string; color: 'error' | 'warning' | 'success' }
915
916/** What a row says after the title: what holds the pull request back, or its approval. */
917function notesOf(pr: PullRequest): Note[] {
918 const notes: Note[] = []
919 if (pr.isConflicting) notes.push({ text: 'conflict', color: 'error' })
920 if (pr.reviewDecision === 'CHANGES_REQUESTED') notes.push({ text: 'changes requested', color: 'error' })
921 if (pr.reviewDecision === 'APPROVED') notes.push({ text: 'approved', color: 'success' })
922 // The open threads' count comes last, beside the age.
923 if (pr.openThreads > 0) notes.push({ text: `${pr.openThreads}*`, color: 'warning' })
924 return notes
925}
926
927/** How much of a thread's first line its drawer line shows. */
928const EXCERPT_LENGTH = 60
929
930/**
931 * A thread's line in its pull request's drawer: where it is, who opened it,
932 * how it starts, and whether a later push left it outdated.
933 */
934function threadLabel(thread: Thread): string {
935 const place = thread.line === null ? thread.path : `${thread.path}:${thread.line}`
936 const excerpt =
937 thread.excerpt.length > EXCERPT_LENGTH ? `${thread.excerpt.slice(0, EXCERPT_LENGTH - 1).trimEnd()}…` : thread.excerpt
938 return [place, thread.author, excerpt, thread.isOutdated ? 'outdated' : null]
939 .filter(piece => piece !== null && piece !== '')
940 .join(' · ')
941}
942
943/** Whether the account the panel's `gh` is signed in as wrote a pull request. */
944const isOwn = (pr: PullRequest, viewer: string | null) => viewer !== null && pr.author === viewer
945
946/**
947 * The panel's pull requests in the order it lists them: yours first, then
948 * everyone else's, each author's together and the authors by login. Within
949 * each, they keep the order they came in.
950 */
951function byAuthor(rows: readonly Row[], viewer: string | null): Row[] {
952 const loginOf = (row: Row) => (row.pr.author ?? '').toLowerCase()
953 const others = rows.filter(row => !isOwn(row.pr, viewer))
954 return [
955 ...rows.filter(row => isOwn(row.pr, viewer)),
956 ...others.sort((one, other) => loginOf(one).localeCompare(loginOf(other))),
957 ]
958}
959
960const secondsSince = (time: number, then: number) => Math.max(0, Math.round((time - then) / 1000))
961
962/** `1 question` or `3 questions`, or nothing for none. */
963const countOf = (count: number, noun: string) =>
964 count === 0 ? undefined : `${count} ${noun}${count === 1 ? '' : 's'}`
965
966/** Labels a pull request `#12` when the panel shows one repository, else by its repository's name. */
967function labeler(prs: readonly PullRequest[]): (pr: PullRequest) => string {
968 const repos = [...new Set(prs.map(pr => pr.repo))]
969 if (repos.length <= 1) return pr => `#${pr.number}`
970 const names = repos.map(repo => repo.split('/')[1])
971 const isNameEnough = new Set(names).size === names.length
972 return pr => `${isNameEnough ? pr.repo.split('/')[1] : pr.repo}#${pr.number}`
973}
974
975/**
976 * Runs the `project inbox` command one of the tools makes: what it printed,
977 * or why the tool call is refused. `instead` says where the agent turns when
978 * the command does not finish.
979 */
980async function runTool(
981 $: Engine,
982 args: string[] | { error: string },
983 instead: string,
984): Promise<{ stdout: string } | { deny: string }> {
985 if (!Array.isArray(args)) return { deny: args.error }
986 let ran: Ran
987 try {
988 ran = await project($, args)
989 } catch (error) {
990 return { deny: `project did not finish (${messageOf(error)}); ${instead}` }
991 }
992 // 65 refuses the call, 66 finds no such item, and 75 finds the store busy;
993 // any other failure is a CLI too old to know the command.
994 if (ran.exitCode === 65 || ran.exitCode === 66 || ran.exitCode === 75) return { deny: errorOf(ran) }
995 if (ran.exitCode !== 0) return { deny: `${errorOf(ran)}; run project upgrade` }
996 checkSoon($)
997 return { stdout: ran.stdout }
998}
999
1000export const register: Register = on => {
1001 on('session.start', async ($, e, next) => {
1002 await $.command.register({
1003 name: 'projector',
1004 description: 'Show or hide Projector’s panel of your loops’ pull requests and your inbox',
1005 })
1006 // A session whose engine cannot serve the tools keeps the panel.
1007 for (const tool of [
1008 { name: 'ask', description: ASK_DESCRIPTION, inputSchema: ASK_SCHEMA },
1009 { name: 'tell', description: TELL_DESCRIPTION, inputSchema: TELL_SCHEMA },
1010 { name: 'withdraw', description: WITHDRAW_DESCRIPTION, inputSchema: WITHDRAW_SCHEMA },
1011 { name: 'revise', description: REVISE_DESCRIPTION, inputSchema: REVISE_SCHEMA },
1012 { name: 'restore', description: RESTORE_DESCRIPTION, inputSchema: RESTORE_SCHEMA },
1013 ]) {
1014 await $.tool.register({ ...tool, isDeferred: false }).catch(() => undefined)
1015 }
1016 // The panel takes its color from the theme, and from its setting once a
1017 // timer has read it, so the start waits on no process.
1018 await $.config
1019 .list()
1020 .then(rows => paint($, rows.find(row => row.key === 'theme')?.value))
1021 .catch(() => undefined)
1022 $.clock.after(1, () => void readBackground($))
1023 $.clock.every(TICK_MS, () => void tick($))
1024 soon($)
1025 checkSoon($)
1026 return next(e)
1027 })
1028
1029 // A theme picked in `/theme` recolors the panel at once.
1030 on('config.set', { key: 'theme' }, async ($, e, next) => {
1031 const set = await next(e)
1032 if (set.deny === undefined) await paint($, set.value)
1033 return set
1034 }).catch(($, e, next) => next(e))
1035
1036 // The tools run the CLI, so what they post, withdraw, or revise and what
1037 // the shell does land in the same store.
1038 on('tool.call', { tool: ASK_TOOL }, async ($, e) => {
1039 const posted = await runTool($, askArguments(e, await $.session.id(), e.agentId), 'ask in the conversation instead')
1040 if ('deny' in posted) return posted
1041 const ref = posted.stdout.trim()
1042 void $.ui.notify(String(e.question), { title: 'Projector question' }).catch(() => undefined)
1043 return {
1044 result: `Asked ${ref}. Keep working on anything the answer does not block; it arrives as a message that starts ANSWER ${ref} or DISMISSED ${ref}. Projector’s panel never shows this number, so name the question to the person by what it asks.`,
1045 }
1046 }).catch(() => ({ deny: 'Projector could not record the question; ask it in the conversation instead' }))
1047
1048 on('tool.call', { tool: TELL_TOOL }, async ($, e) => {
1049 const args = tellArguments(e, await $.session.id(), e.agentId)
1050 const posted = await runTool($, args, 'tell the person in the conversation instead')
1051 if ('deny' in posted) return posted
1052 const ref = posted.stdout.trim()
1053 void $.ui.notify(String(e.notice), { title: 'Projector notice' }).catch(() => undefined)
1054 return {
1055 result: `Posted ${ref}. It waits in Projector’s panel until the person dismisses it; nothing comes back to you. Projector’s panel never shows this number, so name the notice to the person by what it tells.`,
1056 }
1057 }).catch(() => ({ deny: 'Projector could not record the notice; tell the person in the conversation instead' }))
1058
1059 // The panel takes the withdrawn item from the CLI at once, so it leaves the
1060 // panel before the next read of the store.
1061 on('tool.call', { tool: WITHDRAW_TOOL }, async ($, e) => {
1062 const session = await $.session.id()
1063 const instead = 'tell the person in the conversation that it no longer needs them'
1064 const ran = await runTool($, withdrawArguments(e, session), instead)
1065 if ('deny' in ran) return ran
1066 const item = itemOf(ran.stdout, session)
1067 await replace($, item)
1068 await closeDrawer($, `item:${item.ref}`)
1069 return { result: `Withdrew ${item.ref}. It has left Projector’s panel, and nothing comes back to you.` }
1070 }).catch(() => ({
1071 deny: 'Projector could not withdraw the item; tell the person in the conversation that it no longer needs them',
1072 }))
1073
1074 // The panel takes the revised question from the CLI at once, so it redraws
1075 // before the next read of the store. An answer a drawer put in the prompt
1076 // was chosen from the old text, so it turns stale: sent, it answers no
1077 // question, this one or another that shares the old text.
1078 on('tool.call', { tool: REVISE_TOOL }, async ($, e) => {
1079 const session = await $.session.id()
1080 const ran = await runTool($, reviseArguments(e, session), 'ask the revised question in the conversation instead')
1081 if ('deny' in ran) return ran
1082 const item = itemOf(ran.stdout, session)
1083 await replace($, item)
1084 proposed = proposed.map(proposal => (proposal.ref === item.ref ? { ...proposal, isStale: true } : proposal))
1085 return {
1086 result: `Revised ${item.ref}. Projector’s panel shows the new text, and its answer still arrives as a message that starts ANSWER ${item.ref} or DISMISSED ${item.ref}.`,
1087 }
1088 }).catch(() => ({
1089 deny: 'Projector could not revise the question; ask the revised question in the conversation instead',
1090 }))
1091
1092 // The panel takes the restored item from the CLI at once, so it is open in
1093 // the panel before the next read of the store, and comes back as a new item
1094 // does when the person hid it.
1095 on('tool.call', { tool: RESTORE_TOOL }, async ($, e) => {
1096 const session = await $.session.id()
1097 const instead = 'tell the person in the conversation that it could not be restored'
1098 const ran = await runTool($, restoreArguments(e, session), instead)
1099 if ('deny' in ran) return ran
1100 const item = itemOf(ran.stdout, session)
1101 await replace($, item)
1102 if (!(await read($, isShown))) show($)
1103 const { ref } = item
1104 return {
1105 result:
1106 item.kind === 'notice'
1107 ? `Restored ${ref}. It is back in Projector’s panel until the person dismisses it; nothing comes back to you.`
1108 : `Restored ${ref}. It is open in Projector’s panel again, and its answer arrives as a message that starts ANSWER ${ref} or DISMISSED ${ref}. An agent that already heard DISMISSED ${ref} hears RESTORED ${ref} first.`,
1109 }
1110 }).catch(() => ({
1111 deny: 'Projector could not restore the item; tell the person in the conversation that it could not be restored',
1112 }))
1113
1114 // These hooks only watch: the catch hands back what the event settled to,
1115 // so a failure here never runs a tool twice or refuses anything.
1116 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
1117 const ran = await next(e)
1118 if (ran.deny === undefined) await adopt($, e.command)
1119 return ran
1120 }).catch(($, e, next) => next(e))
1121
1122 on('tool.call', { tool: 'Monitor' }, async ($, e, next) => {
1123 const ran = await next(e)
1124 if (ran.deny === undefined) await adopt($, e.command ?? '')
1125 return ran
1126 }).catch(($, e, next) => next(e))
1127
1128 on('prompt.submit', async ($, e, next) => {
1129 // A watcher's line reaches the session as a task notification: the moment
1130 // a pull request it tracks has changed.
1131 if (e.origin.kind === 'task-notification') soon($)
1132
1133 // A prompt sent from the terminal means the prompt has the keyboard, even
1134 // when no keystroke edited it since Esc, as with one a drawer filled.
1135 if (e.origin.kind === 'composer') void unfocus($).catch(() => undefined)
1136
1137 // An answer the panel submitted for the main loop has arrived. Seeing it
1138 // here, rather than only where the panel submitted it, settles it after a
1139 // reload of the module too.
1140 if (e.origin.kind === 'plugin' && e.origin.name === 'projector') {
1141 const entered = await next(e)
1142 if (entered.drop === undefined) {
1143 await adoptOldSending($)
1144 const entry = Object.values(await read($, sending)).find(one => one.route === 'submit' && one.text === e.text)
1145 if (entry !== undefined) await settle($, entry.ref, 'delivered')
1146 }
1147 return entered
1148 }
1149
1150 // An option the panel put in the prompt answers its question: the prompt
1151 // carries the answer to the main loop, and once the prompt has entered,
1152 // the panel records it. Any other text under a quoted question replies to
1153 // it, and the prompt carries the reply while the question stays open.
1154 // Either way the prompt is done with the question's drawer. A subagent's
1155 // question gets a note naming it, so the main loop can pass the answer or
1156 // the reply on. Only a prompt you sent, at the terminal or through Remote
1157 // Control, counts: an agent's message or a notification can quote a
1158 // question it is still waiting on.
1159 const session = await $.session.id()
1160 const isYours = e.origin.kind === 'composer' || e.origin.kind === 'bridge'
1161 const mine = isYours ? (await read($, items)).filter(item => item.session === session) : []
1162 const { answers, replies } = readPrompt(e.text, mine, isYours ? proposed : [])
1163 // An open question is done only when the prompt answers or replies to
1164 // it, so a quote two questions share closes one drawer, not both.
1165 const isOpenQuestion = (item: Item) => item.kind === 'question' && item.answer === undefined
1166 const done = new Set([
1167 ...mine.filter(item => !isOpenQuestion(item) && e.text.includes(quoteOf(item))).map(item => item.ref),
1168 ...answers.map(one => one.question.ref),
1169 ...replies.map(question => question.ref),
1170 ])
1171 if (isYours) proposed = proposed.filter(proposal => !done.has(proposal.ref) && !e.text.includes(proposal.quote))
1172 const answered = answers.map(one => one.question).filter(question => question.agentId !== undefined)
1173 const replied = replies.filter(question => question.agentId !== undefined)
1174 const agents = answered.length + replied.length === 0 ? [] : await $.agent.list().catch(() => [])
1175 const notes = [
1176 ...answered.map(question => relayNote(question, agents)),
1177 ...replied.map(question => replyNote(question, agents)),
1178 ]
1179 const entered = await next(notes.length === 0 ? e : { ...e, context: [...(e.context ?? []), ...notes] })
1180 if (entered.drop === undefined) {
1181 for (const ref of done) void closeDrawer($, `item:${ref}`).catch(() => undefined)
1182 for (const one of answers) void answerFromPrompt($, one.question, one.letter)
1183 }
1184 return entered
1185 }).catch(($, e, next) => next(e))
1186
1187 // Enter presses the panel's element under the ring, so where the ring is
1188 // tells a press from the keyboard from a click. A ring that lands also
1189 // means the panel holds the keyboard, so its hint names the keys that work
1190 // there.
1191 on('ui.focus', { component: 'AbovePrompt' }, async ($, e, next) => {
1192 const moved = await next(e)
1193 if (moved.deny === undefined) {
1194 ring = { requestId: e.requestId, key: e.plugin === 'projector' ? e.element : undefined }
1195 if (!(await read($, isFocused))) {
1196 await update($, isFocused, () => true)
1197 $.ui.invalidate('ui.render')
1198 }
1199 }
1200 return movedhooks/github.ts 204 lines1import type { Checks, PullRequest, Thread } from './types'
2import { keyOf, type TrackedPr } from './parse'
3
4/** Where one pull request's node sits in the response. */
5type Slot = { pr: TrackedPr; repoAlias: string; prAlias: string }
6
7export type Query = { text: string; slots: Slot[] }
8
9export type Fetched = {
10 prs: Map<string, PullRequest>
11 /** The login of the account `gh` is signed in as; null when GitHub did not say. */
12 viewer: string | null
13 error: string | null
14}
15
16const FIELDS = `number title url state isDraft reviewDecision mergeable body
17 author { login } headRefName additions deletions changedFiles updatedAt
18 reviewThreads(first: 100) { nodes { isResolved } }
19 commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }`
20
21// What an open drawer lists of its pull request's threads. GitHub counts
22// `comments` under `reviewThreads(first: 100)` as 100 requests, a point of
23// the account's quota, for each pull request. So the poll reads only
24// `isResolved`, and the panel asks for these for the open drawer's alone.
25const THREAD_FIELDS = `reviewThreads(first: 100) { nodes { isResolved isOutdated path line originalLine
26 comments(first: 1) { nodes { url bodyText author { login } } } } }`
27
28// The line `project summary publish` leaves at the bottom of a description.
29const SUMMARY = /^<!-- projector-summary v=1 sha=[0-9a-f]{40} -->\r?\n\S* ?\*\*Projector summary\*\* [^\r\n]*?(https?:\/\/\S+)\s*$/m
30
31const CHECKS: Record<string, Checks> = {
32 SUCCESS: 'passing',
33 FAILURE: 'failing',
34 ERROR: 'failing',
35 PENDING: 'pending',
36 EXPECTED: 'pending',
37}
38
39/**
40 * Builds one GraphQL query for every pull request, grouped by repository,
41 * and for the signed-in account's login. Repository names come from
42 * `parseTracked`, which admits only GitHub's name characters, so they are
43 * safe inside a string literal.
44 */
45export function buildQuery(prs: readonly TrackedPr[]): Query {
46 const query = queryOf(prs, FIELDS)
47 return { ...query, text: `query { viewer { login } ${query.text} }` }
48}
49
50/** Builds the query for one pull request's unresolved threads, which its open drawer lists. */
51export function buildThreadsQuery(pr: TrackedPr): Query {
52 const query = queryOf([pr], THREAD_FIELDS)
53 return { ...query, text: `query { ${query.text} }` }
54}
55
56/** The repositories' part of a query that asks for `fields` of each pull request. */
57function queryOf(prs: readonly TrackedPr[], fields: string): Query {
58 const byRepo = new Map<string, TrackedPr[]>()
59 for (const pr of prs) {
60 byRepo.set(pr.repo, [...(byRepo.get(pr.repo) ?? []), pr])
61 }
62
63 const slots: Slot[] = []
64 const repos = [...byRepo.entries()].map(([repo, list], index) => {
65 const [owner, name] = repo.split('/')
66 const repoAlias = `r${index}`
67 const pulls = list.map(pr => {
68 const prAlias = `p${pr.number}`
69 slots.push({ pr, repoAlias, prAlias })
70 return `${prAlias}: pullRequest(number: ${pr.number}) { ${fields} }`
71 })
72 return `${repoAlias}: repository(owner: "${owner}", name: "${name}") { ${pulls.join(' ')} }`
73 })
74
75 return { text: repos.join(' '), slots }
76}
77
78const isRecord = (value: unknown): value is Record<string, unknown> =>
79 typeof value === 'object' && value !== null && !Array.isArray(value)
80
81const firstLine = (text: string) => text.trim().split('\n')[0] ?? ''
82
83function messageOf(body: unknown): string | undefined {
84 if (!isRecord(body) || !Array.isArray(body.errors)) return undefined
85 const [first] = body.errors as unknown[]
86 return isRecord(first) && typeof first.message === 'string' ? first.message : undefined
87}
88
89const nodesOf = (value: unknown): unknown[] =>
90 isRecord(value) && Array.isArray(value.nodes) ? (value.nodes as unknown[]) : []
91
92const numberOf = (value: unknown) => (typeof value === 'number' ? value : 0)
93
94const stringOf = (value: unknown) => (typeof value === 'string' ? value : null)
95
96/** An unresolved thread as the drawer lists it, or null for a resolved one. */
97function threadOf(node: unknown): Thread | null {
98 if (!isRecord(node) || node.isResolved !== false) return null
99 const [first] = nodesOf(node.comments)
100 const comment = isRecord(first) ? first : {}
101 const line = typeof node.line === 'number' ? node.line : node.originalLine
102 return {
103 path: stringOf(node.path) ?? '',
104 line: typeof line === 'number' ? line : null,
105 isOutdated: node.isOutdated === true,
106 author: isRecord(comment.author) ? stringOf(comment.author.login) : null,
107 excerpt: firstLine(stringOf(comment.bodyText) ?? ''),
108 url: stringOf(comment.url),
109 }
110}
111
112function checksOf(node: Record<string, unknown>): Checks | null {
113 const [last] = nodesOf(node.commits)
114 const commit = isRecord(last) ? last.commit : undefined
115 const rollup = isRecord(commit) ? commit.statusCheckRollup : undefined
116 return isRecord(rollup) && typeof rollup.state === 'string' ? (CHECKS[rollup.state] ?? null) : null
117}
118
119function toPullRequest(pr: TrackedPr, node: Record<string, unknown>): PullRequest {
120 const threads = nodesOf(node.reviewThreads)
121 const state = node.state === 'MERGED' || node.state === 'CLOSED' ? node.state : 'OPEN'
122 const decision = node.reviewDecision
123 const updatedAt = typeof node.updatedAt === 'string' ? Date.parse(node.updatedAt) : Number.NaN
124 const summary = typeof node.body === 'string' ? SUMMARY.exec(node.body) : null
125 return {
126 repo: pr.repo,
127 number: pr.number,
128 title: typeof node.title === 'string' ? node.title : '',
129 url: typeof node.url === 'string' ? node.url : `https://github.com/${pr.repo}/pull/${pr.number}`,
130 state,
131 isDraft: node.isDraft === true,
132 reviewDecision:
133 decision === 'APPROVED' || decision === 'CHANGES_REQUESTED' || decision === 'REVIEW_REQUIRED'
134 ? decision
135 : null,
136 isConflicting: node.mergeable === 'CONFLICTING',
137 openThreads: threads.filter(thread => isRecord(thread) && thread.isResolved === false).length,
138 author: isRecord(node.author) && typeof node.author.login === 'string' ? node.author.login : null,
139 branch: typeof node.headRefName === 'string' ? node.headRefName : '',
140 additions: numberOf(node.additions),
141 deletions: numberOf(node.deletions),
142 changedFiles: numberOf(node.changedFiles),
143 checks: checksOf(node),
144 updatedAt: Number.isNaN(updatedAt) ? null : updatedAt,
145 summaryUrl: summary?.[1] ?? null,
146 }
147}
148
149type Result = { exitCode: number; stdout: string; stderr: string }
150
151/**
152 * The data in what `gh api graphql` printed. A pull request that does not
153 * exist leaves its slot null and adds an error, but the rest still answer, so
154 * errors fail the fetch only when no data came back at all.
155 */
156function dataOf(result: Result): { data: Record<string, unknown> } | { error: string } {
157 let body: unknown
158 try {
159 body = JSON.parse(result.stdout)
160 } catch {
161 return { error: firstLine(result.stderr) || `gh exited with ${result.exitCode}` }
162 }
163 if (isRecord(body) && isRecord(body.data)) return { data: body.data }
164 return { error: messageOf(body) ?? (firstLine(result.stderr) || 'GitHub returned no data') }
165}
166
167/** The node a slot names in a query's data, when GitHub gave one. */
168function nodeAt(data: Record<string, unknown>, slot: Slot): Record<string, unknown> | undefined {
169 const repo = data[slot.repoAlias]
170 const node = isRecord(repo) ? repo[slot.prAlias] : undefined
171 return isRecord(node) ? node : undefined
172}
173
174/** Reads what `gh api graphql` printed for `buildQuery`. */
175export function parseResponse(query: Query, result: Result): Fetched {
176 const read = dataOf(result)
177 if ('error' in read) return { prs: new Map(), viewer: null, error: read.error }
178 const { data } = read
179
180 const prs = new Map<string, PullRequest>()
181 for (const slot of query.slots) {
182 const node = nodeAt(data, slot)
183 if (node !== undefined) prs.set(keyOf(slot.pr), toPullRequest(slot.pr, node))
184 }
185
186 const viewer = isRecord(data.viewer) && typeof data.viewer.login === 'string' ? data.viewer.login : null
187 return { prs, viewer, error: null }
188}
189
190/**
191 * Reads what `gh api graphql` printed for `buildThreadsQuery`: the pull
192 * request's unresolved threads, oldest first, or null when GitHub gave none
193 * of it.
194 */
195export function parseThreads(query: Query, result: Result): Thread[] | null {
196 const read = dataOf(result)
197 const [slot] = query.slots
198 const node = 'error' in read || slot === undefined ? undefined : nodeAt(read.data, slot)
199 if (node === undefined) return null
200 return nodesOf(node.reviewThreads)
201 .map(threadOf)
202 .filter(thread => thread !== null)
203}
204hooks/parse.ts 224 lines1import type { LoopKind } from './types'
2
3/** Looks up an environment variable; undefined when it is unset or unknown. */
4export type Env = (name: string) => string | undefined
5
6/** A watcher found in a command line, and the tracked path it was given. */
7export type Watcher = {
8 kind: LoopKind
9 /** The path, expanded; undefined when it could not be expanded. */
10 tracked: string | undefined
11 /** The `--tracked` argument as written, for messages. */
12 written: string
13}
14
15/** One `owner/repo#number` entry of a tracked file. */
16export type TrackedPr = { repo: string; number: number }
17
18const SCRIPTS: Record<string, LoopKind> = {
19 'watch-prs.sh': 'reviewing',
20 'watch-threads.sh': 'watching',
21}
22
23const OPERATORS = ['&&', '||', ';', '&', '|', '(', ')', '\n']
24
25type Part = { text: string; isLiteral: boolean }
26type Token = { parts: Part[] } | { operator: string }
27
28/**
29 * Splits a shell command into words and operators, keeping which parts of a
30 * word were quoted so that expansion leaves single-quoted text alone.
31 */
32export function tokenize(command: string): Token[] {
33 const tokens: Token[] = []
34 let parts: Part[] = []
35 let isInWord = false
36
37 const add = (text: string, isLiteral: boolean) => {
38 isInWord = true
39 const last = parts[parts.length - 1]
40 if (last !== undefined && last.isLiteral === isLiteral) {
41 last.text += text
42 } else {
43 parts.push({ text, isLiteral })
44 }
45 }
46 const end = () => {
47 if (isInWord) tokens.push({ parts })
48 parts = []
49 isInWord = false
50 }
51
52 let i = 0
53 while (i < command.length) {
54 const char = command[i] as string
55 const operator = OPERATORS.find(op => command.startsWith(op, i))
56 if (char === ' ' || char === '\t') {
57 end()
58 i += 1
59 } else if (operator !== undefined) {
60 end()
61 tokens.push({ operator })
62 i += operator.length
63 } else if (char === '#' && !isInWord) {
64 while (i < command.length && command[i] !== '\n') i += 1
65 } else if (char === "'") {
66 const close = command.indexOf("'", i + 1)
67 const stop = close === -1 ? command.length : close
68 add(command.slice(i + 1, stop), true)
69 i = stop + 1
70 } else if (char === '"') {
71 i += 1
72 while (i < command.length && command[i] !== '"') {
73 const inner = command[i] as string
74 const next = command[i + 1]
75 if (inner === '\\' && next !== undefined && '"\\$`'.includes(next)) {
76 add(next, true)
77 i += 2
78 } else {
79 add(inner, false)
80 i += 1
81 }
82 }
83 if (!isInWord) add('', true)
84 i += 1
85 } else if (char === '\\') {
86 const next = command[i + 1]
87 if (next !== undefined && next !== '\n') add(next, true)
88 i += 2
89 } else {
90 add(char, false)
91 i += 1
92 }
93 }
94 end()
95
96 return tokens
97}
98
99const VARIABLE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g
100
101/**
102 * Expands a word the way the shell would for a path: a leading `~` and
103 * `$NAME` or `${NAME}` outside single quotes. Undefined when the word holds
104 * something only the running shell knows, such as an unset variable or a
105 * command substitution.
106 */
107export function expand(parts: readonly Part[], env: Env): string | undefined {
108 let out = ''
109 for (const [index, part] of parts.entries()) {
110 if (part.isLiteral) {
111 out += part.text
112 continue
113 }
114 let text = part.text
115 if (text.includes('$(') || text.includes('`')) return undefined
116 if (index === 0 && (text === '~' || text.startsWith('~/'))) {
117 const home = env('HOME')
118 if (home === undefined) return undefined
119 text = home + text.slice(1)
120 }
121 let isKnown = true
122 text = text.replace(VARIABLE, (_, braced: string | undefined, bare: string | undefined) => {
123 const value = env(braced ?? bare ?? '')
124 if (value === undefined) isKnown = false
125 return value ?? ''
126 })
127 if (!isKnown || text.includes('$')) return undefined
128 out += text
129 }
130 return out
131}
132
133const raw = (parts: readonly Part[]) => parts.map(part => part.text).join('')
134
135const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)=/
136
137/**
138 * Finds each `watch-prs.sh` or `watch-threads.sh` invocation in a command
139 * line and the `--tracked` path given to it. A variable the command assigns
140 * before the watcher, as in `D=~/loops; watch-prs.sh --tracked $D/tracked`,
141 * expands ahead of the environment.
142 */
143export function findWatchers(command: string, env: Env): Watcher[] {
144 const tokens = tokenize(command)
145 const found: Watcher[] = []
146 const assigned = new Map<string, string | undefined>()
147 const lookup: Env = name => (assigned.has(name) ? assigned.get(name) : env(name))
148 let isCommandStart = true
149
150 for (const [index, token] of tokens.entries()) {
151 if (!('parts' in token)) {
152 isCommandStart = true
153 continue
154 }
155 const [first, ...rest] = token.parts
156 const assignment =
157 isCommandStart && first !== undefined && !first.isLiteral ? ASSIGNMENT.exec(first.text) : null
158 if (assignment !== null && first !== undefined) {
159 const [written, name] = assignment as unknown as [string, string]
160 assigned.set(name, expand([{ ...first, text: first.text.slice(written.length) }, ...rest], lookup))
161 continue
162 }
163 if (isCommandStart && raw(token.parts) === 'export') continue
164 isCommandStart = false
165
166 const name = raw(token.parts).split('/').pop() ?? ''
167 const kind = SCRIPTS[name]
168 if (kind === undefined) continue
169
170 for (let at = index + 1; at < tokens.length; at += 1) {
171 const arg = tokens[at] as Token
172 if (!('parts' in arg)) break
173 const text = raw(arg.parts)
174 if (text === '--tracked') {
175 const value = tokens[at + 1]
176 if (value === undefined || !('parts' in value)) break
177 found.push({ kind, tracked: expand(value.parts, lookup), written: raw(value.parts) })
178 break
179 }
180 if (text.startsWith('--tracked=')) {
181 const [first, ...rest] = arg.parts
182 if (first === undefined) break
183 const value = [{ ...first, text: first.text.slice('--tracked='.length) }, ...rest]
184 found.push({ kind, tracked: expand(value, lookup), written: raw(value) })
185 break
186 }
187 }
188 }
189
190 return found
191}
192
193const ENTRY = /^(!?)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#([1-9][0-9]*)$/
194
195/** Names a pull request without regard to case, as GitHub and the watchers do. */
196export const keyOf = (pr: TrackedPr) => `${pr.repo}#${pr.number}`.toLowerCase()
197
198/**
199 * Reads a tracked file: one `owner/repo#number` per line, where a line
200 * `!owner/repo#number` keeps that pull request out. Lines of any other
201 * shape are skipped; the watcher reports them itself.
202 */
203export function parseTracked(text: string): TrackedPr[] {
204 const kept = new Map<string, TrackedPr>()
205 const excluded = new Set<string>()
206
207 for (const line of text.split('\n')) {
208 const match = ENTRY.exec(line.trim())
209 if (match === null) continue
210 const [, bang, repo, number] = match as unknown as [string, string, string, string]
211 const pr = { repo, number: Number(number) }
212 const key = keyOf(pr)
213 if (bang === '!') {
214 excluded.add(key)
215 } else if (!kept.has(key)) {
216 kept.set(key, pr)
217 }
218 }
219
220 return [...kept.entries()]
221 .filter(([key]) => !excluded.has(key))
222 .map(([, pr]) => pr)
223}
224hooks/inbox.ts 437 lines1import type { AgentInfo, FsEntry } from 'claude-code'
2
3import type { Item, Question } from './types'
4import type { Env } from './parse'
5
6/** How long a delivered item stays in the panel. */
7export const RESOLVED_MS = 30_000
8
9/** How long a claim lasts without renewal, as `project inbox claim` counts it. */
10export const CLAIM_MS = 60_000
11
12const LIVE: ReadonlySet<AgentInfo['status']> = new Set(['pending', 'running', 'waiting', 'idle'])
13
14export const letterAt = (index: number) => String.fromCharCode('a'.charCodeAt(0) + index)
15
16/** The letter of a typed answer: the one after the last choice. */
17export const typedLetter = (question: Question) => letterAt(question.choices.length)
18
19/** Whether an item is snoozed at a time: put off until its `snoozedUntil`. */
20export const isSnoozedAt = (item: Item, time: number) => item.snoozedUntil !== undefined && time < item.snoozedUntil
21
22/** Whether the agent that posted an item withdrew it. */
23const isWithdrawn = (item: Item) => item.answer !== undefined && 'withdrawn' in item.answer
24
25/**
26 * Whether the panel shows an item: not withdrawn, not snoozed or snoozed
27 * within the last 30 seconds, and open, being delivered, or delivered within
28 * the last 30 seconds.
29 */
30export const isShownAt = (item: Item, time: number) =>
31 !isWithdrawn(item) &&
32 (!isSnoozedAt(item, time) || (item.snoozedAt !== undefined && time - item.snoozedAt < RESOLVED_MS)) &&
33 (item.deliveredAt === undefined || time - item.deliveredAt < RESOLVED_MS)
34
35/** The open items whose snooze ended after `since` and by `time`, which bring a hidden panel back. */
36export const wokeBetween = (items: readonly Item[], since: number, time: number) =>
37 items.filter(
38 item =>
39 item.answer === undefined && item.snoozedUntil !== undefined && since < item.snoozedUntil && item.snoozedUntil <= time,
40 )
41
42/**
43 * Whether a question's line waits for a deliverer: an answer recorded and
44 * undelivered, or word of a restore, and claimed by none that is live.
45 */
46export const needsDelivery = (item: Item, time: number): item is Question =>
47 item.kind === 'question' &&
48 (item.restoredAt !== undefined || (item.answer !== undefined && item.deliveredAt === undefined)) &&
49 (item.claim === undefined || time - item.claim.renewedAt >= CLAIM_MS)
50
51/** What the panel puts in the prompt to discuss an item: its subject, in quotes. */
52export const quoteOf = (item: Item) => `"${item.subject}"`
53
54/** What the panel puts in the prompt for an answer: the quoted question, a blank line, and the answer's text. */
55export const proposalOf = (question: Question, answer: string) => `${quoteOf(question)}\n\n${answer}`
56
57/** One answer a sent prompt gives: the letter of the option it picks. */
58export type Given = { question: Question; letter: string }
59
60/**
61 * What a question's drawer put in the prompt: the question's quote as it read
62 * then, and the option chosen, or an empty answer for discuss. `isStale`
63 * marks one put there before the question was revised.
64 */
65export type Proposal = { ref: string; quote: string; answer: string; isStale?: boolean }
66
67/** What a sent prompt says to the open questions: the answers it gives, and the questions it replies to. */
68export type Read = { answers: Given[]; replies: Question[] }
69
70/**
71 * Reads a sent prompt as the panel writes it, each quote speaking to one
72 * question. A quoted open question takes an answer only when its quote ends
73 * its line and the text after it, up to the next quoted item or the prompt's
74 * end, is one of its options, whatever blank lines and spaces surround it:
75 * what pressing an option puts in the prompt. A quote that a drawer put in
76 * the prompt, with that answer or alone through discuss, speaks to the
77 * question of the drawer that did so last, `proposed` holding them oldest
78 * first: one of its options answers it, and any other text replies to it.
79 * A drawer's pick from before
80 * its question was revised only replies, and one whose question was resolved
81 * before the prompt was sent does nothing, so a drawer's pick never falls
82 * through to another question with the same words.
83 * A quote no drawer put there goes to the oldest question with that text that
84 * offers the option, and otherwise replies to the one whose drawer last put
85 * that quote in the prompt, or else to the oldest with that text. Only
86 * questions take answers and replies, snoozed ones included.
87 */
88export function readPrompt(text: string, items: readonly Item[], proposed: readonly Proposal[] = []): Read {
89 const open = items
90 .filter((item): item is Question => item.kind === 'question' && item.answer === undefined)
91 .sort((one, other) => one.postedAt - other.postedAt)
92 const quotes = [...new Set([...items.map(quoteOf), ...proposed.map(one => one.quote)])]
93 .flatMap(quote => {
94 const found: { at: number; end: number; quote: string }[] = []
95 for (let at = text.indexOf(quote); at !== -1; at = text.indexOf(quote, at + 1)) {
96 found.push({ at, end: at + quote.length, quote })
97 }
98 return found
99 })
100 .sort((one, other) => one.at - other.at)
101 const answers: Given[] = []
102 const answered = new Set<string>()
103 const replied = new Set<string>()
104 const isOpen = (ref: string) => open.some(question => question.ref === ref) && !answered.has(ref)
105 const isFree = (ref: string) => isOpen(ref) && !replied.has(ref)
106 const answer = (question: Question, said: string) => {
107 answered.add(question.ref)
108 answers.push({ question, letter: letterAt(question.choices.indexOf(said)) })
109 }
110 for (const { end, quote } of quotes) {
111 const after = text.slice(end, quotes.find(next => next.at >= end)?.at)
112 const said = /^[ \t]*\n/.test(after) ? after.trim() : undefined
113 // The drawer that put this text in the prompt: the last to put this
114 // quote there with this answer or alone, through discuss, leaving out a
115 // question an earlier quote in this prompt answered.
116 const source = proposed.findLast(
117 one => one.quote === quote && (one.answer === said || one.answer === '') && !answered.has(one.ref),
118 )
119 if (source !== undefined) {
120 // A question resolved since its drawer put the quote there takes
121 // nothing, and the quote falls through to no other question.
122 const question = open.find(one => one.ref === source.ref)
123 if (question === undefined) continue
124 if (source.isStale !== true && said !== undefined && question.choices.includes(said)) {
125 answer(question, said)
126 } else if (isFree(source.ref)) {
127 replied.add(source.ref)
128 }
129 continue
130 }
131 const offering = open.filter(
132 question =>
133 quoteOf(question) === quote && isOpen(question.ref) && said !== undefined && question.choices.includes(said),
134 )
135 if (offering[0] !== undefined && said !== undefined) {
136 answer(offering[0], said)
137 continue
138 }
139 const intended = proposed.findLast(one => one.quote === quote && isFree(one.ref))
140 const replying = intended?.ref ?? open.find(one => quoteOf(one) === quote && isFree(one.ref))?.ref
141 if (replying !== undefined) replied.add(replying)
142 }
143 return { answers, replies: open.filter(question => replied.has(question.ref) && !answered.has(question.ref)) }
144}
145
146/** Names the subagent that asked, by its description and id when the session still lists it. */
147function whoAsked(question: Question, agents: readonly AgentInfo[]): string {
148 const agent = agents.find(one => one.id === question.agentId)
149 return agent === undefined ? (question.agentId ?? '') : `${agent.description} (${agent.id})`
150}
151
152/** What the main loop reads beside a prompt that answers a subagent's question: whom to send it to. */
153export const relayNote = (question: Question, agents: readonly AgentInfo[]) =>
154 `The subagent ${whoAsked(question, agents)} asked ${quoteOf(question)}; send it the answer this prompt gives.`
155
156/** What the main loop reads beside a prompt that replies to a subagent's question: whom to send the reply to. */
157export const replyNote = (question: Question, agents: readonly AgentInfo[]) =>
158 `The subagent ${whoAsked(question, agents)} asked ${quoteOf(question)}; send it the reply this prompt gives, which leaves the question open.`
159
160/** The subagent that asked, while it can still read a message; undefined sends the answer to the main loop. */
161export function liveAgent(question: Question, agents: readonly AgentInfo[]): string | undefined {
162 const agent = agents.find(one => one.id === question.agentId)
163 return agent !== undefined && LIVE.has(agent.status) ? agent.id : undefined
164}
165
166/** What the main loop receives: the answer, and the subagent to relay it to when one asked. */
167export function forMainLoop(text: string, question: Question, agents: readonly AgentInfo[]): string {
168 if (question.agentId === undefined) return text
169 return `${text}\n\nThe subagent ${whoAsked(question, agents)} asked this, and the answer could not reach it; send it this answer, or act on it yourself.`
170}
171
172/** Where a session's items live: `project inbox`'s store, found by the CLI's own rule. */
173export function storeOf(env: Env, session: string): string | undefined {
174 const home = env('HOME')
175 const base = env('XDG_STATE_HOME') ?? (home === undefined ? undefined : `${home}/.local/state`)
176 return base === undefined ? undefined : `${base}/projector/inbox/${session}`
177}
178
179/**
180 * What the store's directory holds: each item file's name, size and
181 * time, leaving out the lock and any file being written. A file whose claim
182 * the panel itself renews counts by name alone, so the panel's own renewal
183 * never makes it read the store again.
184 */
185export function signatureOf(entries: readonly FsEntry[], renewing: ReadonlySet<string>): string {
186 return entries
187 .filter(entry => entry.kind === 'file' && !entry.name.startsWith('.'))
188 .map(entry => (renewing.has(refOf(entry.name)) ? entry.name : `${entry.name} ${entry.size} ${entry.mtimeMs}`))
189 .sort()
190 .join('\n')
191}
192
193/** The reference an item file is named for, the CLI having quoted it; empty for any other file. */
194function refOf(name: string): string {
195 if (!name.endsWith('.json')) return ''
196 try {
197 return decodeURIComponent(name.slice(0, -'.json'.length))
198 } catch {
199 return ''
200 }
201}
202
203/** A short age: `40s`, `5m`, `2h`, `3d`. */
204export const span = (seconds: number) =>
205 seconds < 60 ? `${seconds}s` : seconds < 3600 ? `${Math.floor(seconds / 60)}m`
206 : seconds < 86_400 ? `${Math.floor(seconds / 3600)}h` : `${Math.floor(seconds / 86_400)}d`
207
208const UNSEEN_NUMBER =
209 'The panel never shows an item’s number, so name the item to the person by what it asks or tells, never by its number.'
210
211/** A tool's description: its own lines, then the sentence every inbox tool ends with about an item's number. */
212const described = (lines: readonly string[]) => [...lines, UNSEEN_NUMBER].join(' ')
213
214export const ASK_DESCRIPTION = described([
215 'Ask the person a question without stopping: it appears in Projector’s panel above their prompt, and you keep working.',
216 'Ask in one short line of at most 120 characters, and put what they need to decide in `detail`.',
217 'Always recommend an answer, and write it and each option as a full answer they can pick as it stands.',
218 'Name the pull request the question is about in `pr`, as owner/repo#number.',
219 'Keep working on anything the answer does not block. The call returns the question’s number, such as 3.',
220 'When the person picks an option, a message that starts `ANSWER 3.<letter>` arrives later, or `DISMISSED 3` when they dismiss it.',
221 'When they restore a question after you heard `DISMISSED 3`, `RESTORED 3` arrives, and the question is open again.',
222 'When they reply in their own words instead, the reply arrives as their prompt, quoting the question, and the question stays open:',
223 'answer what they asked, then withdraw the question if the reply settles it, revise it if it was unclear or the choice has changed,',
224 'or leave it open while it still needs them.',
225])
226
227export const ASK_SCHEMA = {
228 type: 'object',
229 properties: {
230 question: { type: 'string', description: 'The question, in one line of at most 120 characters.' },
231 recommendation: { type: 'string', description: 'The answer you recommend, written in full; it is answer a.' },
232 options: {
233 type: 'array',
234 items: { type: 'string' },
235 maxItems: 5,
236 description: 'Up to five other answers, each written in full, lettered b, c, and on in this order.',
237 },
238 detail: {
239 type: 'string',
240 description: 'What the person needs to decide, as Markdown; leave it out when the question says it all.',
241 },
242 pr: { type: 'string', description: 'The pull request the question is about, as owner/repo#number.' },
243 },
244 required: ['question', 'recommendation'],
245 additionalProperties: false,
246}
247
248const isText = (value: unknown): value is string => typeof value === 'string'
249
250/**
251 * The arguments of `project inbox ask` for one call of the tool, or why
252 * the call cannot be one. Each value rides in its flag's `=` form and the
253 * question after `--`, so text that starts with `-` stays text.
254 */
255export function askArguments(
256 input: Readonly<Record<string, unknown>>,
257 session: string,
258 agentId: string | undefined,
259): string[] | { error: string } {
260 const { question, recommendation, options = [], detail, pr } = input
261 if (!isText(question)) return { error: '`question` must be a string' }
262 if (!isText(recommendation)) return { error: '`recommendation` must be a string' }
263 if (!Array.isArray(options) || !options.every(isText)) return { error: '`options` must be a list of strings' }
264 if (detail !== undefined && !isText(detail)) return { error: '`detail` must be a string' }
265 if (pr !== undefined && !isText(pr)) return { error: '`pr` must be a string such as owner/repo#123' }
266 return [
267 'inbox',
268 'ask',
269 `--session=${session}`,
270 `--recommend=${recommendation}`,
271 ...options.map(option => `--option=${option}`),
272 ...postedFlags(detail, pr, agentId),
273 '--',
274 question,
275 ]
276}
277
278export const TELL_DESCRIPTION = described([
279 'Tell the person something without stopping: it appears in Projector’s panel above their prompt until they dismiss it.',
280 'Use it for the answer to a question they asked you, or for something you did that they should know about.',
281 'Write one short line of at most 120 characters, and put the rest in `detail`.',
282 'Name the pull request it is about in `pr`, as owner/repo#number.',
283 'Nothing comes back to you; when you need the person to decide something, use `ask` instead.',
284])
285
286export const TELL_SCHEMA = {
287 type: 'object',
288 properties: {
289 notice: { type: 'string', description: 'What to tell the person, in one line of at most 120 characters.' },
290 detail: {
291 type: 'string',
292 description: 'The rest of what they should read, as Markdown; leave it out when the line says it all.',
293 },
294 pr: { type: 'string', description: 'The pull request the notice is about, as owner/repo#number.' },
295 },
296 required: ['notice'],
297 additionalProperties: false,
298}
299
300/** The arguments of `project inbox tell` for one call of the tool, or why the call cannot be one. */
301export function tellArguments(
302 input: Readonly<Record<string, unknown>>,
303 session: string,
304 agentId: string | undefined,
305): string[] | { error: string } {
306 const { notice, detail, pr } = input
307 if (!isText(notice)) return { error: '`notice` must be a string' }
308 if (detail !== undefined && !isText(detail)) return { error: '`detail` must be a string' }
309 if (pr !== undefined && !isText(pr)) return { error: '`pr` must be a string such as owner/repo#123' }
310 return ['inbox', 'tell', `--session=${session}`, ...postedFlags(detail, pr, agentId), '--', notice]
311}
312
313export const WITHDRAW_DESCRIPTION = described([
314 'Withdraw a question or notice you posted that no longer needs the person,',
315 'such as a question their reply settled or news that has gone stale.',
316 'Name it by the number `ask` or `tell` returned. It leaves Projector’s panel at once.',
317 'Nothing comes back to you: a withdrawn question sends no `DISMISSED` message.',
318])
319
320/** The schema of a tool that takes one item, by the number `ask` or `tell` returned. */
321const ITEM_SCHEMA = {
322 type: 'object',
323 properties: {
324 number: {
325 type: 'integer',
326 minimum: 1,
327 description: 'The item’s number, as `ask` or `tell` returned it, such as 3.',
328 },
329 },
330 required: ['number'],
331 additionalProperties: false,
332}
333
334export const WITHDRAW_SCHEMA = ITEM_SCHEMA
335
336/** Whether a tool's `number` names an item: a whole number from 1. */
337const isNumber = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value) && value >= 1
338
339/** The arguments of a `project inbox` command on one item for one call of its tool, or why the call cannot be one. */
340const itemArguments =
341 (command: 'withdraw' | 'restore') =>
342 (input: Readonly<Record<string, unknown>>, session: string): string[] | { error: string } => {
343 const { number } = input
344 if (!isNumber(number)) return { error: '`number` must be the whole number `ask` or `tell` returned, such as 3' }
345 return ['inbox', command, String(number), '--session', session, '--json']
346 }
347
348/** The arguments of `project inbox withdraw` for one call of the tool, or why the call cannot be one. */
349export const withdrawArguments = itemArguments('withdraw')
350
351export const RESTORE_DESCRIPTION = described([
352 'Restore a question or notice you posted that the person dismissed or snoozed: it reopens in Projector’s panel',
353 'under the same number, with the same text. Use it only when the person says a dismissal was a mistake or asks',
354 'for the item back, never on your own judgement, and never ask a dismissed question again as a new one.',
355 'Name it by the number `ask` or `tell` returned. A restored question’s answer arrives as before, as a message',
356 'that starts `ANSWER 3.<letter>` or `DISMISSED 3`.',
357])
358
359export const RESTORE_SCHEMA = ITEM_SCHEMA
360
361/** The arguments of `project inbox restore` for one call of the tool, or why the call cannot be one. */
362export const restoreArguments = itemArguments('restore')
363
364export const REVISE_DESCRIPTION = described([
365 'Revise a question you asked that is still open, keeping its number, when the person’s reply shows it was unclear',
366 'or the choice has changed. Name it by the number `ask` returned, and give only what changes:',
367 'the question, its detail, the recommendation, or the other options, which `options` replaces as a whole.',
368 'Projector’s panel redraws it at once, and its answer still arrives as a message that starts',
369 '`ANSWER 3.<letter>` or `DISMISSED 3`.',
370])
371
372export const REVISE_SCHEMA = {
373 type: 'object',
374 properties: {
375 number: { type: 'integer', minimum: 1, description: 'The question’s number, as `ask` returned it, such as 3.' },
376 question: { type: 'string', description: 'The new question, in one line of at most 120 characters.' },
377 recommendation: {
378 type: 'string',
379 description: 'The new answer you recommend, written in full; it is answer a.',
380 },
381 options: {
382 type: 'array',
383 items: { type: 'string' },
384 maxItems: 5,
385 description:
386 'Every other answer, up to five, each written in full and lettered b, c, and on in this order; an empty list leaves only the recommendation.',
387 },
388 detail: {
389 type: 'string',
390 description: 'The new detail, as Markdown; an empty string clears it.',
391 },
392 },
393 required: ['number'],
394 additionalProperties: false,
395}
396
397/**
398 * The arguments of `project inbox revise` for one call of the tool, or why
399 * the call cannot be one. Each value rides in its flag's `=` form, so text
400 * that starts with `-` stays text, and an empty `detail` clears the detail.
401 */
402export function reviseArguments(
403 input: Readonly<Record<string, unknown>>,
404 session: string,
405): string[] | { error: string } {
406 const { number, question, recommendation, options, detail } = input
407 if (!isNumber(number)) return { error: '`number` must be the whole number `ask` returned, such as 3' }
408 if (question !== undefined && !isText(question)) return { error: '`question` must be a string' }
409 if (recommendation !== undefined && !isText(recommendation)) return { error: '`recommendation` must be a string' }
410 if (options !== undefined && (!Array.isArray(options) || !options.every(isText))) {
411 return { error: '`options` must be a list of strings' }
412 }
413 if (detail !== undefined && !isText(detail)) return { error: '`detail` must be a string' }
414 if ([question, recommendation, options, detail].every(value => value === undefined)) {
415 return { error: 'give what changes: `question`, `detail`, `recommendation`, or `options`' }
416 }
417 return [
418 'inbox',
419 'revise',
420 String(number),
421 '--session',
422 session,
423 ...(question === undefined ? [] : [`--question=${question}`]),
424 ...(recommendation === undefined ? [] : [`--recommend=${recommendation}`]),
425 ...(options === undefined ? [] : options.length === 0 ? ['--no-options'] : options.map(option => `--option=${option}`)),
426 ...(detail === undefined ? [] : [`--detail=${detail}`]),
427 '--json',
428 ]
429}
430
431/** The flags both posting tools pass when they have a value: the detail, the pull request, and the subagent. */
432const postedFlags = (detail: string | undefined, pr: string | undefined, agentId: string | undefined) => [
433 ...(detail === undefined || detail === '' ? [] : [`--detail=${detail}`]),
434 ...(pr === undefined || pr === '' ? [] : [`--pr=${pr}`]),
435 ...(agentId === undefined ? [] : [`--agent=${agentId}`]),
436]
437hooks/types.d.ts 153 lines1/** What a loop does with its pull requests: `watch-threads.sh` watches, `watch-prs.sh` reviews. */
2export type LoopKind = 'watching' | 'reviewing'
3
4/** A tracked file this session started a watcher on. */
5export type SeenLoop = { kind: LoopKind; tracked: string }
6
7export type Checks = 'passing' | 'failing' | 'pending'
8
9/** A review thread no one has resolved, as a pull request's drawer lists it. */
10export type Thread = {
11 path: string
12 /** The line the thread is on, or was on once its line changed; null for a comment on the whole file. */
13 line: number | null
14 /** Whether a later push changed the lines the thread is on, which GitHub then folds away. */
15 isOutdated: boolean
16 /** Who opened the thread; null when GitHub did not say. */
17 author: string | null
18 /** The first line of the thread's first comment, as plain text. */
19 excerpt: string
20 /** The thread's first comment on GitHub; null when GitHub did not say. */
21 url: string | null
22}
23
24export type PullRequest = {
25 repo: string
26 number: number
27 title: string
28 url: string
29 state: 'OPEN' | 'MERGED' | 'CLOSED'
30 isDraft: boolean
31 reviewDecision: 'APPROVED' | 'CHANGES_REQUESTED' | 'REVIEW_REQUIRED' | null
32 isConflicting: boolean
33 openThreads: number
34 author: string | null
35 branch: string
36 additions: number
37 deletions: number
38 changedFiles: number
39 /** The head commit's combined check state; null when it has no checks. */
40 checks: Checks | null
41 /** When the pull request last changed, in milliseconds; null when GitHub did not say. */
42 updatedAt: number | null
43 /** The Projector summary the description links, when one was published. */
44 summaryUrl: string | null
45}
46
47/** One line of the panel: an open pull request and what the loops do with it. */
48export type Row = { pr: PullRequest; kinds: LoopKind[] }
49
50export type Snapshot = {
51 rows: Row[]
52 /** The login of the account the panel's `gh` is signed in as; null until GitHub says. */
53 viewer: string | null
54 fetchedAt: number | null
55 error: string | null
56}
57
58/** A dismissal, `withdrawn` when the agent that posted the item took it back. */
59export type Dismissal = { dismissed: true; withdrawn?: true; answeredAt: number }
60
61/** How an item was resolved: dismissed, or a question answered with a lettered choice or typed text. */
62export type Answer = { letter: string; text: string; answeredAt: number } | Dismissal
63
64/** What every item has, as `project inbox list --json` gives it, with the session whose store holds it. */
65export type Posted = {
66 /** The item's number in its session, as a string such as `"3"`: what the CLI prints and takes. */
67 ref: string
68 number: number
69 /** The pull request it is about, as `owner/repo#number`; null when none. */
70 pr: string | null
71 /** When the agent posted it, in milliseconds. */
72 postedAt: number
73 /** The question or the notice, in one line. */
74 subject: string
75 detail: string
76 /** The subagent that posted it. */
77 agentId?: string
78 /** When a snoozed item returns, in milliseconds; absent when it is not snoozed. */
79 snoozedUntil?: number
80 /** When the item was last snoozed, in milliseconds; absent when it is not snoozed. */
81 snoozedAt?: number
82 deliveredAt?: number
83 session: string
84}
85
86/** A question, whose answer or dismissal goes back to the agent that asked. */
87export type Question = Posted & {
88 kind: 'question'
89 /** The answers in letter order, the recommendation first; the letter after the last is a typed answer. */
90 choices: string[]
91 answer?: Answer
92 claim?: { token: string; renewedAt: number }
93 /** When the person restored the question after its agent may have heard `DISMISSED`, until `RESTORED` is delivered. */
94 restoredAt?: number
95}
96
97/** A notice, which you read and dismiss, and which sends nothing back; dismissing it delivers it. */
98export type Notice = Posted & {
99 kind: 'notice'
100 answer?: Dismissal
101}
102
103export type Item = Question | Notice
104
105/**
106 * An answer the panel claimed and is delivering: the claim's token, the route
107 * it took, and the text sent, so a later copy of the module keeps renewing
108 * the claim and knows the prompt when it arrives.
109 */
110export type Sending = {
111 ref: string
112 session: string
113 token: string
114 route: 'send' | 'submit'
115 text: string
116}
117
118declare module 'claude-code' {
119 interface PluginState {
120 projector: {
121 seenLoops: SeenLoop[]
122 panelSnapshot: Snapshot
123 panelNow: number
124 isPanelShown: boolean
125 /** The drawer that is open: a pull request's by `keyOf`, or `item:` and an item's reference. */
126 panelDrawer: string | null
127 /**
128 * What an open drawer asks before it acts, in its actions' place: how
129 * long to snooze, or whether to dismiss. `drawer` is the key
130 * `panelDrawer` holds.
131 */
132 panelAsked: { drawer: string; about: 'snooze' | 'dismiss' } | null
133 /**
134 * The unresolved threads of the pull request whose drawer is open, as
135 * GitHub last gave them. `drawer` is the key `panelDrawer` holds.
136 */
137 panelThreads: { drawer: string; threads: Thread[] } | null
138 /** The session's inbox, as the panel last read it. */
139 panelInbox: Item[]
140 /** The answers the panel is delivering, by reference. */
141 panelSending: Record<string, Sending>
142 /** What the release before the rename kept as `panelSending`, which the panel takes over. */
143 bandSending: Record<string, Sending>
144 /** The panel's background for the session's Claude Code theme, which `panel.background = "auto"` takes. */
145 panelThemeBackground: string
146 /** `panel.background` as the panel last read it: `auto`, or the color it draws for the value. */
147 panelBackground: string
148 /** Whether the panel took the keyboard since the last keystroke in the prompt, so its hint names its own keys. */
149 isPanelFocused: boolean
150 }
151 }
152}
153