SLOPSHOPPER

agent-state

Shows the state of Claude (working, permission, input, idle, background, compacting) in the iTerm2 tab subtitle.

guardprocess
v0.1.5MITupdated 2026-10-24M-i-k-e-l/agent-state
A shopper browsing a rack in a slop shop
README

agent-state

A Claude Code mod that shows what Claude is doing in the iTerm2 tab subtitle, so a glance at the tab bar tells which session needs you.

iTerm2 only. In any other terminal the mod writes nothing and reports nothing.

Requires macOS, iTerm2 and Claude Code 2.1.296, the version it was tested on. The hooks API it uses is early access and may change between releases.

The tab showsMeaning
⚙️ workingMain agent is running
🔐 permissionA permission dialog is waiting for you, the main agent's or a subagent's
❓ inputA question dialog is waiting for you
💤 idle Oct 10 12:40Nothing is running, since that time
💤 idle … ⏳1Waiting for you, with a background command still running
🧵 backgroundMain agent is idle, a subagent is running
📦 compactingThe conversation is being compacted
(blank)The session ended

Set up

  1. Install the mod:
   /plugin install agent-state --marketplace M-i-k-e-l/agent-state
  1. In iTerm2, open Settings → Profiles → General and set the profile's Subtitle to:
   \(user.claudeState)
  1. Start a new Claude Code session. The tab shows 💤 idle, and ⚙️ working once you send a prompt.

What it reads

The mod reads Claude Code's tool_decision telemetry records to see the moment you approve a permission dialog; no other event says so. It reads them and changes none, and it sends nothing anywhere. This is why claude plugin validate prints "hooks telemetry for: collector". It works with DISABLE_TELEMETRY=1 set.

How it works

The mod writes the state to the tab's terminal as an iTerm2 user variable, user.claudeState, which the Subtitle shows. It starts a short shell process only when the state changes, about two for each prompt you send.

Limits

  • After you approve with "always allow", or if the approval record is missing, the tab may stay on 🔐 until the approved tool ends.
  • An interrupted /compact may leave 📦 until the next event (untested).
  • If something else changes the tab's variable, the tab stays wrong until the state next changes.
  • A claude -p or SDK session shows nothing unless AGENT_STATE_HEADLESS is set.
  • A session moved to the background (/background) blanks the tab, and the tab you attach it from stays blank until the state next changes.
  • A dialog Claude Code opens by itself at the prompt, such as "Teach auto mode about your environment?", leaves the tab as it was: no event a mod may read says it is up.
  • Claude Code on a Linux machine, reached over SSH from iTerm2, shows nothing (read from the code, not tried).
  • Not tried: tmux inside iTerm2, and a permission dialog in auto mode.

Development

Load the mod from a checkout by setting CLAUDE_CODE_PLUGIN_DIRS to its folder in the env block of ~/.claude/settings.json. Saving a file reloads the mod in every open session; a session that is working then shows 💤 until its next prompt.

Checks: claude plugin validate ., claude plugin test ., and tsc -p . once Claude Code has loaded the mod and written .claude-plugin/types/.

When checking by hand, stay in manual mode for a whole test: it is the easiest way to get a permission dialog.

Two environment variables, both unset by default:

VariableEffect when set
AGENT_STATE_LOGNames a file; the mod appends one line to it for each write it attempts, and repeats
AGENT_STATE_HEADLESSLets a session with no person at the prompt (claude -p, the SDK) write to the tab too

A claude -p run stays silent by default because one started from inside another session's tool call would write over that session's tab.

Design notes, with the signal for each state and the by-hand test table: docs/design.md.

License

MIT

