SLOPSHOPPER

tiller

tiller node mod: inbox delivery, band, toasts and commands

bandrowscommandtoastnetworktimer
★ 3v0.1.0no licenseupdated 2026-10-24swicken/tiller/mod
A shopper browsing a rack in a slop shop
README

tiller mod

Per-node Claude Code mod. It does nothing unless TL_NODE_ID is set (with TL_ENDPOINT, TL_TOKEN_FILE, optional TL_PARENT_ID). Every second it polls the daemon: /tree (the caller's whole tree, root first) feeds the band and toasts, and /inbox messages are delivered. While a turn runs (from turn.start to its turn.complete) a message stays held in the daemon so its sender can still withdraw it; once the turn ends the mod claims it with POST /claim (a withdrawn or expired message fails the claim and is skipped), submits it with $.prompt.submit and acks it with POST /ack once the prompt is accepted. A failed ack (the daemon restarting, say) is retried on each poll until it succeeds or the message has left the inbox (the UserPromptSubmit hook acked it, or it was retired); a submitted message is never submitted again, since the daemon would accept a second claim from a Claude mod. A steer (send with mode "now") is not held: the mod claims it, aborts the running turn with $.turn.abort and submits it at once. Should a turn.complete never arrive, the hold is released once /tree has shown this node done on two polls in a row. It forwards turn.start, turn.complete and session.measure to /mod-event. It draws a one-line band above the prompt (in a child, ↑ parent and ⌂ root buttons; the needs-you child), and in-session toasts for children that need you, finish or error. The tree and node controls live in the app, not in Claude. The mod is silent while a tiller client is attached. Every /tree and /inbox response carries X-TL-Clients: app,browser (the kinds of authenticated ws clients now connected, empty when none); when it is non-empty the mod keeps a quiet state atom true, the AbovePrompt hook passes through, and it makes no toasts and no $.ui.log lines, because the client's sidebar already shows all of it. Inbox delivery, acks, event forwarding and slash commands carry on. When the last client disconnects the band and toasts return, and the first diff after that is a baseline so changes made while quiet are not replayed. In the chat each tiller message is one dim line: a received envelope (a prompt this plugin submitted whose text parses as a frame, nonce matched on its start and end lines) as ↘ message from <sender> · steer · reply-to <id> (the · steer and · reply-to <id> parts are each omitted when absent, and a daemon notice with reply-to: none has no reply-to part), and the agent's own mcp__tiller__send call as ↗ message to <title> (<id>) · <outcome>, its result block hidden unless the outcome is other than queued or delivered. ctrl+o (or --verbose, or an export, or a surface that does not say whether a tool row is expanded) draws them in full; an errored or interrupted send is never compacted. These UserMessage, ToolUse and ToolResult render hooks change the drawing alone: the stored prompt and what the model reads are untouched. The outcome is the one the call returned (usually queued), not later delivery. The received row is drawn by a second plugin, tiller-rows in ../mod-rows/, not by this one: Claude Code skips a plugin's own hooks on everything its own $.prompt.submit raised, the row's ui.render included (the debug log says tiller@inline ui.render skipped: re-entry (the plugin's own code raised it; origin tiller)), so a UserMessage hook here never runs for the messages this plugin delivers. The props it gets, logged live on 2.1.310, are { text, origin: { kind: 'plugin', name: 'tiller', asUser: true }, isExpanded, onScreen? }, text being the frame as submitted. The plugin test kit does not apply that skip, so a UserMessage test here would pass while the session ignores the hook. The send hooks do run in this plugin, with the props they expect, but in a live 2.1.310 terminal session the send call folded into a tool group line (Called tiller), where no ToolUse row is drawn, so they ran only in the ctrl+o transcript, where isExpanded is true and they pass. The daemon loads it by launching claude --plugin-dir <repo>/mod --plugin-dir <repo>/mod-rows ... with the TL_* variables in the environment. Commands: /tl-list, /tl-spawn <title> :: <prompt>, /tl-send <nodeId> <text>, /tl-read <nodeId>. The four call the daemon's POST /api/<tool> with the node's token and print the text result. The band's ↑ parent and ⌂ root buttons POST /focus {id} (any node in the same tree); the daemon broadcasts it and a tl client showing that node switches to the target. Source is TypeScript under hooks/: register.tsx holds everything that uses $; api.ts, notify.ts, commands.ts, rows.ts and band.tsx are pure helpers (the validator forbids passing $ to imported functions). Check with claude plugin validate mod/ and claude plugin test mod/, and the same for mod-rows/; the quiet behaviour, the hold during a turn and the ack retry are tested against a stub daemon in mod/tests/quiet.test.tsx, mod/tests/hold.test.tsx and mod/tests/ack.test.tsx, and the compact rows in mod/tests/rows.test.tsx (send) and mod-rows/tests/rows.test.tsx (received). The mod sends no OS notifications: the daemon is the single sender (see docs/frontends.md), so the app and the terminal never both notify.

