Draws the agentic-workflows engine's gates in the band above the prompt — rows a click puts in the prompt and a second click sends — instead of a menu the…

A Claude Code mod that draws the workflow engine's gates in the band above the prompt instead of leaving the model to reproduce them.
The engine states each gate as data beside the menu it composed. This mod announces itself at the session's start so the engine collects that data, arms the gate off the Bash result that carried it, cuts the menu out of what the model reads, and draws the rows where they stay put while the transcript scrolls; while any screen but the terminal or the Desktop app is attached beside it, it leaves the menu as text so every screen shows it, though a screen that attaches after a menu was drawn does not get that menu. No gate's prose names the mod; only workflow-start's setup step does, with a notice when the mod could run in Claude Code's terminal app or the Desktop app's Code tab but is not running.
A click on a row puts its answer in the prompt box; a second click on it sends it as the next message, which the workflows read as the answer. Once a click has given the band the keyboard, the arrows move between rows, Enter or a row's own key picks, and Enter on the picked row sends. A sent answer enters under the plugin's name, framed for the model and labelled in the transcript as the plugin's; the mod leaves what it sent in the conversation's own folder (see below) as sent.json. A second plugin, workflow-gates-rows (../workflow-gates-rows/), reads that record to draw the row as the question and the answer, since no plugin can redraw the row of a prompt it submitted. Typing answers too: a key and Enter at the prompt, or Esc then Enter after a pick. Rows only typing can answer — Ask, Comment, a range — draw dim, and a click on one says to type it in the prompt. The footer under the rows says which: how to answer, what is in the prompt, or where to type.
The band is never taller than the rows Claude Code gives it, so it never scrolls. A gate that fits shows whole: a rule, the statement and the question, the rows, the footer. One that does not keeps its rule, question and footer in place and shows its rows a page at a time, every page the same height, over a line reading ↑ previous ↓ next page 1 of 3; a click on either turns the page and puts the cursor on its first row. The arrows carry the cursor across pages, the page following it, and a row's own key picks that row whichever page it is on.
A turn the person did not start — a background agent's report, a notification, a schedule — leaves the band as it is, its rows live. The band comes off when the person starts a turn or replies into a running one, or when a turn draws a different gate over it. Esc on such a turn leaves the band as it is, unless the turn had already rendered a different gate: the model now waits at that gate's stop, so the band empties. A second click while Claude works holds the answer instead of sending it: its row reads · queued, and the footer says it sends when Claude finishes. A click on the queued row takes it back to a pick, and a click on another row picks that one instead. As the turn ends, the held answer sends if the same gate is still on the band; if the turn rendered a different gate, the answer is dropped unsent, and the new gate's footer says so; if Esc stopped the turn with the same gate still up, the answer goes back into the prompt box as a pick. When a pick's gate goes, its answer leaves the prompt box too, unless the person has edited it there. Typing while Claude works joins Claude Code's own queue.
Esc on a turn an answer started or joined puts its gate back, dropping whatever that turn drew, as long as no tool has run in it; once one has, the band stays empty, since the mod cannot tell a read from a write. A /clear takes the gate off the band.
At the end of every turn, and as the conversation ends, the mod keeps what the band shows — the gate, or nothing — in the conversation's own folder, ~/.config/workflows/conversations/{session-id}/gate.json (under WORKFLOWS_CONFIG_DIR where that is set, beside the workflows' system config), found by the session id wherever the session's working directory has moved, and stamped with where the transcript ends, not counting the lines Claude Code writes around an interrupted turn. A conversation resumed with claude --resume or /resume, or picked up again by a restart or a reload of the mod's files, gets its gate back as long as its transcript still ends there, with nothing picked or held — a held answer waits on a turn that does not come back; one that moved on while the mod was not loaded gets nothing. A session the mod was loaded into after it started carries no announcement, so there it keeps and reads back nothing, and a conversation that does not run the workflows has no folder and keeps nothing — nor does one in a process that names neither a home directory nor WORKFLOWS_CONFIG_DIR. The folder holds one gate, and goes once Claude Code has deleted the conversation's transcript, so a kept gate lives as long as its conversation can be resumed, with one exception: a conversation whose end the session-end hook never saw keeps its folder — the session that first installed the hook, which Claude Code picks up only as a session starts, or one that crashed.
The engine emits the menu regardless, so where the mod is off or absent the model reads the text menu the engine wrote.
The mod is part of the workflows, and it runs in Claude Code's terminal app and the Desktop app's Code tab, from 2.1.287, with this directory installed in the project; mods are on by default there, so nothing switches it on. Claude Code loads a plugin as a session starts, so a session already open when the mod was installed or updated loads it in the next one. The mod is the workflows' upgrade layer and the engine's text menus their floor: a /workflow-start that finds the mod not running — a session started before the mod was installed or updated, mods turned off by --safe-mode, --bare, "disableAllHooks": true or an organization's policy, or installed mods switched off remotely by Anthropic — says so and carries on with typed menus; one that runs on a Claude Code older than 2.1.287 stops and says why. Anywhere else — the web, the VS Code extension, a Desktop session that runs in the cloud, another entrypoint, a project without this directory — the workflows carry on with the text menus and say nothing.
The Desktop app runs the session as an SDK host: the session starts drawing nowhere and the app attaches after, so the band reads the screens attached at each Bash call that states a gate, and the person's own message there arrives as the host's (an sdk origin), which the band reads as theirs.
Claude Code can load the mod where it does not run — another entrypoint, or an older Claude Code with function hooks switched on — so at the session's start the mod applies the boot's rules: where CLAUDE_CODE_ENTRYPOINT is none of cli, claude-desktop and claude-desktop-3p, CLAUDE_CODE_REMOTE is set, or the version the session reports is older than 2.1.287 or not a release's (a development build among them), it announces nothing, so it draws, keeps and sets nothing — the menus stay text, and Claude Code runs as it would without it.
The mod also carries the workflows' handoffs: every move into work, which the engine names with engine handoff, starts in a cleared conversation. At the session's start, where it announces the gate surface, the mod announces that it carries handoffs too (WORKFLOWS_HANDOFF=1, a variable of its own, which the engine reads apart from WORKFLOWS_GATE_SURFACE). The engine then answers a handoff with a HANDOFF payload beside the line naming where the work goes: the continuation to send (`Invoke /<skill> <args>.) and that line. The payload on a Bash result of the conversation's own call — never a subagent's — arms the handoff, and every call has it cut from what the model reads; the line and the skill stay. As the turn ends the mod clears the conversation and, in the conversation that follows, leaves what it sends with the line as sent.json in that conversation's folder, then sends the continuation, which Claude acts on there, and shows a toast naming where the work went (Handed off → Planning · auth-flow) for eight seconds. The clear runs from a timer started at the turn's end, whatever else there fails: a mod cannot run a command inside a hook the turn waits on. A send that is dropped or fails goes into the prompt box for Enter instead; where the box will not take it either, the toast holds the continuation for the person to send, and stays longer. A clear that fails sends in place, so the work still goes on. Esc on the turn that handed off carries nothing: Esc means stop. workflow-gates-rows` draws the continuation's transcript row as the line. Where the mod does not announce, the engine says so and the workflows invoke the skill in the same conversation.
Every session in either app, from 2.1.287, starts with Claude Code's SendUserMessage tool switched on (CLAUDE_CODE_PEWTER_OWL_TOOL=true): Claude Code builds its tool list just after the session starts, so that is the only moment the switch counts. The mod keeps the tool behind ToolSearch in every such session, one answer that never changes and so never spends the prompt cache; a plain session's tool list is Claude Code's own.
In a conversation that runs the workflows there, the mod sets CLAUDE_CODE_THINKING_DISPLAY_UPDATES=false, which stops one-line summaries of Claude's thinking printing as if they were output, and CLAUDE_CODE_SILENT_TURN_REMINDER=false, which stops the nudge to say what Claude is doing; project settings cannot set the second. Claude Code reads both per request. Every engine call marks the conversation that made it — a workflow file in its folder, named by the session id Claude Code hands every command — and the mod reads that mark by its own session id after each of the conversation's Bash calls and when it starts, so a command that only mentions the engine marks nothing. What the settings replace, the person's own value or none, is kept in the process's environment (WORKFLOWS_HARNESS_REPLACED), which a reload of the mod's files keeps, and a /clear or a resume puts it back exactly — except the clear a handoff runs, which leads into a workflow conversation by construction and so leaves the workflow values on, the person's own put back as that conversation ends. A marked conversation gets the workflow values back when the mod next follows it, whether claude --resume, a restart or /resume in the same process brings it back. A plain conversation in the same project keeps Claude Code's defaults and the person's own settings: the mod never touches either there.
In a session that announced, in a conversation the engine has marked, on the terminal app and the Desktop app, the spinner keeps Claude Code's animation and ellipsis, its word the phase the conversation works in — Discussing, Specifying, Implementing task 2.3, Shaping in discovery, Roadmapping, Assessing at the baseline — from the position the engine keeps in the conversation's folder (position.json). The drawing alone changes, never what Claude reads. The mod reads the position once for each conversation the spinner draws in, and again after each engine call that moves it (session label, session repair, boot, task start, task complete), never per frame. At a work unit's menu or the start menu it keeps Claude Code's word, and on the Desktop app a step that names itself (Creating notes.md) keeps its words.
In a session that announced, in a conversation the engine has marked, a Write, Edit or NotebookEdit aimed at a manifest the engine keeps — the project's .workflows/manifest.json, or a work unit's .workflows/{work-unit}/manifest.json — is refused with one line telling Claude to write it through the engine's manifest verbs. Where the path leads is what counts: a path relative to the working directory, one from the home directory (~/), .. and a symbolic link are followed — a .workflows/ that is itself a link, and a file elsewhere linked to a manifest, included — and a manifest not written yet is placed by its nearest folder that exists. Any other file under .workflows/, a manifest.json anywhere else, and every write in a plain conversation or a session that did not announce go through. Bash is not guarded.
Claude Code compacts a workflow conversation as it compacts any other — its summary, and the recent messages it keeps as they were, the person's waiting message among them — and the mod appends one message last: the engine's conversation position note. It says the conversation was just compacted and where it is working, the work unit named by its work type, then tells Claude to follow the skill's "Resuming After Context Refresh" steps before anything else — the skill and its framework re-read in full, then the topic's documents, each by its absolute path. Those steps end by carrying on from where the conversation was, as if the break never happened. A /compact starts no turn of its own, so after one the mod sends a short continuation once the command is done — into the prompt box for Enter where the send is dropped — and Claude follows the note without the person typing anything. Words typed after /compact go to Claude Code's summary as they always do.
Claude Code stores the note as an ordinary user row and would draw it as a prompt the person typed. So the mod records every note it hands up in the conversation's folder as compacted.json, each with the place the engine names (fumi › discussion › management-window), and workflow-gates-rows draws the note's row from it as one dim line.
It does so in a session that announced, in a conversation the engine has marked, in its main loop, at a position that names a skill. A subagent's transcript, a plain conversation, a work unit's menu or the start menu, a place no longer open, and an engine that cannot answer all compact as Claude Code does, with nothing appended; so does a compaction Claude Code skips. The compaction Claude Code computes ahead of time passes through untouched, and the compaction that comes reuses it beneath the note.
npm run typecheck:mod # tsc against the declarations Claude Code laid npm run test:mod # claude plugin test
Claude Code lays its own build's API declarations into a mod's .claude-plugin/types/ whenever it loads the mod for development, with a tsconfig.json this mod's own extends; the folder ignores itself. Load the mods once in a session — claude --plugin-dir skills/workflow-gates --plugin-dir skills/workflow-gates-rows — before the first typecheck, and every load lays them afresh for the Claude Code running; a worktree Claude Code creates starts with a copy (.worktreeinclude). test:mod needs none: it runs the suites against the installed Claude Code.
The suites run on Claude Code 2.1.287 or newer, where mods are on by default.
hooks/register.ts 1150 lines1/**
2 * workflow-gates — the agentic-workflows engine's gates drawn above the
3 * prompt instead of printed by the model.
4 *
5 * The engine states each gate as data beside the menu it composed. This
6 * module announces itself so the engine collects it, arms the gate off the
7 * Bash result that carried it, cuts the menu out of what the model reads, and
8 * draws the rows in the band once the model's turn is over. A press picks its
9 * row's answer into the prompt box; a second press on that row sends it as the
10 * next message, which the workflows' prose reads as the answer, or while
11 * Claude works on anything else holds it until Claude finishes. In a session
12 * that announced, what the band shows is kept in the conversation's folder
13 * across a restart, so a conversation resumed where nothing has happened
14 * since shows its gate again.
15 *
16 * Every path up to the cut fails open: the engine emits the menu regardless,
17 * so where the module never loads, or a cut throws or overruns, the model
18 * reads the text menu the engine wrote.
19 *
20 * The module carries the workflows' handoffs too: a move into work the engine
21 * names arms off the Bash result that carried it, cut out of what the model
22 * reads, and once the turn ends the module clears the conversation and sends
23 * the continuation into the new one, an Esc on that turn carrying nothing.
24 *
25 * The module also sets Claude Code's harness for the workflows: every session
26 * gets the SendUserMessage tool, kept behind ToolSearch, and a conversation
27 * the engine has marked as running the workflows goes without Claude's
28 * thinking summarised as output and without the nudge to say what it is
29 * doing, the person's own values of both put back as it ends. A conversation
30 * the engine has not marked keeps them untouched.
31 *
32 * It registers the rest of what the mod does in a workflow conversation as
33 * well: the spinner saying the phase (`spinner.ts`), the guard on direct
34 * manifest edits (`guard.ts`), and the compaction — Claude Code's own, the
35 * engine's note appended last (`compaction.ts`).
36 *
37 * All of it happens in Claude Code's terminal app and the Desktop app's Code
38 * tab alone, from 2.1.287. Elsewhere — the VS Code extension, Claude Code on
39 * the web, an older Claude Code — the session is not announced, and the
40 * module draws, keeps and sets nothing.
41 */
42import type {
43 AgentLoop,
44 EngineInterface,
45 PromptOrigin,
46 Register,
47 RenderSurface,
48 SessionMessage,
49} from 'claude-code'
50
51import { compaction } from './compaction.ts'
52import { MARKER, folderOf as folderNamed } from './folder.ts'
53import { guard } from './guard.ts'
54import {
55 IDLE,
56 NO_SENDS,
57 answerOf,
58 linesOf,
59 type Gate,
60 type Option,
61 type Sends,
62} from './layout.ts'
63import { spinner } from './spinner.ts'
64
65/** The payload's marker and the menu it sits directly above. */
66const GATE_MARKER = '=== GATE ('
67const MENU_MARKER = '=== MENU'
68const SECTION_MARKER = '=== '
69
70/** The marker of a handoff's payload. */
71const HANDOFF_MARKER = '=== HANDOFF ('
72
73/** The `Client`'s key: what `ui.message` matches the board's posts on. */
74const ELEMENT = 'gate'
75
76/**
77 * The file in the conversation's folder where a send leaves what it answered,
78 * for a mod that draws the sent row.
79 */
80const SENT = 'sent.json'
81
82/** The record that claims no send, which that mod draws nothing from. */
83const NOTHING_SENT = 'null'
84
85/**
86 * What a send leaves in the conversation's folder: the answer to a gate, with
87 * the question and the row's label; or a handoff's continuation, with the line
88 * naming where the work went.
89 */
90type Sent =
91 | { answer: string; question: string; label: string }
92 | { answer: string; line: string }
93
94/** A move into work the engine named: the continuation to send, and its line. */
95type Handoff = { text: string; line: string }
96
97/** How long a continuation the mod could not carry stays on screen to send. */
98const UNCARRIED_TOAST_MS = 30_000
99
100/** How long the toast saying where the work went stays up. */
101const HANDED_OFF_TOAST_MS = 8_000
102
103/** The file a conversation's band is kept in for a resume. */
104const KEPT = 'gate.json'
105
106/**
107 * The entrypoints the mod runs under, as the engine's boot reads them:
108 * Claude Code's terminal app, and the Desktop app's Code tab on Anthropic's
109 * API or a third-party provider.
110 */
111const ENTRYPOINTS: ReadonlySet<string> = new Set([
112 'cli',
113 'claude-desktop',
114 'claude-desktop-3p',
115])
116
117/** The surfaces the band draws on: the terminal app's, and the Desktop app's. */
118const BAND_SURFACES: ReadonlySet<RenderSurface> = new Set(['terminal', 'desktop'])
119
120/** The oldest Claude Code the mod runs on, major, minor and patch. */
121const OLDEST = [2, 1, 287]
122
123/** A release's version, as `claude --version` prints it. */
124const RELEASE = /^(\d+)\.(\d+)\.(\d+)$/
125
126const STOP_NOTE =
127 "The options are on screen as buttons. The user's answer arrives as their next message — typed by them, or sent for them by the workflow-gates plugin when they press a row."
128
129/**
130 * What the band holds of the conversation's gates. A turn the person starts
131 * clears all of it but the gate that turn answers; a turn anyone else starts
132 * leaves it as it is; the conversation's end clears all.
133 */
134type Band = {
135 /** The gate a render armed, waiting on the end of its turn. */
136 armed: Gate | null
137 /** The gate on the band, from a turn's end to a turn the person starts. */
138 drawn: Gate | null
139 /** The answer a press put in the prompt box: a press on its row sends it. */
140 picked: string | null
141 /** The answer held to send when Claude finishes, and one a gate dropped. */
142 sends: Sends
143 /**
144 * Whether the submission that opens the next turn is the person's; a turn
145 * no submission opened counts as theirs.
146 */
147 isOpenedByPerson: boolean
148 /** Whose the running turn is, the person's or anyone else's; null idle. */
149 running: 'person' | 'other' | null
150 /** The gate on the band when the person's running turn began. */
151 answering: Gate | null
152 /** Whether the running turn has called a tool. */
153 hasCalledTool: boolean
154}
155
156const emptyBand = (): Band => ({
157 armed: null,
158 drawn: null,
159 picked: null,
160 sends: NO_SENDS,
161 isOpenedByPerson: true,
162 running: null,
163 answering: null,
164 hasCalledTool: false,
165})
166
167/**
168 * What a turn's end leaves for the prompt box: a held answer's row, sent now
169 * or handed back as a pick; and the text of a pick whose gate went, which
170 * the box may still hold.
171 */
172type Settled = {
173 held: { option: Option; isToSend: boolean } | null
174 gone: string | null
175}
176
177const NOTHING_SETTLED: Settled = { held: null, gone: null }
178
179/** Whether two gates state the same question over the same rows. */
180const isSameGate = (gate: Gate | null, other: Gate | null) =>
181 JSON.stringify(gate) === JSON.stringify(other)
182
183/**
184 * The gate a Bash result's stdout states directly above its menu, and that
185 * stdout with the payload taken out, which is this module's input alone:
186 * `text` keeps the menu as the engine wrote it, `cut` puts the instruction to
187 * stop in its place. Null where the stdout states no gate.
188 */
189function gateIn(
190 stdout: string,
191): { gate: Gate; text: string; cut: string } | null {
192 if (!stdout.includes(GATE_MARKER)) {
193 return null
194 }
195
196 const lines = stdout.split('\n')
197 const at = lines.findIndex(line => line.startsWith(GATE_MARKER))
198
199 if (at === -1) {
200 return null
201 }
202
203 const payload = lines[at + 1]
204 const menu = lines[at + 2]
205
206 if (payload === undefined || !(menu ?? '').startsWith(MENU_MARKER)) {
207 return null
208 }
209
210 const { gate: name, ...gate } = JSON.parse(payload) as Gate & { gate: string }
211 const before = lines.slice(0, at)
212 const after = lines.findIndex(
213 (line, n) => n > at + 2 && line.startsWith(SECTION_MARKER),
214 )
215
216 return {
217 gate,
218 text: [...before, ...lines.slice(at + 2)].join('\n'),
219 cut: [
220 ...before,
221 `=== MENU: ${name} (drawn above the prompt — do NOT emit it; stop and wait) ===`,
222 STOP_NOTE,
223 ...(after === -1 ? [''] : lines.slice(after)),
224 ].join('\n'),
225 }
226}
227
228/**
229 * The handoff a Bash result's stdout carries, and that stdout with its
230 * payload taken out; null where it carries none.
231 */
232function handoffIn(stdout: string): { handoff: Handoff; text: string } | null {
233 if (!stdout.includes(HANDOFF_MARKER)) {
234 return null
235 }
236
237 const lines = stdout.split('\n')
238 const at = lines.findIndex(line => line.startsWith(HANDOFF_MARKER))
239 const payload = lines[at + 1]
240
241 if (at === -1 || payload === undefined) {
242 return null
243 }
244
245 const { text, line } = JSON.parse(payload) as Handoff
246
247 return {
248 handoff: { text, line },
249 text: [...lines.slice(0, at), ...lines.slice(at + 2)].join('\n'),
250 }
251}
252
253/**
254 * Whether `version` is a release the mod runs on; one that does not read as
255 * a release, a development build's included, counts as older.
256 */
257function isSupported(version: string): boolean {
258 const release = RELEASE.exec(version)
259
260 if (release === null) {
261 return false
262 }
263
264 for (const [n, oldest] of OLDEST.entries()) {
265 const part = Number(release[n + 1])
266
267 if (part !== oldest) {
268 return part > oldest
269 }
270 }
271
272 return true
273}
274
275/**
276 * Whether the mod applies to the session, read as the engine's boot reads
277 * it: Claude Code's terminal app or the Desktop app's Code tab — one of the
278 * mod's entrypoints, not Claude Code on the web — at a version the mod runs
279 * on. Claude Code loads the mod wherever mods are on — the VS Code
280 * extension's session, or an older Claude Code's with function hooks
281 * switched on — so the check is the mod's own.
282 */
283async function isApplicable($: EngineInterface): Promise<boolean> {
284 if (
285 !ENTRYPOINTS.has((await $.env.get('CLAUDE_CODE_ENTRYPOINT')) ?? '') ||
286 (await $.env.get('CLAUDE_CODE_REMOTE'))
287 ) {
288 return false
289 }
290
291 return isSupported((await $.session.version()).version)
292}
293
294/**
295 * Whether the session announces the gate surface: set at its start, and
296 * still set after a reload of the module. The band is kept and read back,
297 * and the harness put on, only where it is, so a process whose session
298 * never announced — one the mod does not apply to, or one this module was
299 * loaded into after it started — never gets either.
300 */
301async function isAnnounced($: EngineInterface): Promise<boolean> {
302 return (await $.env.get('WORKFLOWS_GATE_SURFACE')) === '1'
303}
304
305/** Whether an event is the conversation's own, not a subagent's loop. */
306const inConversation = (e: AgentLoop) => e.agentId === undefined
307
308/**
309 * Whether the band takes a gate a Bash call stated: the conversation's own
310 * call, not a subagent's; and the session's only screen the terminal or the
311 * Desktop app, since the band is theirs and any other screen attached beside
312 * it shows the menu as text alone. The Desktop app attaches after the
313 * session starts, so this is read at the call.
314 */
315async function isForBand($: EngineInterface, e: AgentLoop): Promise<boolean> {
316 if (!inConversation(e)) {
317 return false
318 }
319
320 const [only, ...others] = await $.session.surfaces()
321
322 return only !== undefined && others.length === 0 && BAND_SURFACES.has(only)
323}
324
325/**
326 * Whether a submission is the person's: their Enter at the prompt, their
327 * message through Remote Control, their message in the Desktop app — whose
328 * Code tab runs the session as an SDK host, so it arrives as the host's own —
329 * or this plugin sending their press. One with no origin is the person's
330 * own, as the engine reads it.
331 */
332const isPersons = (origin: PromptOrigin | undefined, plugin: string) =>
333 origin === undefined ||
334 origin.kind === 'composer' ||
335 origin.kind === 'bridge' ||
336 origin.kind === 'sdk' ||
337 (origin.kind === 'plugin' && origin.name === plugin)
338
339/** The row a post names, or null when it names none of the gate's. */
340function optionIn(gate: Gate, data: unknown): Option | null {
341 const said = (data as { answer?: unknown } | null)?.answer
342
343 return typeof said === 'string'
344 ? (gate.options.find(option => answerOf(option) === said) ?? null)
345 : null
346}
347
348/** Puts `text` in the prompt box in place of what is there; whether it took. */
349async function fill($: EngineInterface, text: string): Promise<boolean> {
350 const { isFilled } = await $.prompt.fill({ text, mode: 'replace' })
351
352 return isFilled
353}
354
355/**
356 * Sends the next message, the send recorded in the conversation's folder
357 * where it has one; whether it entered. A send that fails or is dropped
358 * leaves no send recorded.
359 */
360async function deliver($: EngineInterface, sent: Sent): Promise<boolean> {
361 const folder = await folderOf($, await $.session.id())
362 const record = async (text: string) => {
363 if (folder !== null) {
364 await $.fs.write(inFolder(folder, SENT), text)
365 }
366 }
367 let isSent = false
368
369 try {
370 await record(JSON.stringify(sent))
371 // Framed for the model and labelled on screen as this plugin's, by design.
372 const { drop } = await $.prompt.submit({ text: sent.answer })
373
374 isSent = drop === undefined
375 } finally {
376 if (!isSent) {
377 await record(NOTHING_SENT)
378 }
379 }
380
381 return isSent
382}
383
384/** Sends a row as the next message; whether it entered. */
385const submit = ($: EngineInterface, gate: Gate, option: Option) =>
386 deliver($, {
387 answer: answerOf(option),
388 question: gate.question,
389 label: option.head,
390 })
391
392/** Whether `attempt` took; one that fails did not. */
393const took = (attempt: Promise<boolean>) => attempt.catch(() => false)
394
395/**
396 * Carries a handoff: the conversation cleared, then the continuation sent into
397 * the new one, recorded with its line in that conversation's folder first,
398 * and a toast saying where the work went. A clear that fails sends in place,
399 * so the work still goes on; a send that fails or is dropped waits in the
400 * prompt box for Enter; where the box refuses it too, the toast holds the
401 * continuation for the person to send.
402 */
403async function handOff($: EngineInterface, { text, line }: Handoff) {
404 try {
405 await $.command.run({ command: 'clear' })
406 } catch {
407 // Not cleared: the continuation goes on in this conversation.
408 }
409
410 const isCarried =
411 (await took(deliver($, { answer: text, line }))) ||
412 (await took(fill($, text)))
413
414 if (isCarried) {
415 $.ui.toast(`Handed off ${line}`, { timeoutMs: HANDED_OFF_TOAST_MS })
416 } else {
417 $.ui.toast(`Not handed off ${line} — send this to carry on: ${text}`, {
418 timeoutMs: UNCARRIED_TOAST_MS,
419 })
420 }
421}
422
423/**
424 * Empties the prompt box while it holds exactly `text`, a pick's answer; a
425 * draft the person has edited stays.
426 */
427async function unpick($: EngineInterface, text: string) {
428 const box = await $.prompt.read()
429
430 if (box.text === text) {
431 await fill($, '')
432 }
433}
434
435/**
436 * Sends the picked row, the box cleared first; a send that fails or is
437 * dropped puts the answer back in the box, where the pick says it is.
438 */
439async function send($: EngineInterface, gate: Gate, option: Option) {
440 let isSent = false
441
442 await fill($, '')
443
444 try {
445 isSent = await submit($, gate, option)
446 } finally {
447 if (!isSent) {
448 await fill($, answerOf(option))
449 }
450 }
451}
452
453/**
454 * Where a conversation stands: its session id, which names its folder, and
455 * the stamp of the step its transcript ends on.
456 */
457type Place = { id: string; stamp: string }
458
459/** What a conversation's folder keeps of its band: its gate, and where the transcript ended. */
460type Kept = { stamp: string; gate: Gate }
461
462/** A band read back from its folder: where the conversation stands, its gate. */
463type ReadBack = { place: Place; gate: Gate | null }
464
465/**
466 * A read-back the band owes before it is trusted, never taken from `ended`:
467 * the conversation that ended in this process, while the transcript still
468 * holds it.
469 */
470type Owed = { ended: Place | null }
471
472/** The tool calls a message makes or answers, by id. */
473const callsOf = (message: SessionMessage) => [
474 ...message.toolUses.map(use => use.tool_use_id),
475 ...(message.toolResults ?? []).map(result => result.tool_use_id),
476]
477
478/**
479 * The lines Claude Code writes around an interrupted turn rather than the
480 * conversation taking a step: the interruption itself, which can land after
481 * that turn's end has kept the band, and the reply it puts in the model's
482 * place when the conversation is resumed after one. No stamp reads them.
483 */
484const isInterruption = (message: SessionMessage) =>
485 (message.role === 'user' &&
486 message.text.startsWith('[Request interrupted by user')) ||
487 (message.role === 'assistant' &&
488 message.text === 'No response requested.' &&
489 message.toolUses.length === 0)
490
491/**
492 * Where the conversation stands now; null until it takes a step. The stamp
493 * is the last step — who wrote it, its text, the calls it makes or answers —
494 * and the newest call of all, so a conversation that moved on and came to
495 * rest on the same words is told apart.
496 */
497async function placeOf($: EngineInterface): Promise<Place | null> {
498 const id = await $.session.id()
499 const steps = (await $.session.messages()).filter(
500 message => !isInterruption(message),
501 )
502 const last = steps.at(-1)
503
504 if (last === undefined) {
505 return null
506 }
507
508 const calls = steps.flatMap(callsOf)
509
510 return {
511 id,
512 stamp: JSON.stringify([
513 last.role,
514 last.text,
515 callsOf(last),
516 calls.at(-1) ?? null,
517 ]),
518 }
519}
520
521const isSamePlace = (place: Place, other: Place | null) =>
522 other !== null && place.id === other.id && place.stamp === other.stamp
523
524/** Whether `place` is the conversation `seen` read, however far on. */
525const isSameConversation = (place: Place | null, seen: Place | null) =>
526 place !== null && seen !== null && place.id === seen.id
527
528const isKept = (value: unknown): value is Kept =>
529 typeof value === 'object' &&
530 value !== null &&
531 typeof (value as Kept).stamp === 'string'
532
533/**
534 * The folder of the conversation `id`, as the engine names it (`folder.ts`);
535 * null where the process names neither directory.
536 */
537async function folderOf(
538 $: EngineInterface,
539 id: string,
540): Promise<string | null> {
541 return folderNamed(
542 await $.env.get('WORKFLOWS_CONFIG_DIR'),
543 await $.env.get('HOME'),
544 id,
545 )
546}
547
548/** A file in a conversation's folder. */
549const inFolder = (folder: string, file: string) => `${folder}/${file}`
550
551/**
552 * The folder of the conversation `id` where the engine has marked it as one
553 * that runs the workflows; null for any other conversation.
554 */
555async function markedFolder(
556 $: EngineInterface,
557 id: string,
558): Promise<string | null> {
559 const folder = await folderOf($, id)
560
561 return folder !== null && (await $.fs.exists(inFolder(folder, MARKER)))
562 ? folder
563 : null
564}
565
566/**
567 * Keeps what the band shows for the conversation at `place` — the gate, or
568 * nothing — in its folder, in a session that announced and a conversation
569 * that runs the workflows: any other conversation gets no folder.
570 */
571async function keep($: EngineInterface, place: Place | null, gate: Gate | null) {
572 if (place === null || !(await isAnnounced($))) {
573 return
574 }
575
576 const folder = await markedFolder($, place.id)
577
578 if (folder === null) {
579 return
580 }
581
582 const kept: Kept | null = gate === null ? null : { stamp: place.stamp, gate }
583
584 await $.fs.write(inFolder(folder, KEPT), JSON.stringify(kept))
585}
586
587/** What `folder` keeps of its band; undefined where it keeps nothing readable. */
588async function keptIn($: EngineInterface, folder: string): Promise<unknown> {
589 try {
590 return JSON.parse(await $.fs.read(inFolder(folder, KEPT)))
591 } catch {
592 return undefined
593 }
594}
595
596/**
597 * The person's own values of the settings the harness sets, absent where
598 * unset: what the harness replaced, kept while it is on.
599 */
600type Replaced = {
601 CLAUDE_CODE_THINKING_DISPLAY_UPDATES?: string
602 CLAUDE_CODE_SILENT_TURN_REMINDER?: string
603}
604
605/**
606 * Puts Claude Code's harness on for a workflow session, one whose
607 * conversation the engine has marked in a session that announced: no
608 * summary of Claude's thinking printed as if it were output, and no nudge to
609 * say what it is doing. Claude Code reads both per request. What it replaces
610 * is kept in the process's environment, which a reload of the module's files
611 * keeps, and only where nothing is kept yet: the values are read before that
612 * is looked at, so a harness another call has just put on is never kept as
613 * the person's.
614 */
615async function harnessOn($: EngineInterface) {
616 if (!(await isAnnounced($))) {
617 return
618 }
619
620 const replaced: Replaced = {
621 CLAUDE_CODE_THINKING_DISPLAY_UPDATES: await $.env.get(
622 'CLAUDE_CODE_THINKING_DISPLAY_UPDATES',
623 ),
624 CLAUDE_CODE_SILENT_TURN_REMINDER: await $.env.get(
625 'CLAUDE_CODE_SILENT_TURN_REMINDER',
626 ),
627 }
628
629 if ((await $.env.get('WORKFLOWS_HARNESS_REPLACED')) === undefined) {
630 await $.env.set('WORKFLOWS_HARNESS_REPLACED', JSON.stringify(replaced))
631 }
632
633 await $.env.set('CLAUDE_CODE_THINKING_DISPLAY_UPDATES', 'false')
634 await $.env.set('CLAUDE_CODE_SILENT_TURN_REMINDER', 'false')
635}
636
637/**
638 * Takes the harness off, putting back exactly what it replaced: the person's
639 * value, or none. Where the harness is not on, nothing is touched.
640 */
641async function harnessOff($: EngineInterface) {
642 const kept = await $.env.get('WORKFLOWS_HARNESS_REPLACED')
643
644 if (kept === undefined) {
645 return
646 }
647
648 const replaced = JSON.parse(kept) as Replaced
649
650 await $.env.set(
651 'CLAUDE_CODE_THINKING_DISPLAY_UPDATES',
652 replaced.CLAUDE_CODE_THINKING_DISPLAY_UPDATES,
653 )
654 await $.env.set(
655 'CLAUDE_CODE_SILENT_TURN_REMINDER',
656 replaced.CLAUDE_CODE_SILENT_TURN_REMINDER,
657 )
658 await $.env.set('WORKFLOWS_HARNESS_REPLACED', undefined)
659}
660
661/**
662 * Settles the read-back the band owes, if `owing` says it owes one: `take`
663 * gets the conversation the transcript holds now, with its kept gate where
664 * the transcript still ends where it was kept, or none where it has moved
665 * on, the kept gate dropped while the read-back is still owed. A
666 * conversation the engine has marked gets the workflow harness back, again
667 * while the read-back is still owed. Nothing settles in a session that did
668 * not announce, while the transcript is empty, or while it still holds the
669 * conversation that ended in this process.
670 */
671async function readBack(
672 $: EngineInterface,
673 owing: () => Owed | null,
674 take: (asked: Owed, read: ReadBack) => void,
675) {
676 const asked = owing()
677
678 if (asked === null || !(await isAnnounced($))) {
679 return
680 }
681
682 const place = await placeOf($)
683
684 if (place === null || isSamePlace(place, asked.ended)) {
685 return
686 }
687
688 const folder = await markedFolder($, place.id)
689
690 if (folder !== null && owing() === asked) {
691 await harnessOn($)
692 }
693
694 const kept = folder === null ? undefined : await keptIn($, folder)
695
696 if (isKept(kept) && kept.stamp === place.stamp) {
697 take(asked, { place, gate: kept.gate })
698
699 return
700 }
701
702 if (folder !== null && isKept(kept) && owing() === asked) {
703 await $.fs.write(inFolder(folder, KEPT), JSON.stringify(null))
704 }
705
706 take(asked, { place, gate: null })
707}
708
709export const register: Register = on => {
710 let band = emptyBand()
711
712 /** Whether a send is under way, so a press meanwhile cannot send twice. */
713 let isSending = false
714
715 /**
716 * The read-back the band owes: from the module's load, which a restart or
717 * a reload of its files begins, and from a conversation's end in this
718 * process, until the next turn or a read settles it.
719 */
720 let owed: Owed | null = { ended: null }
721
722 /** Where the conversation stood when the band was last kept or read back. */
723 let seen: Place | null = null
724
725 /** The handoff a call armed, carried once its turn ends. */
726 let handoff: Handoff | null = null
727
728 /**
729 * Whether the clear under way is this module's own, for a handoff: the
730 * conversation it leads into runs the workflows by construction, so the
731 * workflow harness stays on through it.
732 */
733 let isClearingForHandoff = false
734
735 /**
736 * The person takes the turn: the band comes down, keeping the gate their
737 * turn answers. Whether a gate came down.
738 */
739 const takeDown = (): boolean => {
740 const { drawn } = band
741
742 band = { ...emptyBand(), running: 'person', answering: drawn }
743
744 return drawn !== null
745 }
746
747 /**
748 * Settles the band as the conversation's turn ends. The person's turn
749 * draws the gate it rendered; an Esc drops that and takes the answer back,
750 * its gate returning, until the turn calls a tool, which may already have
751 * acted on the answer: a read and a write look alike from here. Anyone
752 * else's turn leaves the band as it is unless it rendered another gate: at
753 * its end that gate takes the band and drops a held answer unsent; after an
754 * Esc, which leaves the model at that gate's stop, the band empties. A held
755 * answer on the gate still there sends now, or after an Esc goes back to
756 * the prompt as a pick; a pick whose gate went goes with it.
757 */
758 const endTurn = (isInterrupted: boolean): Settled => {
759 const { running, armed, drawn, picked, answering, hasCalledTool, sends } =
760 band
761
762 band = { ...band, armed: null, running: null, answering: null }
763
764 if (running !== 'other') {
765 band.drawn = isInterrupted ? (hasCalledTool ? null : answering) : armed
766
767 return NOTHING_SETTLED
768 }
769
770 const gate = armed ?? drawn
771
772 if (!isSameGate(gate, drawn)) {
773 band = isInterrupted
774 ? { ...band, drawn: null, picked: null, sends: NO_SENDS }
775 : {
776 ...band,
777 drawn: gate,
778 picked: null,
779 sends: { held: null, dropped: sends.held },
780 }
781
782 return { held: null, gone: picked }
783 }
784
785 band.sends = { ...sends, held: null }
786
787 const option =
788 drawn === null || sends.held === null
789 ? null
790 : optionIn(drawn, { answer: sends.held })
791
792 return {
793 held: option === null ? null : { option, isToSend: !isInterrupted },
794 gone: null,
795 }
796 }
797
798 const owing = () => owed
799
800 /**
801 * Takes a read-back onto the band, unless a turn or a conversation's end
802 * overtook it while it read: the conversation it read is the one the band
803 * follows from here.
804 */
805 const takeBack = (asked: Owed, read: ReadBack) => {
806 if (owed !== asked) {
807 return
808 }
809
810 owed = null
811 seen = read.place
812
813 if (read.gate !== null) {
814 band.drawn = read.gate
815 }
816 }
817
818 // Announced, never always-on: the engine collects a gate, and composes a
819 // handoff for this module to carry, only for a session that asked, and
820 // every Bash child inherits this. Where the mod does not apply nothing is
821 // announced, which leaves it inert there. A fresh load comes back to a
822 // conversation this module has not followed, so the band is read back from
823 // the conversation's folder.
824 on('session.start', async ($, e, next) => {
825 if (!(await isApplicable($))) {
826 return next(e)
827 }
828
829 await $.env.set('WORKFLOWS_GATE_SURFACE', '1')
830 await $.env.set('WORKFLOWS_HANDOFF', '1')
831
832 // Claude Code builds its tool catalogue just after this hook, so only
833 // here does the switch that gives the session SendUserMessage count.
834 await $.env.set('CLAUDE_CODE_PEWTER_OWL_TOOL', 'true')
835
836 owed = { ended: null }
837 await readBack($, owing, takeBack)
838
839 if (band.drawn !== null) {
840 $.ui.invalidate('ui.render')
841 }
842
843 return next(e)
844 }).catch(($, e, next) => next(e))
845
846 // A /clear or a resume goes on in this process as another conversation,
847 // which no gate of this one answers and which is no workflow session until
848 // the engine marks it or it is read back as one it has marked. What the
849 // band showed is kept for this one first, stamped where its transcript
850 // ends now, which can have moved since its last turn's end. The clear a
851 // handoff runs leads into a workflow conversation, so the harness stays on.
852 on('session.end', async ($, e, next) => {
853 const isHandingOff = isClearingForHandoff && e.reason === 'clear'
854
855 isClearingForHandoff = false
856
857 try {
858 const place = await placeOf($)
859
860 if (isSameConversation(place, seen)) {
861 await keep($, place, band.drawn)
862 seen = place
863 }
864 } finally {
865 band = emptyBand()
866 handoff = null
867 owed = { ended: seen }
868 seen = null
869 $.ui.invalidate('ui.render')
870
871 if (!isHandingOff) {
872 await harnessOff($)
873 }
874 }
875
876 return next(e)
877 }).catch(($, e, next) => next(e))
878
879 on('tool.call', ($, e, next) => {
880 if (inConversation(e)) {
881 band.hasCalledTool = true
882 }
883
884 return next(e)
885 }).catch(($, e, next) => next(e))
886
887 // Every engine call marks the conversation that made it, whatever its exit,
888 // so after each of the conversation's own commands the mark says whether it
889 // runs the workflows; a command that only mentions the engine marks nothing.
890 // A failure replays the payloads uncut, so the harness never fails the call
891 // and nothing is armed until nothing more can fail.
892 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
893 const result = await next(e)
894
895 try {
896 if (
897 inConversation(e) &&
898 (await markedFolder($, await $.session.id())) !== null
899 ) {
900 await harnessOn($)
901 }
902 } catch {
903 // The harness waits for the conversation's next call.
904 }
905
906 if (result.deny !== undefined || result.isError === true) {
907 return result
908 }
909
910 const record = result.result
911 const carried = handoffIn(record.stdout)
912 const stdout = carried === null ? record.stdout : carried.text
913 const stated = gateIn(stdout)
914 const isArmed = stated !== null && (await isForBand($, e))
915
916 if (carried !== null && inConversation(e)) {
917 handoff = carried.handoff
918 }
919
920 if (stated === null) {
921 return carried === null ? result : { result: { ...record, stdout } }
922 }
923
924 if (isArmed) {
925 band.armed = stated.gate
926 }
927
928 return {
929 result: { ...record, stdout: isArmed ? stated.cut : stated.text },
930 }
931 }).catch(($, e, next) => next(e))
932
933 // The tool waits behind ToolSearch in every session that announced,
934 // workflow or not: one answer, since a changed answer sends the tool list
935 // again and spends the prompt cache.
936 on('tool.describe', { tool: 'SendUserMessage' }, async ($, e, next) => {
937 const described = await next(e)
938
939 return (await isAnnounced($))
940 ? { ...described, isDeferred: true }
941 : described
942 }).catch(($, e, next) => next(e))
943
944 // Drawn at the turn's end, once what the rows choose between is on screen,
945 // and kept with where the transcript ends, which a resume must still match.
946 // A held answer is not kept: it waits on a turn no resume brings back. It
947 // sends once the turn is over, and one not sent is put back as a pick; the
948 // answer of a pick whose gate went leaves the prompt box. A handoff the turn
949 // armed is carried once it is over, whatever else at its end fails; an Esc
950 // means stop, and carries nothing.
951 on('turn.complete', async ($, e, next) => {
952 if (!inConversation(e)) {
953 return next(e)
954 }
955
956 const carried = handoff
957
958 handoff = null
959
960 try {
961 const settled = endTurn(e.isAborted)
962 const { drawn } = band
963
964 owed = null
965
966 if (drawn !== null) {
967 $.ui.invalidate('ui.render')
968 }
969
970 const place = await placeOf($)
971
972 await keep($, place, drawn)
973 seen = place
974
975 const answered = await next(e)
976 const { held, gone } = settled
977
978 if (gone !== null) {
979 await unpick($, gone)
980 }
981
982 if (held !== null && drawn !== null) {
983 const answer = answerOf(held.option)
984 let isSent = false
985
986 isSending = true
987
988 try {
989 isSent = held.isToSend && (await submit($, drawn, held.option))
990 } finally {
991 isSending = false
992
993 if (!isSent && (await fill($, answer))) {
994 band.picked = answer
995 $.ui.invalidate('ui.render')
996 }
997 }
998 }
999
1000 return answered
1001 } finally {
1002 if (carried !== null && !e.isAborted) {
1003 // A command cannot run inside a hook the turn waits on, so the clear
1004 // runs from a timer once this hook is done — proven in the lab.
1005 $.clock.after(0, () => {
1006 isClearingForHandoff = true
1007 void handOff($, carried).finally(() => {
1008 isClearingForHandoff = false
1009 })
1010 })
1011 }
1012 }
1013 }).catch(($, e, next) => next(e))
1014
1015 // A drawing while a read-back is owed — a reload's first, the first after
1016 // a conversation's end, one before the transcript was there to read —
1017 // settles it first.
1018 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1019 await readBack($, owing, takeBack)
1020
1021 const gate = band.drawn
1022
1023 if (
1024 gate === null ||
1025 e.props.hasSurvey ||
1026 (e.surface !== 'terminal' && e.surface !== 'desktop')
1027 ) {
1028 return next(e)
1029 }
1030
1031 const beneath = await next(e)
1032
1033 try {
1034 const { Box, Client } = await $.ui.resolve(e)
1035 const { bodyColumns: columns, maxRows } = e.props
1036
1037 return Box({
1038 flexDirection: 'column',
1039 children: [
1040 // The module's path is read off this source, so it is a literal;
1041 // the region must be exactly as tall as the drawing, or the pointer
1042 // cannot reach the rows past its edge.
1043 h(Client, {
1044 key: ELEMENT,
1045 module: './board.ts',
1046 width: columns,
1047 height: linesOf(gate, columns, IDLE, band.sends, maxRows).length,
1048 props: {
1049 gate,
1050 picked: band.picked,
1051 ...band.sends,
1052 columns,
1053 maxRows,
1054 },
1055 }),
1056 beneath,
1057 ],
1058 })
1059 } catch {
1060 return beneath
1061 }
1062 }).catch(($, e, next) => next(e))
1063
1064 // The board has no `$`: a press posts here, and this picks its row or, on
1065 // the row already picked, sends it. The turn a send opens takes the gate
1066 // off the band; a send that fails or is dropped leaves the row there to
1067 // press again. While anyone else's turn runs, the send is held, its answer
1068 // out of the prompt box, until that turn ends; a press on the held row
1069 // takes it back to a pick, and a press on another row picks that instead.
1070 on('ui.message', { element: ELEMENT }, async ($, e, next) => {
1071 const gate = band.drawn
1072 const option = gate === null || isSending ? null : optionIn(gate, e.data)
1073
1074 if (gate === null || option === null) {
1075 return next(e)
1076 }
1077
1078 const answer = answerOf(option)
1079
1080 if (answer !== band.picked) {
1081 if (await fill($, answer)) {
1082 band.picked = answer
1083 band.sends = { ...band.sends, held: null }
1084 $.ui.invalidate('ui.render')
1085 }
1086 } else if (band.running === 'other') {
1087 if (await fill($, '')) {
1088 band.picked = null
1089 band.sends = { ...band.sends, held: answer }
1090 $.ui.invalidate('ui.render')
1091 }
1092 } else {
1093 isSending = true
1094
1095 try {
1096 await send($, gate, option)
1097 } finally {
1098 isSending = false
1099 }
1100 }
1101
1102 return next(e)
1103 }).catch(($, e, next) => next(e))
1104
1105 // A submission made while the session idles opens the next turn; one made
1106 // over a running turn joins it, and the person's makes anyone else's turn
1107 // theirs, which takes the band down.
1108 on('prompt.submit', ($, e, next) => {
1109 const isTheirs = isPersons(e.origin, $.plugin.name)
1110
1111 if (e.turnId === undefined) {
1112 band.isOpenedByPerson = isTheirs
1113 } else if (isTheirs && band.running === 'other') {
1114 if (takeDown()) {
1115 $.ui.invalidate('ui.render')
1116 }
1117 }
1118
1119 return next(e)
1120 }).catch(($, e, next) => next(e))
1121
1122 // A gate lives from its render to the turn the person starts to answer it,
1123 // which keeps it to put back; a gate the conversation re-presents is armed
1124 // again by its own render. Anyone else's turn — an agent's report, a
1125 // notification, a schedule — leaves the band live, its rows still to
1126 // press. The band follows the conversation the turn runs in, owing no
1127 // read-back.
1128 on('turn.start', ($, e, next) => {
1129 owed = null
1130
1131 if (!band.isOpenedByPerson) {
1132 band = {
1133 ...band,
1134 armed: null,
1135 isOpenedByPerson: true,
1136 running: 'other',
1137 hasCalledTool: false,
1138 }
1139 } else if (takeDown()) {
1140 $.ui.invalidate('ui.render')
1141 }
1142
1143 return next(e)
1144 }).catch(($, e, next) => next(e))
1145
1146 spinner(on)
1147 guard(on)
1148 compaction(on)
1149}
1150hooks/compaction.ts 152 lines1/**
2 * A workflow conversation's compaction: Claude Code compacts as it does, and
3 * the mod appends one message, last, the engine's own words — that the
4 * conversation was just compacted, where it is working, and the skill's steps
5 * for resuming after one with what to re-read. A `/compact` starts no turn of
6 * its own, so after one the mod sends a continuation for Claude to follow the
7 * note.
8 *
9 * Only the main conversation of a conversation the engine has marked, in a
10 * session that announced, at a position that names a skill; everything else
11 * compacts as Claude Code does. Each note handed up is recorded in the
12 * conversation's folder as `compacted.json`, which the rows mod draws the
13 * note's row from.
14 */
15import type { EngineInterface, On, SessionMessage } from 'claude-code'
16
17import { MARKER, folderOf } from './folder.ts'
18
19const ENGINE = '.claude/skills/workflow-engine/scripts/engine.cjs'
20
21const POSITION_MARKER = '=== POSITION ('
22
23const ENGINE_TIMEOUT_MS = 15_000
24
25const COMPACTED = 'compacted.json'
26
27export const CONTINUATION =
28 'The compaction is done. Please carry on from where the conversation left off.'
29
30type CarryOn = { text: string; skill: string | null; place: string }
31
32/** Keyed by each note's text, as the rows mod finds the row it draws. */
33type Notes = Record<string, string>
34
35const isNotes = (value: unknown): value is Notes =>
36 typeof value === 'object' &&
37 value !== null &&
38 !Array.isArray(value) &&
39 Object.values(value).every(place => typeof place === 'string')
40
41/**
42 * The session's own conversation's folder where the session announced and
43 * the engine has marked the conversation as one that runs the workflows;
44 * null for any other.
45 */
46async function workflowFolder($: EngineInterface): Promise<string | null> {
47 if ((await $.env.get('WORKFLOWS_GATE_SURFACE')) !== '1') {
48 return null
49 }
50
51 const folder = folderOf(
52 await $.env.get('WORKFLOWS_CONFIG_DIR'),
53 await $.env.get('HOME'),
54 await $.session.id(),
55 )
56
57 return folder !== null && (await $.fs.exists(`${folder}/${MARKER}`)) ? folder : null
58}
59
60/** The engine's `conversation position` answer, from its POSITION line; null where it gave none. */
61export function positionIn(stdout: string): CarryOn | null {
62 const lines = stdout.split('\n')
63 const at = lines.findIndex(line => line.startsWith(POSITION_MARKER))
64
65 try {
66 const { text, skill, place } = JSON.parse(lines[at + 1] ?? '') as {
67 text?: unknown
68 skill?: unknown
69 place?: unknown
70 }
71
72 return at !== -1 && typeof text === 'string' && typeof place === 'string'
73 ? { text, skill: typeof skill === 'string' ? skill : null, place }
74 : null
75 } catch {
76 return null
77 }
78}
79
80async function positionNow($: EngineInterface): Promise<CarryOn | null> {
81 const root = await $.session.root()
82 const { exitCode, stdout } = await $.process.run(
83 ['node', `${root}/${ENGINE}`, 'conversation', 'position', await $.session.id()],
84 { cwd: root, timeoutMs: ENGINE_TIMEOUT_MS },
85 )
86
87 return exitCode === 0 ? positionIn(stdout) : null
88}
89
90/**
91 * Adds a note handed up to the conversation's record of them. A record that
92 * cannot be read starts afresh; one that cannot be written costs the drawing
93 * alone, never the compaction.
94 */
95async function record($: EngineInterface, folder: string, { text, place }: CarryOn) {
96 const file = `${folder}/${COMPACTED}`
97 let notes: Notes = {}
98
99 try {
100 const kept: unknown = JSON.parse(await $.fs.read(file))
101
102 notes = isNotes(kept) ? kept : {}
103 } catch {}
104
105 try {
106 await $.fs.write(file, JSON.stringify({ ...notes, [text.trim()]: place }))
107 } catch {}
108}
109
110/** A continuation that is dropped or fails waits in the prompt box for Enter instead. */
111async function sendContinuation($: EngineInterface) {
112 const { drop } = await $.prompt.submit({ text: CONTINUATION }).catch(() => ({ drop: 'failed' }))
113
114 if (drop !== undefined) {
115 await $.prompt.fill({ text: CONTINUATION, mode: 'replace' }).catch(() => undefined)
116 }
117}
118
119const message = (text: string): SessionMessage => ({ role: 'user', text, toolUses: [] })
120
121export function compaction(on: On) {
122 on('session.compact', async ($, e, next) => {
123 if (e.trigger === 'precompute' || e.agentId !== undefined) {
124 return next(e)
125 }
126
127 const folder = await workflowFolder($)
128 const carryOn = folder === null ? null : await positionNow($)
129
130 if (folder === null || carryOn === null || carryOn.skill === null) {
131 return next(e)
132 }
133
134 const compacted = await next(e)
135
136 if (compacted.messages === undefined) {
137 return compacted
138 }
139
140 await record($, folder, carryOn)
141
142 if (e.trigger === 'manual') {
143 // The session takes a prompt only once the `/compact` is done.
144 $.clock.after(0, () => {
145 void sendContinuation($)
146 })
147 }
148
149 return { ...compacted, messages: [...compacted.messages, message(carryOn.text)] }
150 }).catch(($, e, next) => next(e))
151}
152hooks/folder.ts 32 lines1/**
2 * The conversation's folder, as the engine names it (domain/conversation.cjs):
3 * in the workflows' system config directory — `WORKFLOWS_CONFIG_DIR`, else
4 * `.config/workflows` in the home directory — by the session id's safe
5 * characters alone, so a `cd` or a resume elsewhere finds it all the same.
6 *
7 * No `$` here: a hook's `$` is never followed across an import, so each
8 * module reads the environment and the files itself.
9 */
10
11/** The file the engine marks a conversation that runs the workflows with. */
12export const MARKER = 'workflow'
13
14/** The file the engine keeps the conversation's position in. */
15export const POSITION = 'position.json'
16
17/**
18 * The folder of the conversation `id`, from the process's
19 * `WORKFLOWS_CONFIG_DIR` and `HOME`; null where they name neither directory.
20 */
21export function folderOf(
22 configDir: string | undefined,
23 home: string | undefined,
24 id: string,
25): string | null {
26 const config = configDir || (home ? `${home}/.config/workflows` : null)
27
28 return config === null
29 ? null
30 : `${config}/conversations/${id.replace(/[^A-Za-z0-9_-]/g, '')}`
31}
32hooks/guard.ts 108 lines1/**
2 * The workflows' manifests are the engine's to write: in a session that
3 * announced, in a conversation the engine has marked, a file tool aimed at a
4 * work unit's manifest or the project manifest is refused, wherever its path
5 * leads from.
6 */
7import type { EngineInterface, On } from 'claude-code'
8
9import { MARKER, folderOf } from './folder.ts'
10
11const REFUSAL =
12 'Workflow manifests are written through the engine, never edited directly — use `node .claude/skills/workflow-engine/scripts/engine.cjs manifest set|push|pull|delete|apply …` instead.'
13
14const MANIFEST = 'manifest.json'
15
16/**
17 * Whether the session announced and the engine has marked its conversation
18 * as one that runs the workflows.
19 */
20async function isWorkflow($: EngineInterface): Promise<boolean> {
21 if ((await $.env.get('WORKFLOWS_GATE_SURFACE')) !== '1') {
22 return false
23 }
24
25 const folder = folderOf(
26 await $.env.get('WORKFLOWS_CONFIG_DIR'),
27 await $.env.get('HOME'),
28 await $.session.id(),
29 )
30
31 return folder !== null && (await $.fs.exists(`${folder}/${MARKER}`))
32}
33
34/** A path as written, made absolute: `~/` the home directory, a relative one the session's working directory. */
35async function absoluteOf($: EngineInterface, path: string): Promise<string> {
36 if (path.startsWith('/')) {
37 return path
38 }
39
40 const home = path.startsWith('~/') ? await $.env.get('HOME') : undefined
41
42 return home ? `${home}/${path.slice(2)}` : `${await $.session.cwd()}/${path}`
43}
44
45/**
46 * Where a path lands, every link followed: the nearest part of it that
47 * exists resolved, the rest of its spelling after it — a file not there yet
48 * lands where writing it would put it. Undefined where nothing resolves.
49 */
50async function landing(
51 $: EngineInterface,
52 path: string,
53): Promise<string | undefined> {
54 const absolute = await absoluteOf($, path)
55 const parts: string[] = []
56
57 for (const part of absolute.split('/')) {
58 if (part === '..') {
59 parts.pop()
60 } else if (part !== '' && part !== '.') {
61 parts.push(part)
62 }
63 }
64
65 for (let n = parts.length; n >= 0; n -= 1) {
66 const stat = await $.fs
67 .stat(`/${parts.slice(0, n).join('/')}`, { resolve: true })
68 .catch(() => undefined)
69
70 if (stat?.realPath !== undefined) {
71 return [stat.realPath.replace(/\/$/, ''), ...parts.slice(n)].join('/')
72 }
73 }
74
75 return undefined
76}
77
78/**
79 * Whether `path` lands on a manifest the engine keeps under the session's
80 * project: `.workflows/manifest.json`, or a work unit's own one level down.
81 */
82async function isManifest($: EngineInterface, path: string): Promise<boolean> {
83 const workflows = await landing($, `${await $.session.root()}/.workflows`)
84 const real = await landing($, path)
85
86 if (workflows === undefined || real === undefined || !real.startsWith(`${workflows}/`)) {
87 return false
88 }
89
90 const [first, second, ...deeper] = real.slice(workflows.length + 1).split('/')
91
92 return second === undefined
93 ? first === MANIFEST
94 : second === MANIFEST && deeper.length === 0 && first !== undefined && !first.startsWith('.')
95}
96
97export function guard(on: On) {
98 on('tool.call', { tool: ['Write', 'Edit', 'NotebookEdit'] }, async ($, e, next) => {
99 const path = e.tool === 'NotebookEdit' ? e.notebook_path : e.file_path
100
101 if (!(await isWorkflow($)) || !(await isManifest($, path))) {
102 return next(e)
103 }
104
105 return { deny: REFUSAL }
106 }).catch(($, e, next) => next(e))
107}
108hooks/layout.ts 558 lines1/**
2 * The gate's geometry and text shaping, shared by the hooks module and the
3 * board: the band is one list of lines, which the hook counts to size the
4 * `Client`'s region and the board draws line for line. Any drift between the
5 * two is dead space under the last row, or rows the pointer cannot reach.
6 *
7 * The engine states every gate as data, so nothing here parses markdown: a
8 * row arrives already split into what it is and what it says about itself.
9 */
10
11/** One pressable row of the engine's gate payload. */
12export type Option = {
13 key: string
14 word: string | null
15 head: string
16 tail: string | null
17 cue: string | null
18 holder: string | null
19 detail: string | null
20 struck: boolean
21 recommended: boolean
22}
23
24/** One row of the payload a span or a natural reply can only answer. */
25export type Typed = {
26 label: string
27 description: string
28 detail: string | null
29}
30
31/** A gate as the engine states it, less its name. */
32export type Gate = {
33 question: string
34 statement: string
35 options: Option[]
36 typed: Typed[]
37}
38
39/** A run of a drawn line under one style. */
40export type Run = {
41 text: string
42 bold?: boolean
43 dim?: boolean
44 italic?: boolean
45 strikethrough?: boolean
46 underline?: boolean
47 /** Drawn in the colour the band asks in, rather than the text's own. */
48 accent?: boolean
49}
50
51/**
52 * What the footer says: how to answer, what a pick put in the prompt, what
53 * waits to send when Claude finishes, what a new gate kept from sending, or
54 * how to answer the typed row last clicked.
55 */
56export type Footer =
57 | { kind: 'idle' }
58 | { kind: 'picked'; answer: string }
59 | { kind: 'queued'; answer: string }
60 | { kind: 'dropped'; answer: string }
61 | { kind: 'typed'; label: string }
62
63/**
64 * What became of a send pressed while Claude works: the answer held until it
65 * finishes, and one a new gate kept from sending, which that gate's footer
66 * names.
67 */
68export type Sends = { held: string | null; dropped: string | null }
69
70/**
71 * A line of a row: its wrapped label or its detail, each carrying the row so
72 * a pointer lands on any of them. The key column, filled on the first line
73 * alone, and the label are padded out so a background spans the band.
74 */
75export type RowLine = {
76 kind: 'option' | 'typed'
77 index: number
78 key: Run[]
79 runs: Run[]
80}
81
82/** The line under a page of rows: which page shows, of how many. */
83export type PagerLine = { kind: 'pager'; page: number; pages: number }
84
85/** One line of the band, top to bottom. */
86export type Line =
87 | { kind: 'rule' }
88 | { kind: 'blank' }
89 | { kind: 'prose'; glyph: boolean; runs: Run[] }
90 | RowLine
91 | PagerLine
92 | { kind: 'footer'; runs: Run[] }
93
94/** The cursor's gutter, where the footer also sits. */
95export const GUTTER = 2
96
97/** The `◆ ` the question opens with; the statement lines up past it. */
98export const GLYPH_COLUMN = 2
99
100export const IDLE: Footer = { kind: 'idle' }
101
102export const NO_SENDS: Sends = { held: null, dropped: null }
103
104const GAP = 2
105const MIN_LABEL = 8
106
107const TAIL_SEPARATOR = ' — '
108const NOTE_SEPARATOR = ' · '
109const RECOMMENDED = ' (recommended)'
110const QUEUED = ' · queued'
111
112const IDLE_HINT = 'Click to choose · click again to send · or type'
113const PICKED_HINT = ' is in your prompt · click again to send'
114const QUEUED_HINT = ' sends when Claude finishes · click to undo'
115const DROPPED_HINT = ' not sent — the menu changed'
116
117const PREVIOUS = '↑ previous'
118const NEXT = '↓ next'
119const PAGER_GAP = ' '
120
121/** A typed row's label that is a span of numbers, as the engine writes one. */
122const RANGE = /^\d+–\d+$/
123
124const RULE: Line = { kind: 'rule' }
125const BLANK: Line = { kind: 'blank' }
126
127/** The cells of the pager line its previous and next presses cover. */
128export const PAGER_SPANS = {
129 previous: { from: GUTTER, to: GUTTER + PREVIOUS.length },
130 next: {
131 from: GUTTER + PREVIOUS.length + PAGER_GAP.length,
132 to: GUTTER + PREVIOUS.length + PAGER_GAP.length + NEXT.length,
133 },
134}
135
136/** What a row shows in its key column, and what pressing it answers with. */
137export const answerOf = (option: Option) => option.word ?? option.key
138
139/**
140 * The row the cursor starts on, so Enter on arrival takes what the engine
141 * recommends: that row, else the first not struck through, else the first.
142 */
143export function startingRow(options: readonly Option[]): number {
144 const recommended = options.findIndex(option => option.recommended)
145
146 return recommended !== -1
147 ? recommended
148 : Math.max(0, options.findIndex(option => !option.struck))
149}
150
151/** Fills a line out to `width`, so a background spans it. */
152export function pad(runs: readonly Run[], width: number): Run[] {
153 const short = width - runs.reduce((cells, run) => cells + run.text.length, 0)
154
155 return short > 0 ? [...runs, { text: ' '.repeat(short) }] : [...runs]
156}
157
158/**
159 * Greedy word wrap that keeps each run's styling: a label too long for its
160 * column breaks onto the next line rather than being cut, so nothing the
161 * engine wrote is lost. A line's words come back under one run per style,
162 * and the space a break falls on is dropped rather than drawn.
163 */
164export function wrapRuns(runs: readonly Run[], width: number): Run[][] {
165 const column = Math.max(1, width)
166 const lines: Run[][] = []
167
168 let line: { source: Run; run: Run }[] = []
169 let used = 0
170 let gap: { source: Run; text: string } | null = null
171
172 const wrap = () => {
173 lines.push(line.map(entry => entry.run))
174 line = []
175 used = 0
176 gap = null
177 }
178
179 const add = (source: Run, text: string) => {
180 const last = line.at(-1)
181
182 if (last !== undefined && last.source === source) {
183 last.run.text += text
184 } else {
185 line.push({ source, run: { ...source, text } })
186 }
187
188 used += text.length
189 }
190
191 for (const source of runs) {
192 for (const piece of source.text.split(/(\s+)/)) {
193 if (piece === '') {
194 continue
195 }
196
197 if (piece.trim() === '') {
198 gap = used > 0 ? { source, text: piece } : null
199 continue
200 }
201
202 let word = piece
203
204 while (word.length > column) {
205 if (used > 0) {
206 wrap()
207 }
208
209 add(source, word.slice(0, column))
210 word = word.slice(column)
211 wrap()
212 }
213
214 if (used > 0 && used + (gap?.text.length ?? 0) + word.length > column) {
215 wrap()
216 } else if (gap !== null) {
217 add(gap.source, gap.text)
218 }
219
220 gap = null
221 add(source, word)
222 }
223 }
224
225 if (line.length > 0 || lines.length === 0) {
226 wrap()
227 }
228
229 return lines
230}
231
232/** Text whose lines are its own, each wrapped to `width`; none for no text. */
233const paragraphs = (
234 text: string,
235 width: number,
236 style: Omit<Run, 'text'> = {},
237) =>
238 text === ''
239 ? []
240 : text
241 .split('\n')
242 .flatMap(line => wrapRuns([{ ...style, text: line }], width))
243
244/**
245 * The band's two columns at this width: the keys, and the labels beside
246 * them. The band has no frame, so a row is gutter, key, gap, label.
247 */
248export function geometry(gate: Gate, columns: number) {
249 const keyWidth = Math.max(
250 1,
251 ...gate.options.map(option => answerOf(option).length),
252 ...gate.typed.map(row => row.label.length),
253 )
254
255 return {
256 keyWidth,
257 labelWidth: Math.max(MIN_LABEL, columns - GUTTER - keyWidth - GAP),
258 }
259}
260
261/**
262 * The key column's runs: the word with the row's key underlined where the
263 * word spells it, as a menu marks its accelerator; a bare key as it is.
264 */
265function keyRuns(option: Option): Run[] {
266 const shown = answerOf(option)
267 const at =
268 option.word === null
269 ? -1
270 : shown.toLowerCase().indexOf(option.key.toLowerCase())
271
272 if (at === -1) {
273 return [{ text: shown }]
274 }
275
276 const end = at + option.key.length
277
278 return [
279 { text: shown.slice(0, at) },
280 { text: shown.slice(at, end), underline: true },
281 { text: shown.slice(end) },
282 ].filter(run => run.text !== '')
283}
284
285/** A label part after its separator; nothing for a part the row lacks. */
286const partRuns = (
287 separator: string,
288 text: string | null,
289 style: Omit<Run, 'text'> = {},
290): Run[] => (text === null ? [] : [{ text: `${separator}${text}`, ...style }])
291
292/**
293 * A row's label by the text menu's grammar: the tail dim and italic after a
294 * dash, and a cue the same after a dot; a held row struck from its head
295 * through its cue, the holder plain after the strike; and the recommendation
296 * last, bold in the accent colour.
297 */
298function labelRuns(option: Option): Run[] {
299 const strike = option.struck ? { strikethrough: true } : {}
300 const aside = { ...strike, dim: true, italic: true }
301
302 return [
303 { text: option.head, ...strike },
304 ...partRuns(TAIL_SEPARATOR, option.tail, aside),
305 ...partRuns(NOTE_SEPARATOR, option.cue, aside),
306 ...partRuns(NOTE_SEPARATOR, option.holder),
307 ...(option.recommended
308 ? [{ text: RECOMMENDED, bold: true, accent: true }]
309 : []),
310 ]
311}
312
313/**
314 * The pressable rows and then the typed ones, each row's lines a group
315 * closed by its detail; every pressable row marked queued after its label
316 * where `queued`.
317 */
318function rowGroups(gate: Gate, columns: number, queued: boolean): RowLine[][] {
319 const { keyWidth, labelWidth } = geometry(gate, columns)
320
321 const linesOfRow = (
322 kind: RowLine['kind'],
323 index: number,
324 key: Run[],
325 label: Run[],
326 detail: string | null,
327 ): RowLine[] =>
328 [
329 ...wrapRuns(label, labelWidth),
330 ...paragraphs(detail ?? '', labelWidth, { dim: true }),
331 ].map((runs, n) => ({
332 kind,
333 index,
334 key: pad(n === 0 ? key : [], keyWidth + GAP),
335 runs: pad(runs, labelWidth),
336 }))
337
338 return [
339 ...gate.options.map((option, index) =>
340 linesOfRow(
341 'option',
342 index,
343 keyRuns(option),
344 [...labelRuns(option), ...(queued ? [{ text: QUEUED }] : [])],
345 option.detail,
346 ),
347 ),
348 ...gate.typed.map((row, index) =>
349 linesOfRow(
350 'typed',
351 index,
352 [{ text: row.label, dim: true }],
353 [{ text: row.description, dim: true }],
354 row.detail,
355 ),
356 ),
357 ]
358}
359
360// A click leaves the keys with the band; only the person can hand them back.
361const typedHint = (label: string) =>
362 RANGE.test(label)
363 ? `${label} — Esc, then type the numbers in the prompt`
364 : `${label} — Esc, then type it in the prompt`
365
366/** The footer's words: dim, the answer it speaks of named in bold. */
367export function footerRuns(footer: Footer): Run[] {
368 switch (footer.kind) {
369 case 'idle':
370 return [{ text: IDLE_HINT, dim: true }]
371 case 'picked':
372 return [
373 { text: footer.answer, bold: true },
374 { text: PICKED_HINT, dim: true },
375 ]
376 case 'queued':
377 return [
378 { text: footer.answer, bold: true },
379 { text: QUEUED_HINT, dim: true },
380 ]
381 case 'dropped':
382 return [
383 { text: footer.answer, bold: true },
384 { text: DROPPED_HINT, dim: true },
385 ]
386 case 'typed':
387 return [{ text: typedHint(footer.label), dim: true }]
388 }
389}
390
391const footerLines = (footer: Footer, columns: number) =>
392 wrapRuns(footerRuns(footer), columns - GUTTER)
393
394/**
395 * The footer, in a slot as tall as the tallest thing it can say for this
396 * gate, so a click never moves the rows above it.
397 */
398function footerSlot(
399 gate: Gate,
400 footer: Footer,
401 columns: number,
402 dropped: string | null,
403): Line[] {
404 const states: Footer[] = [
405 IDLE,
406 ...gate.options.flatMap(option => [
407 { kind: 'picked' as const, answer: answerOf(option) },
408 { kind: 'queued' as const, answer: answerOf(option) },
409 ]),
410 ...gate.typed.map(row => ({ kind: 'typed' as const, label: row.label })),
411 ...(dropped === null
412 ? []
413 : [{ kind: 'dropped' as const, answer: dropped }]),
414 ]
415
416 const rows = Math.max(
417 ...states.map(state => footerLines(state, columns).length),
418 )
419 const said = footerLines(footer, columns)
420
421 return Array.from({ length: rows }, (_, n) => ({
422 kind: 'footer',
423 runs: said[n] ?? [],
424 }))
425}
426
427/**
428 * The rows cut into pages of `budget` lines, in order: a page takes whole
429 * rows while they fit, and a row taller than a page is cut to it.
430 */
431function pagesOf(groups: readonly RowLine[][], budget: number): RowLine[][] {
432 const pages: RowLine[][] = []
433 let page: RowLine[] = []
434
435 for (const group of groups) {
436 const lines = group.slice(0, budget)
437
438 if (page.length > 0 && page.length + lines.length > budget) {
439 pages.push(page)
440 page = []
441 }
442
443 page = [...page, ...lines]
444 }
445
446 return [...pages, page]
447}
448
449/** The page holding the option at `cursor`; the first for none. */
450const pageHolding = (pages: readonly RowLine[][], cursor: number) =>
451 Math.max(
452 0,
453 pages.findIndex(page =>
454 page.some(line => line.kind === 'option' && line.index === cursor),
455 ),
456 )
457
458/**
459 * Every line the band draws for a gate, top to bottom: the rule, a blank, the
460 * statement, the question, a blank, the rows, a blank and the footer. Where
461 * that would stand taller than `maxRows`, the rows show a page at a time over
462 * a pager line, every page padded to one height; the page shown is `page`, or
463 * the one holding the option at `cursor`. How many lines there are is the
464 * region's height whatever the footer says, whichever row is held and
465 * whichever page shows.
466 */
467export function linesOf(
468 gate: Gate,
469 columns: number,
470 footer: Footer = IDLE,
471 { held, dropped }: Sends = NO_SENDS,
472 maxRows = Infinity,
473 { page, cursor = -1 }: { page?: number; cursor?: number } = {},
474): Line[] {
475 const width = columns - GLYPH_COLUMN
476 const statement = paragraphs(gate.statement, width)
477 const question = paragraphs(gate.question, width, { bold: true })
478 const prose = (runs: Run[], glyph: boolean): Line => ({
479 kind: 'prose',
480 glyph,
481 runs,
482 })
483
484 const plain = rowGroups(gate, columns, false)
485 const queued = rowGroups(gate, columns, true)
486 const heldAt = gate.options.findIndex(option => answerOf(option) === held)
487 const groups = plain.map((group, n) =>
488 n === heldAt ? (queued[n] ?? group) : group,
489 )
490 const rows = groups.flat()
491 const marks = queued.map((group, n) => group.length - (plain[n]?.length ?? 0))
492 const tallest = plain.flat().length + Math.max(0, ...marks)
493 const head: Line[] = [
494 RULE,
495 BLANK,
496 ...statement.map(runs => prose(runs, false)),
497 ...question.map((runs, n) => prose(runs, n === 0)),
498 BLANK,
499 ]
500 const foot = [BLANK, ...footerSlot(gate, footer, columns, dropped)]
501 // Lines under the footer that the rows take back when a held row's mark
502 // wraps, so the whole gate holds its height.
503 const spare = Array.from(
504 { length: tallest - rows.length },
505 (): Line => ({ kind: 'footer', runs: [] }),
506 )
507 const whole = [...head, ...rows, ...foot, ...spare]
508
509 if (whole.length <= maxRows) {
510 return whole
511 }
512
513 const budget = Math.max(1, maxRows - head.length - 1 - foot.length)
514 const pages = pagesOf(groups, budget)
515 const shown = Math.min(pages.length - 1, page ?? pageHolding(pages, cursor))
516 const lines: Line[] = pages[shown] ?? []
517
518 return [
519 ...head,
520 ...lines,
521 ...Array.from({ length: budget - lines.length }, () => BLANK),
522 { kind: 'pager', page: shown, pages: pages.length },
523 ...foot,
524 ]
525}
526
527/** The pager line's words, a press that goes nowhere dim. */
528export const pagerRuns = ({ page, pages }: PagerLine): Run[] => [
529 { text: PREVIOUS, dim: page === 0 },
530 { text: PAGER_GAP },
531 { text: NEXT, dim: page === pages - 1 },
532 { text: `${PAGER_GAP}page ${page + 1} of ${pages}`, dim: true },
533]
534
535/** The page the option at `cursor` shows on; the first where none pages. */
536export const pageOf = (
537 gate: Gate,
538 columns: number,
539 sends: Sends,
540 maxRows: number,
541 cursor: number,
542) =>
543 linesOf(gate, columns, IDLE, sends, maxRows, { cursor }).find(
544 (line): line is PagerLine => line.kind === 'pager',
545 )?.page ?? 0
546
547/** The first option on `page`; null where the page shows none. */
548export const firstOnPage = (
549 gate: Gate,
550 columns: number,
551 sends: Sends,
552 maxRows: number,
553 page: number,
554) =>
555 linesOf(gate, columns, IDLE, sends, maxRows, { page }).find(
556 (line): line is RowLine => line.kind === 'option',
557 )?.index ?? null
558hooks/spinner.ts 81 lines1/**
2 * The spinner saying the phase the conversation works in, the drawing alone,
3 * in a session that announced and a conversation the engine has marked, on
4 * the terminal app's and the Desktop app's surfaces.
5 */
6import type { EngineInterface, On } from 'claude-code'
7
8import { MARKER, POSITION, folderOf } from './folder.ts'
9import { positionOf, wordFor } from './position.ts'
10
11/** The engine calls that move the conversation's position. */
12const MOVES =
13 /\.claude\/skills\/workflow-engine\/scripts\/engine\.cjs"?\s+(?:boot|session\s+(?:label|repair)|task\s+(?:start|complete))\b/
14
15/** The Desktop app's spinner word while its row names no step of its own. */
16const DESKTOP_IDLE = 'Working'
17
18/** The spinner's word for a conversation, and which conversation it was read for. */
19type Said = { id: string; word: string | null }
20
21/**
22 * The spinner's word for the session's conversation as its position stands
23 * now; none in a session that did not announce.
24 */
25async function sayNow($: EngineInterface): Promise<Said> {
26 const id = await $.session.id()
27
28 if ((await $.env.get('WORKFLOWS_GATE_SURFACE')) !== '1') {
29 return { id, word: null }
30 }
31
32 const folder = folderOf(
33 await $.env.get('WORKFLOWS_CONFIG_DIR'),
34 await $.env.get('HOME'),
35 id,
36 )
37 const isMarked = folder !== null && (await $.fs.exists(`${folder}/${MARKER}`))
38 const text = isMarked ? await $.fs.read(`${folder}/${POSITION}`).catch(() => null) : null
39
40 return { id, word: text === null ? null : wordFor(positionOf(text)) }
41}
42
43export function spinner(on: On) {
44 /** What the spinner says; null until read, a null word leaving Claude Code's. */
45 let said: Said | null = null
46
47 // The position is read when an engine call moves it, and once for each
48 // conversation the spinner draws in — never per frame.
49 on('tool.call', { tool: 'Bash', command: MOVES }, async ($, e, next) => {
50 const result = await next(e)
51
52 if (e.agentId === undefined) {
53 const before = said?.word ?? null
54
55 said = await sayNow($)
56
57 if (said.word !== before) {
58 $.ui.invalidate('ui.render')
59 }
60 }
61
62 return result
63 }).catch(($, e, next) => next(e))
64
65 // Claude Code's spinner and its ellipsis, the word the phase. On the
66 // Desktop app a step that names itself keeps its words.
67 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
68 if (said === null || said.id !== (await $.session.id())) {
69 said = await sayNow($)
70 }
71
72 const { word } = said
73
74 if (word === null || (e.surface === 'desktop' && e.props.word !== DESKTOP_IDLE)) {
75 return next(e)
76 }
77
78 return next({ ...e, props: { ...e.props, word } })
79 }).catch(($, e, next) => next(e))
80}
81hooks/board.ts 316 lines1/**
2 * The gate's surface module: its own keys and pointer, no `$`. A press posts
3 * the row back to the hooks module, which picks it into the prompt or, on the
4 * row already picked, sends it — holding it while Claude works, until a press
5 * takes it back; a click on a typed row only tells the person how to answer
6 * it.
7 *
8 * Colours are theme keys, never values, so the band resolves against the
9 * person's theme — the ANSI themes included, where the palette is the
10 * terminal's own and a raw colour would be ignored.
11 */
12import type { ClientSurface, RenderElement } from 'claude-code'
13
14import {
15 GLYPH_COLUMN,
16 GUTTER,
17 IDLE,
18 NO_SENDS,
19 PAGER_SPANS,
20 answerOf,
21 firstOnPage,
22 linesOf,
23 pageOf,
24 pagerRuns,
25 startingRow,
26 type Footer,
27 type Gate,
28 type Line,
29 type PagerLine,
30 type RowLine,
31 type Run,
32 type Sends,
33} from './layout.ts'
34
35type Props = Sends & {
36 gate: Gate
37 picked: string | null
38 columns: number
39 maxRows: number
40}
41
42/**
43 * The cursor, the typed row whose hint the footer shows, the page of rows
44 * showing, and the rows they belong to: another gate's rows start all three
45 * afresh.
46 */
47type State = { cursor: number; hint: string | null; page: number; rows: string }
48
49/** The prompt's own border, so the rule reads as the gate's top edge. */
50const RULE = 'promptBorder'
51/** The blue-violet the prompt and its dialogs already ask in. */
52const ACCENT = 'permission'
53const HOVERED = 'selectionBg'
54const PICKED = 'diffAddedDimmed'
55
56const GLYPH = '◆'.padEnd(GLYPH_COLUMN)
57const NO_GLYPH = ' '.repeat(GLYPH_COLUMN)
58const RULE_CELL = '─'
59const CURSOR = '▌'.padEnd(GUTTER)
60const NO_CURSOR = ' '.repeat(GUTTER)
61
62/**
63 * What the listeners read, rather than what they closed over: they are
64 * registered once, on the first draw, and a redraw can hand this instance
65 * another gate's rows.
66 */
67let shown: {
68 gate: Gate
69 lines: readonly Line[]
70 columns: number
71 sends: Sends
72 maxRows: number
73} = {
74 gate: { question: '', statement: '', options: [], typed: [] },
75 lines: [],
76 columns: 0,
77 sends: NO_SENDS,
78 maxRows: Infinity,
79}
80
81/**
82 * The footer follows the last click: a typed row's hint, else the answer
83 * held or picked, else the one a new gate kept from sending.
84 */
85function footerOf(
86 hint: string | null,
87 picked: string | null,
88 { held, dropped }: Sends,
89): Footer {
90 if (hint !== null) {
91 return { kind: 'typed', label: hint }
92 }
93
94 if (held !== null) {
95 return { kind: 'queued', answer: held }
96 }
97
98 if (picked !== null) {
99 return { kind: 'picked', answer: picked }
100 }
101
102 return dropped === null ? IDLE : { kind: 'dropped', answer: dropped }
103}
104
105export default function GateBoard(
106 { gate, picked, held, dropped, columns, maxRows }: Props,
107 surface: ClientSurface<State>,
108): RenderElement {
109 const { Box, Text } = surface.elements
110
111 if (surface.state === undefined) {
112 listen(surface)
113 }
114
115 const sends = { held, dropped }
116 const rows = JSON.stringify(gate.options)
117 const cursor = startingRow(gate.options)
118 const state =
119 surface.state?.rows === rows
120 ? surface.state
121 : {
122 cursor,
123 hint: null,
124 page: pageOf(gate, columns, sends, maxRows, cursor),
125 rows,
126 }
127
128 if (state !== surface.state) {
129 surface.setState(state)
130 }
131
132 const footer = footerOf(state.hint, picked, sends)
133 const lines = linesOf(gate, columns, footer, sends, maxRows, {
134 page: state.page,
135 })
136 const pickedRow = gate.options.findIndex(
137 option => answerOf(option) === (held ?? picked),
138 )
139
140 shown = { gate, lines, columns, sends, maxRows }
141
142 const styled = (run: Run, color?: string, backgroundColor?: string) =>
143 Text({
144 color: run.accent === true ? ACCENT : color,
145 backgroundColor,
146 bold: run.bold,
147 dimColor: run.dim,
148 italic: run.italic,
149 strikethrough: run.strikethrough,
150 underline: run.underline,
151 children: run.text,
152 })
153
154 const row = (line: RowLine) => {
155 const isOption = line.kind === 'option'
156 const isCursor = isOption && line.index === state.cursor
157 const backgroundColor =
158 isOption && line.index === pickedRow
159 ? PICKED
160 : isCursor
161 ? HOVERED
162 : undefined
163
164 return Text({
165 children: [
166 Text({
167 color: ACCENT,
168 backgroundColor,
169 children: isCursor ? CURSOR : NO_CURSOR,
170 }),
171 ...line.key.map(run =>
172 styled(run, isOption ? ACCENT : undefined, backgroundColor),
173 ),
174 ...line.runs.map(run => styled(run, undefined, backgroundColor)),
175 ],
176 })
177 }
178
179 const pager = (line: PagerLine) =>
180 Text({
181 children: [
182 Text({ children: NO_CURSOR }),
183 ...pagerRuns(line).map(run =>
184 styled(run, run.dim === true ? undefined : ACCENT),
185 ),
186 ],
187 })
188
189 const draw = (line: Line): RenderElement => {
190 switch (line.kind) {
191 case 'rule':
192 return Text({
193 color: RULE,
194 children: RULE_CELL.repeat(Math.max(1, columns)),
195 })
196 case 'blank':
197 return Text({ children: ' ' })
198 case 'prose':
199 return Text({
200 children: [
201 line.glyph
202 ? Text({ color: ACCENT, bold: true, children: GLYPH })
203 : Text({ children: NO_GLYPH }),
204 ...line.runs.map(run => styled(run)),
205 ],
206 })
207 case 'footer':
208 return Text({
209 children: [
210 Text({ children: NO_CURSOR }),
211 ...line.runs.map(run => styled(run)),
212 ],
213 })
214 case 'pager':
215 return pager(line)
216 default:
217 return row(line)
218 }
219 }
220
221 return Box({ flexDirection: 'column', children: lines.map(draw) })
222}
223
224/**
225 * Keys while the band has the focus, and the pointer over the rows: both move
226 * the cursor and press a row; a click on a typed row shows its hint, and one
227 * on the pager turns the page.
228 */
229function listen(surface: ClientSurface<State>) {
230 const update = (state: State, change: Partial<State>) => {
231 const next = { ...state, ...change }
232
233 if (
234 next.cursor !== state.cursor ||
235 next.hint !== state.hint ||
236 next.page !== state.page
237 ) {
238 surface.setState(next)
239 }
240 }
241
242 const pageHolding = (cursor: number) =>
243 pageOf(shown.gate, shown.columns, shown.sends, shown.maxRows, cursor)
244
245 // The page follows the cursor onto a row it does not show.
246 const moveTo = (state: State, cursor: number) =>
247 update(state, { cursor, page: pageHolding(cursor) })
248
249 const turnTo = (state: State, page: number) => {
250 const { gate, columns, sends, maxRows } = shown
251 const first = firstOnPage(gate, columns, sends, maxRows, page)
252
253 update(state, { page, cursor: first ?? state.cursor })
254 }
255
256 const press = (state: State, index: number) => {
257 const option = shown.gate.options[index]
258
259 if (option !== undefined) {
260 update(state, { cursor: index, hint: null, page: pageHolding(index) })
261 surface.post({ answer: answerOf(option) })
262 }
263 }
264
265 const within = (x: number, span: { from: number; to: number }) =>
266 x >= span.from && x < span.to
267
268 surface.onKey(({ key }) => {
269 const state = surface.state
270 const count = shown.gate.options.length
271
272 if (state === undefined || count === 0) {
273 return
274 }
275
276 if (key === 'up') {
277 moveTo(state, (state.cursor - 1 + count) % count)
278 } else if (key === 'down') {
279 moveTo(state, (state.cursor + 1) % count)
280 } else if (key === 'return') {
281 press(state, state.cursor)
282 } else {
283 press(
284 state,
285 shown.gate.options.findIndex(option => option.key === key),
286 )
287 }
288 })
289
290 surface.onPointer(event => {
291 const state = surface.state
292 const line = shown.lines[event.y]
293
294 if (state === undefined || line === undefined) {
295 return
296 }
297
298 if (line.kind === 'pager' && event.type === 'down') {
299 if (within(event.x, PAGER_SPANS.previous) && line.page > 0) {
300 turnTo(state, line.page - 1)
301 } else if (
302 within(event.x, PAGER_SPANS.next) &&
303 line.page < line.pages - 1
304 ) {
305 turnTo(state, line.page + 1)
306 }
307 } else if (line.kind === 'option' && event.type === 'down') {
308 press(state, line.index)
309 } else if (line.kind === 'option' && event.type === 'move') {
310 update(state, { cursor: line.index })
311 } else if (line.kind === 'typed' && event.type === 'down') {
312 update(state, { hint: shown.gate.typed[line.index]?.label ?? null })
313 }
314 })
315}
316hooks/position.ts 75 lines1/**
2 * The conversation's position as the engine records it in the conversation's
3 * folder (domain/position.cjs), and the word the spinner says for it.
4 */
5
6/** Where the conversation is working: a work unit, its phase and topic, the task in flight. */
7export type Position = {
8 name: string
9 phase?: string
10 topic?: string
11 task?: string
12}
13
14/** What each phase's work is, as the spinner says it. */
15const PHASE_WORDS: ReadonlyMap<string, string> = new Map([
16 ['discovery', 'Shaping'],
17 ['research', 'Researching'],
18 ['experiment', 'Experimenting'],
19 ['discussion', 'Discussing'],
20 ['investigation', 'Investigating'],
21 ['scoping', 'Scoping'],
22 ['specification', 'Specifying'],
23 ['planning', 'Planning'],
24 ['implementation', 'Implementing'],
25 ['review', 'Reviewing'],
26])
27
28/** What the project-level places' work is, as the spinner says it. */
29const PLACE_WORDS: ReadonlyMap<string, string> = new Map([
30 ['roadmap', 'Roadmapping'],
31 ['baseline', 'Assessing'],
32])
33
34const isPosition = (value: unknown): value is Position =>
35 typeof value === 'object' &&
36 value !== null &&
37 typeof (value as Position).name === 'string'
38
39/** The position a kept file's text states; null where it does not read as one. */
40export function positionOf(text: string): Position | null {
41 try {
42 const kept: unknown = JSON.parse(text)
43
44 return isPosition(kept) ? kept : null
45 } catch {
46 return null
47 }
48}
49
50/**
51 * The spinner's word for a position: its phase's work, the task in flight
52 * with it; a project-level place's own; none at a work unit's menu.
53 */
54export function wordFor(position: Position | null): string | null {
55 if (position === null) {
56 return null
57 }
58
59 const { name, phase, task } = position
60
61 if (phase === undefined) {
62 return PLACE_WORDS.get(name) ?? null
63 }
64
65 const word = PHASE_WORDS.get(phase)
66
67 if (word === undefined) {
68 return null
69 }
70
71 return phase === 'implementation' && typeof task === 'string'
72 ? `${word} task ${task}`
73 : word
74}
75