Source 1 files
hooks/register.ts 296 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3// Shows Claude's state in the iTerm2 tab through the user variable the profile's
4// Subtitle reads: \(user.claudeState). Only an event that changes what the tab
5// shows starts a process.
6
7const VAR = 'claudeState'
8
9const WORKING = '⚙️ working'
10const PERMISSION = '🔐 permission'
11const INPUT = '❓ input'
12const IDLE = '💤 idle'
13const BACKGROUND = '🧵 background'
14const COMPACTING = '📦 compacting'
15const CLEARED = ''
16
17// $1 variable, $2 the state, $3 "1" to stamp the state with the date and time,
18// $4 the tty a write before this one found, or empty, $5 log line, $6 "1" when no
19// person is at the prompt (a -p run or the SDK), $7 text to put after the stamp, or empty.
20// The child has no controlling terminal of its own, so without $4 the tty is found
21// by walking up the process tree to the first ancestor that has one (claude, then
22// its shell). Prints the tty it used, for the next write to pass back. Exits 0 when
23// the state reached the tab, 2 when this session has no tab to write to and never
24// will, so the module stops asking, and 1 for any other failure.
25// Logs the write when the environment variable AGENT_STATE_LOG names a file.
26// A session with no person at the prompt writes only when AGENT_STATE_HEADLESS is
27// set: started from inside another session's tool, it would write over that
28// session's tab.
29// A session moved to the background (/background) goes on in a process whose environment
30// names no terminal at all, only the iTerm2 profile it was started under (observed).
31// A write that lands inside Claude Code's own title write is taken as title text and
32// lost (observed), so a write that went out is sent again half a second later, unless
33// a newer one has gone out to that tty since: the mark file names the latest.
34const EMIT = `
35case "$TERM_PROGRAM$LC_TERMINAL" in *iTerm*) iterm=1 ;; *) iterm=0 ;; esac
36if [ -z "$TERM_PROGRAM$LC_TERMINAL" ] && [ -n "$ITERM_PROFILE" ]; then iterm=1; fi
37off=
38if [ "$iterm" = 0 ]; then off='not iTerm2'; fi
39if [ "$6" = 1 ] && [ -z "$AGENT_STATE_HEADLESS" ]; then off='no person at the prompt'; fi
40tty=none
41case "$4" in /dev/*) if [ -w "$4" ]; then tty="$4"; fi ;; esac
42if [ -z "$off" ] && [ "$tty" = none ]; then
43  p=$PPID
44  while [ -n "$p" ] && [ "$p" -gt 1 ]; do
45    t=$(ps -o tty= -p "$p" 2>/dev/null | tr -d ' ')
46    case "$t" in ttys*) if [ -w "/dev/$t" ]; then tty="/dev/$t"; break; fi ;; esac
47    p=$(ps -o ppid= -p "$p" 2>/dev/null | tr -d ' ')
48  done
49fi
50state="$2"
51if [ "$3" = 1 ]; then state="$state $(LC_ALL=C date '+%b %-d %H:%M')"; fi
52if [ -n "$7" ]; then state="$state $7"; fi
53rc=-
54if [ -n "$off" ]; then rc="off, $off"; fi
55if [ -z "$off" ] && [ "$tty" != none ]; then
56  esc=$(printf '\\033]1337;SetUserVar=%s=%s\\007' "$1" "$(printf '%s' "$state" | base64 | tr -d '\\n')")
57  printf '%s' "$esc" > "$tty" 2>/dev/null
58  rc=$?
59fi
60if [ "$rc" = 0 ]; then
61  mark="\${TMPDIR:-/tmp}/agent-state.$(basename "$tty")"
62  printf '%s' "$$" > "$mark"
63  (
64    sleep 0.5
65    if [ "$(cat "$mark" 2>/dev/null)" != "$$" ]; then exit 0; fi
66    printf '%s' "$esc" > "$tty" 2>/dev/null
67    again=$?
68    if [ -n "$AGENT_STATE_LOG" ]; then
69      printf '%s %s again rc=%s\\n' "$(date '+%H:%M:%S')" "\${5%% *}" "$again" >> "$AGENT_STATE_LOG"
70    fi
71  ) </dev/null >/dev/null 2>&1 &
72fi
73if [ -n "$AGENT_STATE_LOG" ]; then
74  printf '%s %s tty=%s wrote=[%s] rc=%s\\n' "$(date '+%H:%M:%S')" "$5" "$tty" "$state" "$rc" >> "$AGENT_STATE_LOG"
75fi
76printf '%s' "$tty"
77if [ -n "$off" ]; then exit 2; fi
78[ "$rc" = 0 ]
79`
80
81const loaded = Date.now()
82let seq = 0
83// One write at a time, in the order the events came: two states written at once
84// could land on the tab in the wrong order.
85let queue: Promise<unknown> = Promise.resolve()
86// The tab's tty, as the script last reported it. It does not change while the
87// process lives; a reload starts it over, and the next write searches again.
88let tty: string | undefined
89// The state the tab shows, as last written with success; undefined after a reload,
90// so the first write after one always goes out.
91let shown: string | undefined
92// Set once the script says this session has no tab to write to: no write is tried
93// again until a reload.
94let isOff = false
95// Whether no person is at the prompt, as session.start said; a reload raises
96// session.start again.
97let isHeadless = false
98// Whether the main agent's turn is running: what a finished tool or compaction
99// goes back to. A tool's end that arrives after an interrupt must not write working.
100let isTurnLive = false
101// The main agent's running turn, by id; undefined between turns and after a reload.
102let liveTurn: string | undefined
103// The background commands in flight, as the main agent's last Stop listed them: one
104// of them may be a server that runs as long as the session, so they add to idle and
105// do not make it background. A turn's start clears the count, since an interrupted
106// turn may raise no Stop to list them again.
107let jobs = 0
108// Every entry of that Stop's list as type:status, subagents too, for the log line.
109let listed = ''
110
111// What idle adds for the background commands in flight: an hourglass and their count.
112const jobsNote = (): string => (jobs === 0 ? '' : `⏳${jobs}`)
113
114// Writes the state to the tab; an event with no state leaves the tab alone, and so
115// does one whose state the tab already shows. A repeated idle keeps its first stamp.
116const emit = ($: EngineInterface, line: string, state: string | undefined): Promise<unknown> => {
117  if (state === undefined || isOff) return Promise.resolve()
118  const at = Date.now() - loaded
119  const note = state === IDLE ? jobsNote() : ''
120  const shows = `${state}${note}`
121  queue = queue.then(async () => {
122    if (shows === shown || isOff) return
123    seq += 1
124    const stamped = `#${seq} +${at}ms ${line}`
125    const stamp = state === IDLE ? '1' : '0'
126    const argv = ['sh', '-c', EMIT, 'sh', VAR, state, stamp, tty ?? '', stamped, isHeadless ? '1' : '0', note]
127    const ran = await $.process.run(argv, { timeoutMs: 5000 }).catch(() => undefined)
128    // A failed search prints "none": caching that would stop every later write.
129    const found = ran?.stdout.trim()
130    if (found?.startsWith('/dev/')) tty = found
131    // A write that failed leaves the tab unknown, so the next one goes out whatever it is.
132    shown = ran?.exitCode === 0 ? shows : undefined
133    if (ran?.exitCode === 2) isOff = true
134  })
135  return queue
136}
137
138// The tool calls in flight, each with the agent that made it: a decision names
139// its call, not its agent.
140const calls = new Map<string, string | undefined>()
141
142// The subagents with a permission dialog put to the person. A dialog of theirs
143// outranks working, background and idle: it is the person the session waits on.
144const waiting = new Set<string>()
145
146const who = (agentId: string | undefined): string => agentId ?? 'main'
147
148// What a running main agent shows.
149const active = (): string => (waiting.size > 0 ? PERMISSION : WORKING)
150
151// The agent statuses that keep the tab on background. A subagent whose turn ended
152// with background work of its own still running is waiting, and reports when that
153// work ends (observed).
154const LIVE = new Set<unknown>(['running', 'pending', 'waiting'])
155
156// What the main agent rests in: background while a subagent of it still runs.
157const resting = async ($: EngineInterface): Promise<string> => {
158  if (waiting.size > 0) return PERMISSION
159  const agents = await $.agent.list().catch(() => [])
160  const live = agents.filter(a => LIVE.has(a.status))
161  return live.length > 0 ? BACKGROUND : IDLE
162}
163
164// The sources of a decision that a person gave at the dialog, for this call alone
165// or with a rule kept for later ones (the first observed, the second from the engine's
166// monitoring docs). A rule, a mode or a hook deciding is not the person answering.
167const BY_PERSON = new Set<unknown>(['user_temporary', 'user_permanent'])
168
169// A subagent's dialog is over when the person approves it, its tool returns or its
170// turn ends: what the tab goes back to, or undefined when that subagent had no dialog up.
171const settled = async ($: EngineInterface, agentId: string): Promise<string | undefined> => {
172  if (!waiting.delete(agentId)) return undefined
173  return isTurnLive ? active() : resting($)
174}
175
176export const register: Register = on => {
177  on('session.start', async ($, e, next) => {
178    const started = await next(e)
179    isHeadless = !e.isInteractive
180    await emit($, `session.start surface=${e.surface} interactive=${e.isInteractive}`, IDLE)
181    return started
182  })
183
184  on('session.end', async ($, e, next) => {
185    // A /clear ends the conversation, not the process, and no session.start follows.
186    jobs = 0
187    listed = ''
188    await emit($, `session.end reason=${e.reason}`, e.reason === 'clear' ? IDLE : CLEARED)
189    return next(e)
190  })
191
192  on('turn.start', async ($, e, next) => {
193    isTurnLive = true
194    liveTurn = e.turnId
195    jobs = 0
196    listed = ''
197    await emit($, `turn.start turn=${e.turnId}`, active())
198    return next(e)
199  })
200
201  on('turn.complete', async ($, e, next) => {
202    // A prompt typed over a running turn starts the new turn before the old one's
203    // end is reported (observed): that late end must not put a working tab to idle.
204    const isCurrent = e.agentId === undefined && (liveTurn === undefined || liveTurn === e.turnId)
205    if (isCurrent) {
206      isTurnLive = false
207      liveTurn = undefined
208    }
209    // A subagent killed with its dialog up ends its turn without its tool returning.
210    const state = isCurrent ? await resting($) : e.agentId !== undefined ? await settled($, e.agentId) : undefined
211    const tasks = isCurrent ? ` jobs=[${listed}]` : ''
212    await emit($, `turn.complete agent=${who(e.agentId)} reason=${e.reason} turn=${e.turnId}${tasks}`, state)
213    return next(e)
214  })
215
216  // The main agent's Stop, raised just before its turn.complete (observed), lists the
217  // background work in flight. Only shells count: a subagent is counted from
218  // $.agent.list(), and a session watching its published artifacts for comments keeps
219  // a monitor running for each (observed).
220  on('classic.Stop', async ($, e, next) => {
221    const tasks = e.background_tasks ?? []
222    jobs = tasks.filter(t => t.type === 'shell').length
223    listed = tasks.map(t => `${t.type}:${t.status}`).join(',')
224    return next(e)
225  })
226
227  on('tool.call', async ($, e, next) => {
228    const tool = String(e.tool)
229    const isMain = e.agentId === undefined
230    calls.set(e.tool_use_id, e.agentId)
231    await emit($, `tool.call> tool=${tool} agent=${who(e.agentId)}`, isMain && tool === 'AskUserQuestion' ? INPUT : undefined)
232    try {
233      const ran = await next(e)
234      calls.delete(e.tool_use_id)
235      const outcome = ran.deny !== undefined ? 'deny' : ran.isError === true ? 'error' : 'ok'
236      const after = e.agentId === undefined ? (isTurnLive ? active() : undefined) : await settled($, e.agentId)
237      await emit($, `tool.call< tool=${tool} agent=${who(e.agentId)} ${outcome}`, after)
238      return ran
239    } catch (error) {
240      calls.delete(e.tool_use_id)
241      const after = e.agentId === undefined ? undefined : await settled($, e.agentId)
242      await emit($, `tool.call! tool=${tool} agent=${who(e.agentId)} threw`, after)
243      throw error
244    }
245  })
246
247  on('session.compact', async ($, e, next) => {
248    const isMain = e.agentId === undefined && e.trigger !== 'precompute'
249    await emit($, `session.compact> trigger=${e.trigger} agent=${who(e.agentId)}`, isMain ? COMPACTING : undefined)
250    try {
251      const compacted = await next(e)
252      const after = isMain ? (isTurnLive ? WORKING : await resting($)) : undefined
253      await emit($, `session.compact< trigger=${e.trigger} ${'skip' in compacted ? 'skipped' : 'done'}`, after)
254      return compacted
255    } catch (error) {
256      await emit($, `session.compact! trigger=${e.trigger} threw`, isMain ? IDLE : undefined)
257      throw error
258    }
259  })
260
261  // Raised when the dialog is put to the person; a tool.check verdict of `ask`
262  // is not, since it also comes when no dialog is shown.
263  // A question put to the person is tool.call's to name, not a permission.
264  // No event of its own says the person approved: the decision record below does,
265  // and failing it the tab stays on permission until the approved tool ends.
266  on('classic.PermissionRequest', async ($, e, next) => {
267    const isPrompt = e.tool_name !== 'AskUserQuestion'
268    // A subagent's dialog is shown too, and remembered: its end is that
269    // subagent's tool returning, which otherwise writes nothing.
270    if (isPrompt && e.agent_id !== undefined) waiting.add(e.agent_id)
271    await emit(
272      $,
273      `classic.PermissionRequest tool=${e.tool_name} agent=${who(e.agent_id)} mode=${e.permission_mode}`,
274      isPrompt ? PERMISSION : undefined,
275    )
276    return next(e)
277  })
278
279  // The engine logs each decision on a tool call for the operator's collector, with
280  // or without one configured (observed): an accept the person gave, of a call in flight,
281  // is the approval of the dialog that is up, the main agent's or a subagent's. An
282  // accept from a rule, a mode or a hook comes with no dialog of its own, and may
283  // come while another call's dialog is up. Read, never changed.
284  on('telemetry.log', { to: 'collector' }, async ($, e, next) => {
285    const isApproval =
286      e.event === 'tool_decision' && e.attributes.decision === 'accept' && BY_PERSON.has(e.attributes.source)
287    const id = isApproval ? e.attributes.tool_use_id : undefined
288    if (typeof id === 'string' && calls.has(id)) {
289      const agentId = calls.get(id)
290      const state = agentId !== undefined ? await settled($, agentId) : isTurnLive ? active() : undefined
291      await emit($, `tool_decision accept call=${id} agent=${who(agentId)}`, state)
292    }
293    return next(e)
294  })
295}
296