Source 7 files
hooks/register.tsx 158 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3import type { Child } from '../types'
4import { parse, request, type Ctx } from './api'
5import { Band } from './band'
6import { COMMANDS, parseSend, parseSpawn } from './commands'
7import { changes } from './notify'
8import { sendResult, sentLine } from './rows'
9
10// tiller per-node mod. Inert unless TL_NODE_ID is set. Contract: src/shared/protocol.ts "Mod-facing HTTP API".
11const kids = atom({ plugin: 'tiller', key: 'children' } as const, [] as Child[])
12const pend = atom({ plugin: 'tiller', key: 'pending' } as const, 0)
13// True while any tiller client (app or browser) is attached: its sidebar makes everything the mod draws redundant.
14const quietAtom = atom({ plugin: 'tiller', key: 'quiet' } as const, false)
15let quiet = false
16let ctx: Ctx | undefined
17let parent: string | undefined, busy = false
18// The running turn's id, from turn.start; unknown after a hot reload mid-turn, when messages are submitted as before.
19let turn: string | undefined, endedTurn: string | undefined
20let prev: Child[] | null = null
21const inflight = new Set<string>()
22// Submitted but not yet acked: only the ack is retried (each poll), never the submit; the daemon would accept a second claim.
23const unacked = new Set<string>()
24const lastToast = new Map<string, number>()
25
26async function call($: any, method: string, path: string, body?: unknown) {
27  const [url, init] = request(ctx!, method, path, body)
28  return parse(path, await $.http.fetch(url, init))
29}
30
31async function tool($: any, name: string, args: unknown): Promise<string> {
32  try { const r = await call($, 'POST', `/api/${name}`, args); return r.text ?? (r.data === undefined ? '(no output)' : JSON.stringify(r.data)) } catch (err) { return `error: ${err}` }
33}
34
35async function focus($: any, id: string, label: string) {
36  try { await call($, 'POST', '/focus', { id }); $.ui.toast(`→ ${label}`) } catch (err) { $.ui.toast(`tiller: focus failed: ${err}`) }
37}
38
39async function ack($: any, id: string) {
40  try {
41    await call($, 'POST', '/ack', { id })
42    unacked.delete(id)
43    inflight.delete(id)
44  } catch (err) {
45    if (!unacked.has(id) && !quiet) $.ui.log(`tiller: ack ${id} failed, retrying: ${err}`)
46    unacked.add(id)
47  }
48}
49
50function forward($: any, event: string, payload: unknown) {
51  if (ctx) call($, 'POST', '/mod-event', { event, payload }).catch(() => {})
52}
53
54// At most one toast per key per 5 s. OS notifications are the daemon's job, not the mod's.
55async function notify($: any, key: string, text: string) {
56  const now = await $.clock.now()
57  if (quiet || now - (lastToast.get(key) ?? 0) < 5000) return
58  lastToast.set(key, now)
59  $.ui.toast(text)
60}
61
62async function poll($: any) {
63  if (busy) return
64  busy = true
65  try {
66    const [url, init] = request(ctx!, 'GET', '/tree')
67    const res = await $.http.fetch(url, init)
68    const list: Child[] = parse('/tree', res)
69    const q = !!res.headers['x-tl-clients']
70    if (q !== quiet) {
71      quiet = q
72      if (!q) prev = null // what changed while quiet is not news: the next diff is a baseline
73      await update($, quietAtom, () => q)
74    }
75    await update($, kids, () => list)
76    // Should a turn.complete never reach this hook (another plugin's hook answering without next), messages would be held
77    // until they expire; so release the hold once the daemon has seen this turn end on two polls in a row.
78    const ended = turn !== undefined && list.find(c => c.self)?.state === 'done'
79    if (ended && endedTurn === turn) turn = undefined
80    endedTurn = ended ? turn : undefined
81    if (prev) for (const c of changes(prev, list)) await notify($, c.key, c.text)
82    prev = list
83    const all: any[] = await call($, 'GET', '/inbox')
84    const msgs = all.filter(m => !inflight.has(m.id)) // before the retries below take acked ids out of inflight
85    for (const id of unacked) {
86      // Gone from the inbox: acked by the UserPromptSubmit hook, or retired. Otherwise retry the ack.
87      if (all.some(m => m.id === id)) await ack($, id)
88      else { unacked.delete(id); inflight.delete(id) }
89    }
90    await update($, pend, () => inflight.size + msgs.length)
91    for (const m of msgs) {
92      // While a turn runs, hold a message in the daemon so its sender can still withdraw it; a steer goes now.
93      if (turn && !m.steer) continue
94      inflight.add(m.id)
95      try { await call($, 'POST', '/claim', { id: m.id }) } catch { inflight.delete(m.id); continue } // withdrawn or expired
96      if (m.steer && turn) await $.turn.abort({ turnId: turn }).catch(() => {}) // the turn may have just ended
97      await notify($, `msg:${m.from}`, `message from ${m.from}`)
98      // submit resolves once the prompt is accepted (session idle); ack after that.
99      $.prompt.submit({ text: m.text, asUser: true }).then(
100        () => ack($, m.id),
101        (err: unknown) => { inflight.delete(m.id); if (!quiet) $.ui.log(`tiller: deliver ${m.id} failed: ${err}`) })
102    }
103  } catch (err) { if (!quiet) $.ui.log(`tiller: poll error ${err}`) } finally { busy = false }
104}
105
106export const register: Register = on => {
107  on('session.start', async ($, e, next) => {
108    const id = await $.env.get('TL_NODE_ID')
109    if (!id) return next(e)
110    const token = (await $.fs.read((await $.env.get('TL_TOKEN_FILE'))!)).trim()
111    ctx = { id, endpoint: (await $.env.get('TL_ENDPOINT'))!, token }
112    parent = (await $.env.get('TL_PARENT_ID')) || undefined
113    for (const [name, description] of COMMANDS) await $.command.register({ name, description })
114    $.clock.every(1000, () => poll($))
115    return next(e)
116  })
117
118  on('turn.start', ($, e, next) => { turn = e.turnId; forward($, 'turn.start', e); return next(e) })
119  on('turn.complete', ($, e, next) => { if (turn === e.turnId) turn = undefined; forward($, 'turn.complete', e); return next(e) })
120  on('session.measure', ($, e, next) => { forward($, 'session.measure', e); return next(e) })
121
122  on('command.run', { command: 'tl-list' }, async $ => ({ text: await tool($, 'list_nodes', {}) }))
123  on('command.run', { command: 'tl-spawn' }, async ($, e) => {
124    const a = parseSpawn(e.args)
125    if (!a) return { text: 'usage: /tl-spawn <title> :: <prompt>' }
126    return { text: await tool($, 'spawn', { kind: 'claude', cwd: (await $.env.get('PWD')) || '.', ...a }) }
127  })
128  on('command.run', { command: 'tl-send' }, async ($, e) => {
129    const a = parseSend(e.args)
130    return { text: a ? await tool($, 'send', a) : 'usage: /tl-send <nodeId> <text>' }
131  })
132  on('command.run', { command: 'tl-read' }, async ($, e) => {
133    const nodeId = e.args.trim()
134    return { text: nodeId ? await tool($, 'read', { nodeId, what: 'summary' }) : 'usage: /tl-read <nodeId>' }
135  })
136
137  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
138    if (!ctx || (await read($, quietAtom))) return next(e)
139    const id = ctx.id
140    return Band($.ui.resolve(e), id, await read($, kids), await read($, pend), parent, (to, label) => focus($, to, label))
141  })
142
143  // Received messages are drawn by the tiller-rows plugin (mod-rows/): the engine skips this plugin's hooks on rows its own submit made.
144  on('ui.render', { component: 'ToolUse', props: { tool: 'mcp__tiller__send' } }, async ($, e, next) => {
145    // isExpanded is optional here: a surface that does not say (an export) draws in full.
146    if (e.props.isExpanded !== false || e.props.isErrored || e.props.isInterrupted) return next(e)
147    const { Text } = $.ui.resolve(e)
148    return <Text dimColor wrap="truncate-end">{sentLine(e.props.input, e.props.output, e.props.isRunning, await read($, kids))}</Text>
149  })
150  // The outcome is on the call's own line, so its result block draws nothing until expanded; a failed send's shows its reason.
151  on('ui.render', { component: 'ToolResult', props: { tool: 'mcp__tiller__send' } }, async ($, e, next) => {
152    const outcome = sendResult(e.props.output)?.outcome
153    if (e.props.isExpanded !== false || e.props.isErrored || (outcome !== 'queued' && outcome !== 'delivered')) return next(e)
154    const { Box } = $.ui.resolve(e)
155    return <Box />
156  })
157}
158
hooks/api.ts 17 lines
1// Pure helpers for talking to the daemon; register.tsx does the actual $.http.fetch.
2export type Ctx = { id: string; endpoint: string; token: string }
3
4export const request = (c: Ctx, method: string, path: string, body?: unknown): [string, { method: string; headers: Record<string, string>; body?: string }] => [
5  `${c.endpoint}${path}`,
6  {
7    method,
8    headers: { Authorization: `Bearer ${c.token}`, 'X-TL-Node': c.id, 'Content-Type': 'application/json' },
9    body: body === undefined ? undefined : JSON.stringify(body),
10  },
11]
12
13export const parse = (path: string, r: { ok: boolean; status: number; text: string }) => {
14  if (!r.ok) throw new Error(`${path}: ${r.status} ${r.text}`)
15  return r.text ? JSON.parse(r.text) : undefined
16}
17
hooks/band.tsx 21 lines
1import type { Child } from '../types'
2import { needsYou } from './notify'
3export type Els = { Box: any; Text: any; Button: any }
4
5/** One line above the prompt. In a child the parent (and, when different, the root) is a button that focuses it. */
6export function Band({ Box, Text, Button }: Els, id: string, list: Child[], pending: number, parentId: string | undefined, focus: (id: string, label: string) => void) {
7  const rootId = list[0] && !list[0].self ? list[0].id : undefined
8  const me = list.find(c => c.self)
9  const needy = list.filter(c => !c.self && needsYou(c))
10  const first = needy[0], k = needy.length
11  return (
12    <Box columnGap={1}>
13      <Text dimColor wrap="truncate-end">tiller · {me?.title ?? id} ·{parentId ? '' : ' parent none'}</Text>
14      {parentId && <Button plain key="parent" onPress={() => focus(parentId, 'parent')}>↑ parent</Button>}
15      {rootId && rootId !== parentId && <Button plain key="root" onPress={() => focus(rootId, 'root')}>⌂ root</Button>}
16      {first && <Text color="yellow" wrap="truncate-end">· ! {first.title} [{first.id.slice(-4)}]{k > 1 ? ` +${k - 1}` : ''}</Text>}
17      {pending > 0 && <Text dimColor>· {pending} pending</Text>}
18    </Box>
19  )
20}
21
hooks/commands.ts 16 lines
1export const COMMANDS: [string, string][] = [
2  ['tl-list', 'List tiller nodes'],
3  ['tl-spawn', 'Spawn a child: <title> :: <prompt>'], ['tl-send', 'Send a message: <nodeId> <text>'],
4  ['tl-read', 'Read a node summary: <nodeId>'],
5]
6
7export const parseSpawn = (args: string) => {
8  const [title, prompt] = args.split('::').map(s => s.trim())
9  return title ? { title, prompt: prompt || undefined } : undefined
10}
11
12export const parseSend = (args: string) => {
13  const [nodeId, ...text] = args.trim().split(/\s+/)
14  return nodeId && text.length ? { nodeId, text: text.join(' ') } : undefined
15}
16
hooks/notify.ts 19 lines
1import type { Child } from '../types'
2
3// Same rule as needsYou in src/shared/protocol.ts, which the mod cannot import.
4export const needsYou = (c: Child) => !c.exited && (c.state === 'blocked' || c.state === 'waiting')
5export const kind = (c: Child) => (c.errored ? 'error' : needsYou(c) ? 'needs' : c.state === 'done' ? 'done' : '')
6
7/** Toasts for descendants whose kind changed since `prev`. */
8export function changes(prev: Child[], list: Child[]) {
9  const out: { key: string; text: string }[] = []
10  for (const c of list) {
11    if (c.self) continue
12    const was = prev.find(p => p.id === c.id)
13    const k = kind(c)
14    if (!was || !k || kind(was) === k) continue
15    out.push({ key: c.id, text: k === 'done' ? `${c.title} finished` : k === 'error' ? `${c.title} errored` : `${c.title} needs you` })
16  }
17  return out
18}
19
hooks/rows.ts 20 lines
1// The agent's own send call as one transcript row. Display only: the tool call stays as it was.
2
3/** The send call's result, from the JSON the daemon's MCP server returns as a text block; undefined while it runs or when unreadable. */
4export function sendResult(output: unknown): { outcome: string; steer?: boolean } | undefined {
5  const blocks = Array.isArray(output) ? output : [output]
6  for (const b of blocks) {
7    const text = typeof b === 'string' ? b : typeof b?.text === 'string' ? b.text : undefined
8    try { const o = text && JSON.parse(text); if (typeof o?.outcome === 'string') return { outcome: o.outcome, steer: o.steer === true } } catch {}
9  }
10  return undefined
11}
12
13export function sentLine(input: unknown, output: unknown, isRunning: boolean, titles: { id: string; title: string }[]): string {
14  const nodeId = (input as { nodeId?: unknown } | null)?.nodeId
15  const id = typeof nodeId === 'string' ? nodeId : '?'
16  const title = titles.find(c => c.id === id)?.title
17  const r = isRunning ? { outcome: 'sending' } : sendResult(output)
18  return `↗ message to ${title ? `${title} (${id})` : id}${r?.steer ? ' · steer' : ''}${r ? ` · ${r.outcome}` : ''}`
19}
20
types/index.d.ts 12 lines
1export type Child = {
2  id: string; title: string; depth: number; state: string; activity?: string
3  ageSec: number; lastMessage?: string; unread: boolean; errored?: boolean; exited?: boolean
4  self?: boolean; parentId?: string | null
5}
6
7declare module 'claude-code' {
8  interface PluginState {
9    tiller: { children: Child[]; pending: number; quiet: boolean }
10  }
11}
12