SLOPSHOPPER

thimble

A browser workspace beside a Claude Code session for making sense of a corpus of files: chat, files, a canvas of cards and a report. Start it with /thimble in…

guardpromptnetworkagents
★ 21v0.8.0Apache-2.0updated 2026-10-23safety-research/thimble/browser/plugin
A shopper browsing a rack in a slop shop
README

thimble is a Claude Code plugin for making sense of large volumes of agent outputs. It gives Claude tools to cite, visualize and label your data, and gives you an interface to understand and verify Claude's work faster.

[!CAUTION]

  • thimble is in alpha. It changes daily, so expect bugs and rough edges.
  • thimble is not an official Anthropic product.

For feedback, bug reports, or anything else, please reach out to @mjoerke. I would love to hear from you!

https://github.com/user-attachments/assets/4b436c41-40b0-4bf2-bab8-e5dcc3ecee94

Features

  • Cards: interactive graphs of your data, drawn in the terminal, that you can click and ask about. v draws one for the last answer.
  • Citations: every claim points to the code output or file line that shows it, and a second Claude checks each one against your files.
  • Labels (l): records sorted into categories by a rule or a model's reading, which you can open and correct.
  • Coverage (r): how much of the folder Claude has read, and what it never opened.
  • Claims (c): everything the session has concluded, as a map, with why each claim holds and what was corrected. They are found when you ask (f in the pane), or after every reply when you turn that on.
  • Squeeze (s): the last answer, shorter or longer, or with its interpretation and background.
  • Side threads (t): ask about a passage or part of a card without derailing the session.

Installation

With Claude (recommended)

claude "install thimble from https://github.com/safety-research/thimble"

Claude asks whether you want the terminal plugin, the browser workbench, or both, and helps with anything missing. Agents installing thimble: follow CLAUDE.md.

Manual installation

git clone https://github.com/safety-research/thimble
cd thimble
scripts/install.sh

scripts/install.sh --no-browser installs the terminal plugin alone. INSTALL.md covers upgrading from 0.9 and what to do when something does not work.

Usage

Terminal plugin

Run claude in a folder with files you'd like to analyze. thimble is on in every session. Click thimble above the prompt, or run /thimble-settings, to turn features on or off; /plugin turns thimble off.

When thimble does something wrong, /thimble-fix <what should work differently> has Claude change your own copy of thimble. In a shell, thimble file issue N posts fix N as a GitHub issue and thimble file pr N opens a pull request with its code; each shows you the text first.

thimble in the terminal: a card of each agent's activity during the incident, a side thread on one agent, and a reply with checked citations

Browser workbench

Run thimble-browser in a folder of files to open the browser workbench.

the browser workbench answering whether agents reviewed before approving: a chat answer with citations, an agent transcript colored by an activity label, a timeline of every agent's labeled work and approvals, and a table of what each approver ran

Requirements

Claude Code, macOS or Linux, Python 3.10+ and Node.js 22.18+. The browser workbench also needs uv and about 1 GB of disk.

Security & Privacy

thimble is a research prototype. Please report any security issues privately to @mjoerke. The plugin runs inside your Claude Code session: it collects no data of its own, its model calls go through your session, and Claude's card code runs in Anthropic's sandbox runtime with no network.

License

Apache-2.0; see LICENSE.

Source 1 files
hooks/thimble.ts 1133 lines
1// thimble's hooks module: how a click in thimble's browser starts, messages and stops one of thimble's subagents in
2// the analyst's Claude Code session with no turn of main, and how a typed start runs on exactly the model and effort
3// its request names. The server's side is backend/app/module_bridge.py; the tests are thimble.test.ts beside this file.
4//
5// Scope. It acts only in thimble's main and checks that before its first fetch or registration: `isInteractive` first
6// (an open long poll would hold every `claude -p` run open), THIMBLE_NO_MODULE unset, then either THIMBLE_LAUNCHED at
7// session.start (the `thimble` command starts the server first, so the types are in main's first agent listing) or
8// /thimble expanding in this session; then a server named by server.json that accepts its hello for this folder and
9// session (only main's). The module hears of /thimble from skill.prompt for thimble:thimble, or at the end of main's
10// turn from the marker /thimble's own hook leaves, <home>/up/<session>.active (app/cli.py hook_up), written anew at
11// each /thimble: where an organization manages Claude Code (managed settings on the machine, or a Team or Enterprise
12// account), Claude Code seats its built-in security plugin, and skill.prompt passes over the plugins a person installs,
13// while turn.complete still reaches them. Whichever of the two comes first stands for that /thimble; a marker the
14// module has seen (its mtime and size) never turns it on again, and neither does one the session already had when it
15// started, from a /thimble of an earlier run of the session (`claude -c` or --resume, then /thimble again, as the
16// skill.prompt route needs). In a session the launcher did not start, it waits for that server at most
17// ACTIVATE_WAIT_MS after /thimble, then says hello once at the end of each of main's turns; a refused hello, or a folder
18// the server does not know, leaves it idle until the next /thimble. Anywhere else it registers nothing and fetches
19// nothing, and looks at nothing but that marker's file system entry at session.start and once per turn of main's. It
20// starts no process: $.http.fetch only, every request proving the token of server.json and every answer proving it
21// back (app/hook_auth.py), so a process on the port can neither hand it requests nor read them.
22//
23// The file guard (tool.call), from the moment the scope check passes: it refuses a call of a file tool (Read, Edit,
24// Write, MultiEdit, NotebookEdit, Grep, Glob) on thimble's token files, a call of an edit tool on thimble's records or,
25// when the analyst turned corpus edits off, on the corpus, and WebFetch and WebSearch when the analyst turned the web
26// off, with the reason each rule names. The rules come with the roles (GET /api/module/roles, or roles.json in terminal
27// mode: app/userconf.py module_rules); until they come, or when they cannot be fetched, only the token files in
28// thimble's home are refused. The path is compared as spelled and as resolved ($.fs.stat with resolve), so a link to a
29// token file is refused too; Grep and Glob are refused at thimble's home itself. Bash it leaves to the permission mode.
30//
31// What it does once the server accepts it:
32// - registers thimble's roles and thimble:orient-helper from GET /api/module/roles (each with a full model id and an
33//   explicit effort, from Settings); when the server is up at session start this happens inside session.start, so the
34//   types are in main's first agent listing;
35// - asks Claude Code's permission decision for a write it never makes every PLAN_POLL_MS and tells the server when main
36//   went into plan mode or out of it (POST /api/module/mode), which no event of Claude Code's says while main is idle;
37// - holds GET /api/module/next and handles the requests one at a time, in order, so a role's registration and the
38//   spawn that needs it are never split by another request: register (all roles again), spawn (register the role with
39//   the run's values if they differ, $.agent.spawn with no `model`, then the one-line note the server rendered), send
40//   (register if needed, then SendMessage), stop (TaskStop of the agent and of the shells the server names), abort
41//   (the analyst's Stop of main: $.turn.abort of main's running turn, by the id its turn.start carried, answered once
42//   that turn completed or ABORT_WAIT_MS passed, after a TaskStop of each command of that turn the abort moved to the
43//   background, where Esc would have ended it), note ($.session.append). It never starts, sends or stops anything the
44//   server did not ask for;
45// - agent.spawn: an Agent call for one of thimble's roles whose prompt's first line names a typed request, main's or a
46//   subagent's (a subagent of main's own may start thimble's agents, as Claude Code lets a subagent start subagents;
47//   a thread's fork makes none: main makes the call for it, tools._ask_main), gets that request's full model id, and
48//   the agent it starts that request's effort, which turn.step sets on its every request;
49//   a child of such an agent whose type is not thimble's gets the same effort (its model it inherits already). These
50//   hooks never see a run of an agent this module started, which is why clicks register instead;
51// - turn.start and turn.complete of main's own turns: the id of main's running turn, which abort names;
52// - turn.complete: posts the end of each run of an agent it started (POST /api/module/ended), with why it ended and,
53//   for a refusal, what the API said of it, since its other hooks skip those agents;
54// - session.end: on /clear and /resume keeps its poll, waits for the new session id, says hello again under it,
55//   refetches what the workspace's record holds and appends to the new main one note per running thimble agent; on
56//   any other reason it stops polling.
57// Its state lives in this module's memory, which /clear and /resume keep, with subagents.json as the record it
58// refetches at session start and after a change of session; never in $.state, which both commands reset.
59//
60// Terminal mode (THIMBLE_WS names the workspace folder and its trusted/launch.json says `mode: terminal`) has no
61// server, and the module makes no HTTP request there, even when server.json names a live server. Its scope check reads
62// launch.json: terminal mode, and a session that is $.session.id() or one --rekey moved it to (the moves
63// subagents.json records). It reads the roles from trusted/roles.json and registers them again whenever that
64// file changes; it takes the requests addressed to it from subagents.json (entries of `requests` of kind `module`
65// whose `module` is pending, for its session, not past `expires_at`), polling every FILE_POLL_MS, and handles them one
66// at a time as it handles the long poll's; and it writes everything it says to trusted/module.json, which only it
67// writes: its heartbeat every FILE_BEAT_MS, the requests it took, its answers, the ends of the runs it started, main's
68// plan mode as its poll sees it, and what it could not register (backend/app/module_bridge.py has the file's form).
69// After /clear it appends the notes --rekey left for the new main in subagents.json (`module.notes`).
70import type { EngineInterface, Register } from 'claude-code'
71
72type Engine = EngineInterface
73type Json = Record<string, unknown>
74type Effort = string | number
75type Values = { model?: string; effort?: Effort | null }
76type Spec = { name: string; description: string; prompt: string; model?: string; effort?: Effort } & Json
77type Answer = Json
78type Request = { id: string; op: string; args: Json; expires_in?: number }
79type Server = { base: string; token: string }
80type Reply = { status: number; data: Json }
81type Hello = 'ok' | 'wait' | 'refused'
82// what the file guard refuses (userconf.module_rules): absolute paths, each as spelled and as resolved
83type Rules = { private: string[]; records: string[]; corpus: string | null; web_off: boolean; reasons: Record<string, string> }
84
85export const PLUGIN = 'thimble'
86// thimble's roles: each names its own model and effort, so a typed run's effort never goes to one of them
87export const ROLES = ['orientation', 'critic', 'writer', 'view-builder', 'view-reviewer', 'check', 'dev-ticket']
88export const RETRY_MS = 2000 // between hellos while no server accepts one, and after a failed poll
89export const SESSION_WAIT_MS = 10000 // how long /clear's new session id is waited for
90export const SESSION_TICK_MS = 25
91// how long the module waits for a server that accepts its hello after /thimble in a session the launcher did not start:
92// the timeout of /thimble's own hook, which starts the server (hooks.json, UserPromptExpansion)
93export const ACTIVATE_WAIT_MS = 600_000
94const QUICK_MS = 1000 // a poll answered sooner than this with nothing is a server that is stopping
95// how long abort waits for main's turn to complete after $.turn.abort, so that its answer comes once Claude Code has
96// ended the turn
97export const ABORT_WAIT_MS = 3000
98// $.turn.abort's refusal when main's turn had ended already, or was ending (no turn runs, another turn runs, or this
99// one is ending)
100const NO_TURN = /no turn is running|is not the running turn|is already ending/i
101// Claude Code's text when it runs as many subagents as it allows: the Agent tool's, and $.agent.spawn's when as many of
102// this plugin's spawns run as CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS allows ("thimble: $.agent.spawn refused: 2 spawns are
103// running at once", which it throws; live check L19)
104const LIMIT = /concurrent subagent limit|spawns are running at once/i
105const GONE = /is not running|no task found|could not be resumed|no transcript found/i
106const QUEUED = /queued for delivery/i
107const REQUEST_WORD = /[A-Za-z0-9_-]{8,64}/g // a request id on the first line of a typed start's prompt
108const OFF = new Set(['', '0', 'false', 'no', 'off'])
109// Claude Code tells no plugin of a mode change, so the module asks its permission decision for a write it never makes
110// every PLAN_POLL_MS, and plan mode says so in the reason ("Cannot write to … while in plan mode"); the server hears a
111// change at once, not at main's next turn (live check L21)
112export const PLAN_POLL_MS = 2000
113// never written; outside main's folder and every rule of thimble's, whose ask or deny would decide first and say nothing
114// of plan mode
115const PLAN_PROBE = '/tmp/.thimble-plan-probe'
116const PLAN_REASON = /\bplan mode\b/i
117
118// terminal mode (module note)
119export const FILE_POLL_MS = 500 // how often subagents.json and roles.json are looked at
120export const FILE_BEAT_MS = 2000 // the heartbeat in module.json; module_bridge counts a module live while it is fresh
121const KEPT = 64 // the requests taken, the answers and the ends module.json keeps, the newest
122const TYPED_LIVE = new Set(['', 'pending', 'claimed']) // module_bridge.TYPED_LIVE
123const MODULE_KIND = 'module' // subagent_files.MODULE_KIND
124
125// the file guard (module note): the tools whose path it reads, those of them that edit, those that search a folder
126// (their `path`, else the working directory), and the web tools
127const FILE_TOOLS = new Set(['Read', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Grep', 'Glob'])
128const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
129const SEARCH_TOOLS = new Set(['Grep', 'Glob'])
130const WEB_TOOLS = new Set(['WebFetch', 'WebSearch'])
131const PRIVATE_NAMES = ['server.json', 'session.key', 'paired.json', 'links'] // in thimble's home (userconf.module_rules)
132// what a refusal of a token file says before the server's rules came: prompts/tools.md's module-deny-private
133export const PRIVATE_FALLBACK = "thimble refused this call, since it keeps its token files (server.json, session.key, paired.json and the links folder in thimble's home) out of reach of the file tools of its sessions. Do the task without them."
134const REFUSED = 'thimble refused this call.' // a refusal whose reason the rules lack
135
136const isObj = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)
137const text = (v: unknown): string => (typeof v === 'string' ? v : '')
138const roleOf = (type: string): string => (type.startsWith(`${PLUGIN}:`) && ROLES.includes(type.slice(PLUGIN.length + 1)) ? type.slice(PLUGIN.length + 1) : '')
139
140// --------------------------------------------------------------------------------------------------- the proof
141
142const encoder = new TextEncoder()
143
144async function sha256(data: Uint8Array): Promise<Uint8Array> {
145  return new Uint8Array(await crypto.subtle.digest('SHA-256', data))
146}
147
148function hex(bytes: Uint8Array): string {
149  return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('')
150}
151
152/** HMAC-SHA256 as hex, built on crypto.subtle.digest, the one digest this environment offers (app/hook_auth.py sign). */
153export async function hmac(key: string, message: string): Promise<string> {
154  let k = encoder.encode(key)
155  if (k.length > 64) k = await sha256(k)
156  const block = new Uint8Array(64)
157  block.set(k)
158  const body = encoder.encode(message)
159  const inner = new Uint8Array(64 + body.length)
160  inner.set(block.map(b => b ^ 0x36))
161  inner.set(body, 64)
162  const innerHash = await sha256(inner)
163  const outer = new Uint8Array(64 + innerHash.length)
164  outer.set(block.map(b => b ^ 0x5c))
165  outer.set(innerHash, 64)
166  return hex(await sha256(outer))
167}
168
169/** thimble's home: THIMBLE_HOME, else ~/.thimble. */
170async function thimbleHome($: Engine): Promise<string> {
171  const homeDir = (await $.env.get('HOME')) ?? ''
172  const home = (await $.env.get('THIMBLE_HOME')) || `${homeDir}/.thimble`
173  return home.startsWith('~/') ? `${homeDir}${home.slice(1)}` : home
174}
175
176/** <THIMBLE_HOME>/server.json's API base and token (`api`, then `port`, as bin/thimble-mcp reads it); null without. */
177async function findServer($: Engine): Promise<Server | null> {
178  const home = await thimbleHome($)
179  let data: unknown
180  try {
181    data = JSON.parse(await $.fs.read(`${home}/server.json`))
182  } catch {
183    return null
184  }
185  if (!isObj(data) || !text(data.token)) return null
186  const port = Number(data.port)
187  const base = text(data.api) ? text(data.api).replace(/\/+$/, '') : Number.isInteger(port) && port > 0 ? `http://127.0.0.1:${port}` : ''
188  return base ? { base, token: text(data.token) } : null
189}
190
191// --------------------------------------------------------------------------------------------------- the module
192// One State per load of the module (register runs once per load); the functions below take `$` and it. Claude Code's
193// check of a module (claude plugin validate) allows `$` to pass only to plain functions, never to a method.
194
195type Ended = { n: number; agentId: string; answer: string; reason: string; refusal?: Json; at: number }
196type Out = {
197  session: string; version: string; load: string; beat: number; plan: boolean | null; plan_at: number; problem: string
198  taken: string[]; answers: Record<string, Answer>; ended: Ended[]; gone?: boolean
199}
200
201type State = {
202  active: boolean // in thimble's interactive main (the scope check passed) and not ended
203  interactive: boolean // session.start said the session is interactive
204  launched: boolean // the launcher started this session (THIMBLE_LAUNCHED at session.start)
205  armed: boolean // /thimble expanded in this session the launcher did not start, and no hello was refused since
206  expanded: boolean // skill.prompt reported /thimble in main's turn now running, so its marker is not a new /thimble
207  marker: string // the stamp of the last marker /thimble's hook left that the module saw ('' for none)
208  user: string // $HOME, for a path that starts with ~
209  home: string // thimble's home, as spelled
210  homeReal: string // and resolved, '' when it does not resolve
211  rules: Rules | null // what the file guard refuses (null until the scope check passed)
212  file: boolean // terminal mode: the trusted folder, not the server (module note)
213  ws: string // the workspace folder, in terminal mode
214  out: Out // what module.json holds, in terminal mode
215  writing: Promise<void> // module.json's writes, one at a time
216  stamps: Record<string, string> // the files' stamps (mtime and size) as last read, in terminal mode
217  n: number // the ends written to module.json, in terminal mode
218  cwd: string
219  session: string // main's session id, as the server accepted it
220  version: string
221  gen: number // a poll whose generation is past stops
222  server: Server | null
223  roles: Record<string, Spec> // the roles as Settings name them (GET /api/module/roles)
224  registered: Record<string, Spec> // what each role is registered with now
225  efforts: Record<string, Effort> // agent id -> the effort turn.step sets (typed runs and their children)
226  requests: Record<string, { role: string; values: Values }> // typed starts waiting for main's Agent call
227  started: Set<string> // agents this module spawned: their turn.complete is posted
228  queue: Promise<void> // the requests, one at a time
229  helloing: { sid: string; said: Promise<Hello> } | null
230  leaving: string // the session /clear or /resume is taking main away from, until the new one is known
231  plan: boolean | null // whether main's session was in plan mode at the last look, as the server heard it
232  turn: string // main's running model turn: the id its turn.start carried, '' once it completed
233  turnEnded: (() => void)[] // what waits for the end of `turn` (abortTurn)
234}
235
236function fresh(): State {
237  return {
238    active: false, interactive: false, launched: false, armed: false, expanded: false, marker: '', user: '', home: '',
239    homeReal: '', rules: null,
240    cwd: '', session: '', version: '', gen: 0, server: null, roles: {}, registered: {}, efforts: {},
241    requests: {}, started: new Set(), queue: Promise.resolve(), helloing: null, leaving: '', plan: null, turn: '', turnEnded: [],
242    file: false, ws: '', writing: Promise.resolve(), stamps: {}, n: 0,
243    out: { session: '', version: '', load: '', beat: 0, plan: null, plan_at: 0, problem: '', taken: [], answers: {}, ended: [] },
244  }
245}
246
247const where = (m: State): string => new URLSearchParams({ cwd: m.cwd, session: m.session }).toString()
248
249function stop(m: State): void {
250  m.active = false
251  m.gen += 1
252}
253
254/** A refused hello: idle, and in a session the launcher did not start, until the next /thimble. */
255function refuse(m: State): void {
256  stop(m)
257  m.armed = false
258}
259
260// ------------------------------------------------------------------------------------------------ the server
261
262async function call($: Engine, m: State, method: string, path: string, body?: Json): Promise<Reply | null> {
263  const server = m.server ?? (m.server = await findServer($))
264  if (!server) return null
265  // app/hook_auth.py's headers: the nonce's time and the port make the proof good on that port alone, for a few minutes,
266  // once, so a process that holds the recorded port while thimble's server runs on another gains nothing from it
267  const nonce = `${Math.floor(Date.now() / 1000)}.${hex(crypto.getRandomValues(new Uint8Array(16)))}`
268  const port = /:(\d+)$/.exec(server.base)?.[1] ?? '80'
269  const headers: Record<string, string> = { 'x-thimble-nonce': nonce, 'x-thimble-auth': await hmac(server.token, `hook@${port}:${nonce}`) }
270  let payload: string | undefined
271  if (body !== undefined) {
272    headers['content-type'] = 'application/json'
273    payload = JSON.stringify(body)
274  }
275  let r
276  try {
277    r = await $.http.fetch(`${server.base}${path}`, { method, headers, body: payload })
278  } catch {
279    m.server = null // the next call reads server.json again: a restarted server may have another port or token
280    return null
281  }
282  if ((r.headers['x-thimble-proof'] ?? '') !== (await hmac(server.token, `server:${nonce}`))) {
283    m.server = null // not thimble's server: believe nothing it says
284    return null
285  }
286  let data: unknown = {}
287  try {
288    data = r.text ? JSON.parse(r.text) : {}
289  } catch {
290    data = {}
291  }
292  return { status: r.status, data: isObj(data) ? data : {} }
293}
294
295/** One hello per session at a time: 'ok' when the server accepted this session, 'refused' when it never will, else
296 *  'wait'. An answer for a session this module has since left (/clear came meanwhile) counts as 'wait'. */
297function hello($: Engine, m: State, problem = ''): Promise<Hello> {
298  const sid = m.session
299  if (m.helloing && m.helloing.sid === sid && !problem) return m.helloing.said
300  const said = (async (): Promise<Hello> => {
301    const r = await call($, m, 'POST', '/api/module/hello', { cwd: m.cwd, session: sid, version: m.version, problem })
302    if (m.session !== sid || !r) return 'wait'
303    if (r.status === 200 && r.data.ok === true) return 'ok'
304    if (r.status === 403) return sid === m.leaving ? 'wait' : 'refused' // the server moved main first
305    // 404, a folder that is no workspace: /thimble registers the folder before it expands, so after /thimble it did not
306    // open this folder; for the launcher's session, a server that is starting
307    if (r.status === 404) return m.launched ? 'wait' : 'refused'
308    return 'wait'
309  })().finally(() => {
310    if (m.helloing?.said === said) m.helloing = null
311  })
312  if (!problem) m.helloing = { sid, said }
313  return said
314}
315
316async function fetchRoles($: Engine, m: State): Promise<boolean> {
317  const r = await call($, m, 'GET', `/api/module/roles?${where(m)}`)
318  if (!r || r.status !== 200 || !isObj(r.data.roles)) return false
319  const roles: Record<string, Spec> = {}
320  for (const [name, spec] of Object.entries(r.data.roles)) {
321    if (isObj(spec) && text(spec.model) && text(spec.prompt)) roles[name] = { ...spec, name, description: text(spec.description), prompt: text(spec.prompt), background: true } as Spec
322  }
323  m.roles = roles
324  m.rules = parseRules(m, r.data.rules) ?? m.rules
325  return true
326}
327
328/** What subagents.json holds: the per-run efforts, the typed starts, the agents this module started. The notes it
329 *  answers for the running agents are returned, for a new main after /clear or /resume. */
330async function fetchState($: Engine, m: State): Promise<string[]> {
331  if (m.file) {
332    await fetchStateFile($, m)
333    return []
334  }
335  const r = await call($, m, 'GET', `/api/module/state?${where(m)}`)
336  if (!r || r.status !== 200) return []
337  if (isObj(r.data.efforts)) {
338    for (const [id, effort] of Object.entries(r.data.efforts)) {
339      if (typeof effort === 'string' || typeof effort === 'number') m.efforts[id] = effort
340    }
341  }
342  if (isObj(r.data.requests)) {
343    const requests: State['requests'] = {}
344    for (const [id, req] of Object.entries(r.data.requests)) {
345      if (isObj(req) && text(req.role)) requests[id] = { role: text(req.role), values: isObj(req.values) ? (req.values as Values) : {} }
346    }
347    m.requests = requests
348  }
349  if (isObj(r.data.agents)) {
350    for (const [id, agent] of Object.entries(r.data.agents)) if (isObj(agent) && agent.plugin_started === true) m.started.add(id)
351  }
352  return Array.isArray(r.data.notes) ? r.data.notes.filter((n): n is string => typeof n === 'string' && n !== '') : []
353}
354
355async function registerAll($: Engine, m: State): Promise<void> {
356  const problems: string[] = []
357  m.registered = {}
358  for (const [name, spec] of Object.entries(m.roles)) {
359    try {
360      await $.agent.register(spec as Parameters<Engine['agent']['register']>[0])
361      m.registered[name] = spec
362    } catch (err) {
363      problems.push(`${PLUGIN}:${name}: ${String(err)}`)
364    }
365  }
366  if (problems.length) await say($, m, `Claude Code did not register ${problems.join('; ')}`)
367}
368
369/** What the module could not do: in the hello's `problem` (browser mode), or module.json's (terminal mode). */
370async function say($: Engine, m: State, problem: string): Promise<void> {
371  if (!m.file) {
372    await hello($, m, problem)
373    return
374  }
375  m.out.problem = problem
376  await writeOut($, m)
377}
378
379// ------------------------------------------------------------------------------------------------ the session
380
381/** Once the scope check passed (module note): thimble's home as spelled and resolved, and the file guard's rules until
382 *  the server's come (only the token files). */
383async function prepare($: Engine, m: State): Promise<void> {
384  m.user = (await $.env.get('HOME')) ?? ''
385  m.home = normal(m, await thimbleHome($))
386  const st = await $.fs.stat(m.home, { resolve: true }).catch(() => undefined)
387  m.homeReal = st?.realPath ?? ''
388  if (!m.rules) m.rules = fallbackRules(m)
389}
390
391/** The scope check passed (session.start, /thimble, or the end of main's turn after /thimble): hello, roles and
392 *  registrations, then the long poll. A session the launcher did not start waits at most `patience` for a server that
393 *  accepts its hello, then stays idle, armed, until the end of main's next turn. */
394async function begin($: Engine, m: State, cwd: string, patience: number): Promise<void> {
395  await prepare($, m)
396  m.cwd = cwd
397  m.session = await $.session.id()
398  try {
399    const manifest = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`))
400    m.version = isObj(manifest) ? text(manifest.version) : ''
401  } catch {
402    m.version = ''
403  }
404  // a server that is up now: hello, roles and registrations inside session.start, for main's first agent listing
405  const first = await connect($, m)
406  if (first === 'refused') return refuse(m)
407  const gen = m.gen
408  const since = await $.clock.now()
409  void (async () => {
410    let state: Hello = first
411    while (state === 'wait' && m.active && gen === m.gen) {
412      if (!m.launched && (await $.clock.now()) - since >= patience) break
413      await $.clock.sleep(RETRY_MS)
414      state = await connect($, m)
415    }
416    if (gen !== m.gen) return
417    if (state === 'ok') {
418      void watchPlan($, m, gen)
419      await poll($, m, gen)
420    } else if (state === 'refused') refuse(m)
421    else stop(m) // waited `patience` after /thimble: the end of main's next turn says hello again (still armed)
422  })()
423}
424
425/** Every PLAN_POLL_MS: whether main's session is in plan mode now (Claude Code's decision for a write the module never
426 *  makes, PLAN_REASON), posted to the server when it changed. */
427async function watchPlan($: Engine, m: State, gen: number): Promise<void> {
428  while (m.active && gen === m.gen) {
429    await $.clock.sleep(PLAN_POLL_MS)
430    if (!m.active || gen !== m.gen) return
431    let plan: boolean
432    try {
433      const got = await $.tool.check({ tool: 'Write', input: { file_path: PLAN_PROBE, content: '' } } as Parameters<Engine['tool']['check']>[0])
434      plan = PLAN_REASON.test(text((got as Json).reason))
435    } catch {
436      continue
437    }
438    if (plan === m.plan) continue
439    if (m.file) {
440      m.plan = plan
441      m.out.plan = plan
442      m.out.plan_at = Date.now()
443      await writeOut($, m)
444      continue
445    }
446    const r = await call($, m, 'POST', '/api/module/mode', { cwd: m.cwd, session: m.session, plan })
447    if (r?.status === 200) m.plan = plan
448  }
449}
450
451async function connect($: Engine, m: State): Promise<Hello> {
452  const said = await hello($, m)
453  if (said !== 'ok') return said
454  await fetchState($, m)
455  if (await fetchRoles($, m)) await registerAll($, m)
456  else await hello($, m, 'thimble’s module could not fetch the roles it registers')
457  return 'ok'
458}
459
460async function poll($: Engine, m: State, gen: number): Promise<void> {
461  while (m.active && gen === m.gen) {
462    const asked = Date.now()
463    const r = await call($, m, 'GET', `/api/module/next?${where(m)}`)
464    if (!m.active || gen !== m.gen) return
465    if (r?.status === 200 && isObj(r.data.request)) {
466      take($, m, r.data.request as Request)
467      continue
468    }
469    if (r?.status === 204) {
470      // a server holds a poll up to 25 s; one that answers at once is stopping, and is not asked again at once
471      if (Date.now() - asked < QUICK_MS) await $.clock.sleep(RETRY_MS)
472      continue
473    }
474    if (r?.status === 409 && m.leaving && m.session === m.leaving) {
475      await $.clock.sleep(SESSION_TICK_MS) // main is moving: follow says hello under the new id
476      continue
477    }
478    if (r?.status === 409) {
479      // not the accepted session (a server that restarted, or main moved): say hello again
480      const said = await hello($, m)
481      if (said === 'refused') return refuse(m)
482      if (said === 'ok') continue
483    }
484    await $.clock.sleep(RETRY_MS)
485  }
486}
487
488function take($: Engine, m: State, req: Request): void {
489  const received = Date.now()
490  m.queue = m.queue
491    .then(async () => {
492      const late = typeof req.expires_in === 'number' && Date.now() - received > req.expires_in
493      const answer = late ? { error: 'the request expired before thimble’s module reached it' } : await handle($, m, req)
494      await call($, m, 'POST', '/api/module/result', { cwd: m.cwd, session: m.session, id: req.id, answer })
495    })
496    .catch(() => undefined)
497}
498
499async function handle($: Engine, m: State, req: Request): Promise<Answer> {
500  const a = isObj(req.args) ? req.args : {}
501  const values = isObj(a.values) ? (a.values as Values) : undefined
502  try {
503    switch (req.op) {
504      case 'register':
505        if (!(await (m.file ? readRoles($, m) : fetchRoles($, m)))) return { error: 'the roles could not be fetched' }
506        await registerAll($, m)
507        return { ok: true }
508      case 'spawn':
509        return await spawn($, m, text(a.role), text(a.prompt), text(a.description), values, text(a.note))
510      case 'send':
511        return await send($, m, text(a.agent), text(a.text), text(a.role), values)
512      case 'stop':
513        return await stopAgent($, text(a.agent), Array.isArray(a.shells) ? a.shells.map(text).filter(Boolean) : [])
514      case 'abort':
515        return await abortTurn($, m)
516      case 'note':
517        return await note($, text(a.text))
518      default:
519        return { error: `thimble’s module has no op ${req.op}` }
520    }
521  } catch (err) {
522    const why = String(err)
523    return LIMIT.test(why) ? { limit: why } : { error: why }
524  }
525}
526
527/** The role registered with `values` (the run's model and effort) when they differ from its registration now. */
528async function ensure($: Engine, m: State, role: string, values: Values | undefined): Promise<void> {
529  const base = m.roles[role]
530  if (!base) throw new Error(`thimble’s role ${role} is not registered in this session`)
531  const want: Spec = { ...base }
532  if (values && text(values.model)) want.model = text(values.model)
533  if (values && 'effort' in values) {
534    if (values.effort === null || values.effort === undefined || values.effort === '') delete want.effort
535    else want.effort = values.effort
536  }
537  const have = m.registered[role]
538  if (have && have.model === want.model && have.effort === want.effort && have.prompt === want.prompt) return
539  await $.agent.register(want as Parameters<Engine['agent']['register']>[0])
540  m.registered[role] = want
541}
542
543async function spawn($: Engine, m: State, role: string, prompt: string, description: string, values: Values | undefined, line: string): Promise<Answer> {
544  await ensure($, m, role, values)
545  // no `model`: a spawn takes only an alias; the registration carries the full id
546  const r = await $.agent.spawn({ subagentType: `${PLUGIN}:${role}`, prompt, description })
547  if (r.deny !== undefined) return LIMIT.test(r.deny) ? { limit: r.deny } : { deny: r.deny }
548  if (!r.agentId) return { error: 'Claude Code started no agent' }
549  m.started.add(r.agentId)
550  if (line) await note($, line.split('{agent}').join(r.agentId))
551  return { agentId: r.agentId, model: r.model }
552}
553
554async function send($: Engine, m: State, agent: string, message: string, role: string, values: Values | undefined): Promise<Answer> {
555  if (role && m.roles[role]) await ensure($, m, role, values)
556  const r = await $.tool.call({ tool: 'SendMessage', to: agent, message } as Parameters<Engine['tool']['call']>[0])
557  if (r.deny !== undefined) return { deny: r.deny }
558  const said = text(r.text)
559  if (r.isError) return { error: said || 'SendMessage failed', ...(GONE.test(said) ? { gone: true } : {}) }
560  const result = (r as { result?: unknown }).result
561  if (isObj(result) && result.success === false) {
562    const why = text(result.message) || said
563    return { error: why, ...(GONE.test(why) ? { gone: true } : {}) }
564  }
565  return { agentId: agent, text: said, queued: QUEUED.test(said) }
566}
567
568async function stopAgent($: Engine, agent: string, shells: string[] = []): Promise<Answer> {
569  const r = await $.tool.call({ tool: 'TaskStop', task_id: agent } as Parameters<Engine['tool']['call']>[0])
570  // the background shells the agent started, which Claude Code's TaskStop of the agent leaves running; one that has
571  // ended already answers an error, which changes nothing
572  for (const shell of shells) await $.tool.call({ tool: 'TaskStop', task_id: shell } as Parameters<Engine['tool']['call']>[0]).catch(() => undefined)
573  if (r.deny !== undefined) return { deny: r.deny }
574  const said = text(r.text)
575  if (r.isError) return { error: said || 'TaskStop failed', ...(GONE.test(said) ? { gone: true } : {}) }
576  return { agentId: agent, text: said }
577}
578
579/** The analyst's Stop of main: main's running turn ended as Esc in the terminal ends it, with $.turn.abort and the id its
580 *  turn.start carried, answered once the turn completed or ABORT_WAIT_MS passed, and the commands the abort moved to the
581 *  background stopped (stopMoved); `gone` when no turn of main's runs. */
582async function abortTurn($: Engine, m: State): Promise<Answer> {
583  const turn = m.turn
584  if (!turn) return { error: 'main is not running a turn', gone: true }
585  try {
586    await $.turn.abort({ turnId: turn })
587  } catch (err) {
588    const why = String(err)
589    return NO_TURN.test(why) ? { error: why, gone: true } : { error: why }
590  }
591  if (m.turn === turn) await Promise.race([new Promise<void>(resolve => m.turnEnded.push(resolve)), $.clock.sleep(ABORT_WAIT_MS)])
592  await stopMoved($)
593  return { ok: true }
594}
595
596/** Where Esc ends a command that runs, $.turn.abort moves it to the background (Claude Code's backgroundedByTurnAbort on
597 *  the call's stored result), where it runs on and its end starts a new turn of main's (live check L4-12l). Once the
598 *  stopped turn ended, each such command of it, read from main's messages back to the turn's prompt (a user message with
599 *  no tool results), is stopped with TaskStop; one that has ended already answers an error, which changes nothing. */
600async function stopMoved($: Engine): Promise<void> {
601  const rows: unknown = await $.session.messages().catch(() => [])
602  if (!Array.isArray(rows)) return
603  const shells = new Set<string>()
604  for (let i = rows.length - 1; i >= 0; i--) {
605    const row = rows[i]
606    if (!isObj(row)) continue
607    const results = Array.isArray(row.toolResults) ? row.toolResults : []
608    if (row.role === 'user' && !results.length) break
609    for (const one of [...(Array.isArray(row.toolUses) ? row.toolUses : []), ...results]) {
610      const result = isObj(one) ? one.result : undefined
611      if (isObj(result) && result.backgroundedByTurnAbort === true && text(result.backgroundTaskId)) shells.add(text(result.backgroundTaskId))
612    }
613  }
614  for (const shell of shells) await $.tool.call({ tool: 'TaskStop', task_id: shell } as Parameters<Engine['tool']['call']>[0]).catch(() => undefined)
615}
616
617async function note($: Engine, line: string): Promise<Answer> {
618  if (!line) return { error: 'an empty note' }
619  const r = await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: line }] } })
620  return r.deny !== undefined ? { deny: r.deny } : { ok: true }
621}
622
623/** The typed start a prompt's first line names, for `role`: from memory, else from the record fetched again. */
624async function typedStart($: Engine, m: State, prompt: string, role: string): Promise<{ id: string; values: Values } | null> {
625  const words = (prompt.split('\n', 1)[0] ?? '').match(REQUEST_WORD) ?? []
626  if (!words.length) return null
627  const find = () => {
628    for (const id of words) {
629      const req = m.requests[id]
630      if (req && req.role === role) return { id, values: req.values }
631    }
632    return null
633  }
634  const known = find()
635  if (known) return known
636  await fetchState($, m)
637  return find()
638}
639
640/** After /clear or /resume: the new session id, a hello under it, the record again, and a note per running agent. */
641async function follow($: Engine, m: State, old: string): Promise<void> {
642  m.leaving = old
643  let sid = old
644  for (let waited = 0; waited < SESSION_WAIT_MS && sid === old; waited += SESSION_TICK_MS) {
645    await $.clock.sleep(SESSION_TICK_MS)
646    sid = await $.session.id()
647  }
648  if (m.leaving === old) m.leaving = ''
649  if (!m.active || sid === old) return
650  m.session = sid
651  let said = await hello($, m)
652  while (said === 'wait' && m.active && m.session === sid) {
653    await $.clock.sleep(RETRY_MS)
654    said = await hello($, m)
655  }
656  if (said === 'refused') return refuse(m)
657  if (said !== 'ok' || m.session !== sid) return
658  for (const line of await fetchState($, m)) await note($, line)
659}
660
661/** What main's (or an agent's) Agent call starts with: a typed start's model, and the effort its agent and that
662 *  agent's children of no thimble type run at. A typed start is found by the request its prompt's first line names,
663 *  whoever makes the call: main, a subagent of main's own whose start tool call made the request, or the
664 *  orientation for its critic. Never fails the call: a lookup that fails changes nothing. */
665async function spawning($: Engine, m: State, e: { subagentType?: string; parentAgentId?: string; prompt?: string }): Promise<{ model?: string; effort?: Effort; typed?: string }> {
666  try {
667    const type = e.subagentType ?? ''
668    const role = roleOf(type)
669    if (role) {
670      const typed = await typedStart($, m, e.prompt ?? '', role)
671      if (!typed) return {}
672      const effort = typed.values.effort
673      return {
674        typed: typed.id,
675        ...(text(typed.values.model) ? { model: text(typed.values.model) } : {}),
676        ...(effort !== null && effort !== undefined && effort !== '' ? { effort } : {}),
677      }
678    }
679    if (e.parentAgentId && !type.startsWith(`${PLUGIN}:`) && m.efforts[e.parentAgentId] !== undefined) return { effort: m.efforts[e.parentAgentId] }
680  } catch {
681    // the call goes on as Claude Code made it
682  }
683  return {}
684}
685
686// ------------------------------------------------------------------------------------------------ terminal mode
687
688async function readJson($: Engine, path: string): Promise<Json | null> {
689  try {
690    const data = JSON.parse(await $.fs.read(path))
691    return isObj(data) ? data : null
692  } catch {
693    return null
694  }
695}
696
697/** A file's stamp (mtime and size), '' when it is missing. */
698async function stamp($: Engine, path: string): Promise<string> {
699  try {
700    const st = await $.fs.stat(path)
701    return `${st.mtimeMs}:${st.size}`
702  } catch {
703    return ''
704  }
705}
706
707const trusted = (m: State, name: string): string => `${m.ws}/trusted/${name}`
708
709/** Session `sid` followed through the moves --rekey recorded (subagents.json `module.rekeyed`). */
710function movedTo(state: Json, sid: string): string {
711  const moves = isObj(state.module) && isObj(state.module.rekeyed) ? (state.module.rekeyed as Json) : {}
712  const seen = new Set<string>()
713  while (sid && typeof moves[sid] === 'string' && !seen.has(sid)) {
714    seen.add(sid)
715    sid = moves[sid] as string
716  }
717  return sid
718}
719
720/** module.json written whole, one write at a time, with a fresh heartbeat (module note). */
721function writeOut($: Engine, m: State): Promise<void> {
722  m.writing = m.writing
723    .then(async () => {
724      m.out.beat = Date.now()
725      await $.fs.write(trusted(m, 'module.json'), JSON.stringify(m.out))
726    })
727    .catch(() => undefined)
728  return m.writing
729}
730
731async function readRoles($: Engine, m: State): Promise<boolean> {
732  const got = await readJson($, trusted(m, 'roles.json'))
733  if (!got || !isObj(got.roles)) return false
734  const roles: Record<string, Spec> = {}
735  for (const [name, spec] of Object.entries(got.roles)) {
736    if (isObj(spec) && text(spec.model) && text(spec.prompt)) roles[name] = { ...spec, name, description: text(spec.description), prompt: text(spec.prompt), background: true } as Spec
737  }
738  m.roles = roles
739  m.rules = parseRules(m, got.rules) ?? m.rules
740  return true
741}
742
743/** module_bridge._efforts: the per-run efforts of the typed starts and their children of no thimble type, then the
744 *  record's own. */
745function effortsOf(state: Json): Record<string, Effort> {
746  const agents = isObj(state.agents) ? Object.entries(state.agents).filter((x): x is [string, Json] => isObj(x[1])) : []
747  const out: Record<string, Effort> = {}
748  for (const [id, e] of agents) {
749    const effort = isObj(e.values) ? e.values.effort : undefined
750    if (text(e.type).startsWith(`${PLUGIN}:`) && !e.plugin_started && (typeof effort === 'string' || typeof effort === 'number') && effort !== '') out[id] = effort
751  }
752  for (let changed = true; changed;) {
753    changed = false
754    for (const [id, e] of agents) {
755      const parent = text(e.parent)
756      if (!(id in out) && parent in out && !text(e.type).startsWith(`${PLUGIN}:`)) {
757        out[id] = out[parent]
758        changed = true
759      }
760    }
761  }
762  if (isObj(state.efforts)) for (const [id, v] of Object.entries(state.efforts)) if ((typeof v === 'string' || typeof v === 'number') && v !== '') out[id] = v
763  return out
764}
765
766/** What fetchState fetches in browser mode, from subagents.json: the per-run efforts, the typed starts waiting for an
767 *  Agent call (module_bridge._typed), the agents this module started. */
768async function fetchStateFile($: Engine, m: State): Promise<Json> {
769  const state = (await readJson($, trusted(m, 'subagents.json'))) ?? {}
770  Object.assign(m.efforts, effortsOf(state))
771  const requests: State['requests'] = {}
772  for (const table of ['pending', 'requests']) {
773    if (!isObj(state[table])) continue
774    for (const [id, r] of Object.entries(state[table] as Json)) {
775      if (!isObj(r) || r.route !== 'typed' || (text(r.kind) || 'start') !== 'start' || !TYPED_LIVE.has(text(r.state))) continue
776      requests[text(r.id) || id] = { role: text(r.role).replace(/^thimble:/, ''), values: isObj(r.values) ? (r.values as Values) : {} }
777    }
778  }
779  m.requests = requests
780  if (isObj(state.agents)) for (const [id, a] of Object.entries(state.agents)) if (isObj(a) && a.plugin_started === true) m.started.add(id)
781  return state
782}
783
784/** Terminal mode's start (module note): the scope check against launch.json, the roles from roles.json, the record,
785 *  module.json, then the poll of the files and the plan poll. */
786async function fileBegin($: Engine, m: State, cwd: string, ws: string, launch: Json): Promise<void> {
787  m.file = true
788  m.ws = ws.replace(/\/+$/, '')
789  m.cwd = cwd
790  await prepare($, m)
791  m.session = await $.session.id()
792  const state = (await readJson($, trusted(m, 'subagents.json'))) ?? {}
793  if (!text(launch.session) || movedTo(state, text(launch.session)) !== m.session) return stop(m)
794  try {
795    const manifest = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`))
796    m.version = isObj(manifest) ? text(manifest.version) : ''
797  } catch {
798    m.version = ''
799  }
800  m.out = { ...m.out, session: m.session, version: m.version, load: hex(crypto.getRandomValues(new Uint8Array(8))), gone: false }
801  await fetchStateFile($, m)
802  m.stamps.roles = await stamp($, trusted(m, 'roles.json'))
803  if (await readRoles($, m)) await registerAll($, m)
804  else m.out.problem = 'thimble’s module could not read the roles it registers (trusted/roles.json)'
805  await writeOut($, m)
806  const gen = m.gen
807  void watchPlan($, m, gen)
808  void pollFiles($, m, gen)
809}
810
811/** Every FILE_POLL_MS: roles.json registered again when it changed, the requests subagents.json addresses to this
812 *  module taken when it changed, and the heartbeat every FILE_BEAT_MS (module note). */
813async function pollFiles($: Engine, m: State, gen: number): Promise<void> {
814  let beat = Date.now()
815  while (m.active && gen === m.gen) {
816    try {
817      const roles = await stamp($, trusted(m, 'roles.json'))
818      if (roles && roles !== m.stamps.roles) {
819        m.stamps.roles = roles
820        if (await readRoles($, m)) {
821          m.queue = m.queue.then(() => registerAll($, m)).catch(() => undefined)
822          await m.queue
823        }
824      }
825      const state = await stamp($, trusted(m, 'subagents.json'))
826      if (state && state !== m.stamps.state) {
827        m.stamps.state = state
828        await takeFile($, m)
829      }
830      if (Date.now() - beat >= FILE_BEAT_MS) {
831        beat = Date.now()
832        await writeOut($, m)
833      }
834    } catch {
835      // the next look tries again
836    }
837    await $.clock.sleep(FILE_POLL_MS)
838  }
839}
840
841/** The requests subagents.json addresses to this module that it has not taken, oldest first, each taken (module.json
842 *  `taken`) and handled in turn, its answer written under its id. */
843async function takeFile($: Engine, m: State): Promise<void> {
844  const state = await readJson($, trusted(m, 'subagents.json'))
845  if (!state || !isObj(state.requests)) return
846  const now = Date.now()
847  const mine = Object.entries(state.requests)
848    .filter((x): x is [string, Json] => isObj(x[1]) && x[1].kind === MODULE_KIND && x[1].module === 'pending' && !m.out.taken.includes(x[0])
849      && (!text(x[1].session) || text(x[1].session) === m.session) && typeof x[1].expires_at === 'number' && x[1].expires_at * 1000 > now)
850    .sort((a, b) => Number(a[1].asked_at ?? 0) - Number(b[1].asked_at ?? 0))
851  if (!mine.length) return
852  m.out.taken = [...m.out.taken, ...mine.map(([id]) => id)].slice(-KEPT)
853  await writeOut($, m)
854  for (const [id, r] of mine) {
855    const req: Request = { id, op: text(r.op), args: isObj(r.args) ? r.args : {} }
856    const due = Number(r.expires_at) * 1000
857    m.queue = m.queue
858      .then(async () => {
859        const answer = Date.now() > due ? { error: 'the request expired before thimble’s module reached it' } : await handle($, m, req)
860        const answers = { ...m.out.answers, [id]: answer }
861        m.out.answers = Object.fromEntries(Object.entries(answers).slice(-KEPT))
862        await writeOut($, m)
863      })
864      .catch(() => undefined)
865  }
866}
867
868/** After /clear or /resume in terminal mode: the new session id, the move --rekey recorded to it, module.json under it,
869 *  the record again, and the notes --rekey left for the new main (subagents.json `module.notes`). */
870async function followFile($: Engine, m: State, old: string): Promise<void> {
871  let sid = old
872  for (let waited = 0; waited < SESSION_WAIT_MS && sid === old; waited += SESSION_TICK_MS) {
873    await $.clock.sleep(SESSION_TICK_MS)
874    sid = await $.session.id()
875  }
876  if (!m.active || sid === old) return
877  let state: Json = {}
878  for (let waited = 0; waited < SESSION_WAIT_MS; waited += RETRY_MS / 4) {
879    state = (await readJson($, trusted(m, 'subagents.json'))) ?? {}
880    if (movedTo(state, old) === sid) break
881    await $.clock.sleep(RETRY_MS / 4)
882  }
883  if (movedTo(state, old) !== sid) {
884    stop(m) // no record says the new session is main's: idle, as a refused hello leaves it
885    return
886  }
887  m.session = sid
888  m.out.session = sid
889  await writeOut($, m)
890  await fetchStateFile($, m)
891  const notes = isObj(state.module) && isObj(state.module.notes) ? (state.module.notes as Json) : {}
892  if (text(notes.session) === sid && Array.isArray(notes.lines)) {
893    for (const line of notes.lines) if (typeof line === 'string' && line) await note($, line)
894  }
895}
896
897// ------------------------------------------------------------------------------------------------ the file guard
898
899/** A path made absolute against the working directory, `~` read as $HOME, `.`, `..` and repeated slashes folded. */
900function normal(m: State, path: string): string {
901  let p = path.trim()
902  if (p === '~') p = m.user
903  else if (p.startsWith('~/')) p = `${m.user}${p.slice(1)}`
904  if (!p.startsWith('/')) p = `${m.cwd}/${p}`
905  const parts: string[] = []
906  for (const part of p.split('/')) {
907    if (part === '' || part === '.') continue
908    if (part === '..') parts.pop()
909    else parts.push(part)
910  }
911  return `/${parts.join('/')}`
912}
913
914/** Whether `path` is one of `roots` or inside one. */
915function under(path: string, roots: string[]): boolean {
916  return roots.some(r => {
917    const root = r.replace(/\/+$/, '')
918    return root !== '' && (path === root || path.startsWith(`${root}/`))
919  })
920}
921
922/** Where a path lands, every link followed: its own realPath, else its folder's with its name (a file not there yet);
923 *  '' when neither resolves. */
924async function placed($: Engine, path: string): Promise<string> {
925  const own = await $.fs.stat(path, { resolve: true }).catch(() => undefined)
926  if (own?.realPath) return own.realPath
927  const cut = path.lastIndexOf('/')
928  const dir = await $.fs.stat(cut > 0 ? path.slice(0, cut) : '/', { resolve: true }).catch(() => undefined)
929  return dir?.realPath ? `${dir.realPath.replace(/\/+$/, '')}/${path.slice(cut + 1)}` : ''
930}
931
932/** The rules before the server's: the token files in thimble's home, as spelled and as resolved. */
933function fallbackRules(m: State): Rules {
934  const homes = [m.home, m.homeReal].filter((h, i, all) => h !== '' && all.indexOf(h) === i)
935  return { private: homes.flatMap(h => PRIVATE_NAMES.map(n => `${h}/${n}`)), records: [], corpus: null, web_off: false, reasons: { private: PRIVATE_FALLBACK } }
936}
937
938/** The rules GET /api/module/roles or roles.json carries (userconf.module_rules), with the token files of thimble's
939 *  home as this module sees it kept; null when there are none. */
940function parseRules(m: State, v: unknown): Rules | null {
941  if (!isObj(v)) return null
942  const paths = (x: unknown): string[] => (Array.isArray(x) ? x.filter((p): p is string => typeof p === 'string' && p.startsWith('/')) : [])
943  const base = fallbackRules(m)
944  const reasons: Record<string, string> = { ...base.reasons }
945  if (isObj(v.reasons)) for (const [key, why] of Object.entries(v.reasons)) if (text(why)) reasons[key] = text(why)
946  return {
947    private: [...new Set([...base.private, ...paths(v.private)])],
948    records: paths(v.records),
949    corpus: text(v.corpus).startsWith('/') ? text(v.corpus) : null,
950    web_off: v.web_off === true,
951    reasons,
952  }
953}
954
955/** The path a file tool's call names: Grep's and Glob's `path`, else the working directory; the others' `file_path`
956 *  or `notebook_path`. '' for no file tool, or none named. */
957function pathOf(m: State, e: Json): string {
958  const tool = text(e.tool)
959  if (!FILE_TOOLS.has(tool)) return ''
960  return SEARCH_TOOLS.has(tool) ? text(e.path) || m.cwd : text(e.file_path) || text(e.notebook_path)
961}
962
963const reason = (rules: Rules, kind: string): string => rules.reasons[kind] || (kind === 'private' ? PRIVATE_FALLBACK : REFUSED)
964
965/** Why the file guard refuses the call (module note), '' when it does not. */
966async function refusal($: Engine, m: State, e: Json): Promise<string> {
967  const tool = text(e.tool)
968  if (WEB_TOOLS.has(tool)) {
969    if (!m.rules) await prepare($, m)
970    const rules = m.rules ?? fallbackRules(m)
971    return rules.web_off ? reason(rules, 'web') : ''
972  }
973  const raw = pathOf(m, e)
974  if (!raw) return ''
975  if (!m.rules) await prepare($, m)
976  const rules = m.rules ?? fallbackRules(m)
977  const spelled = normal(m, raw)
978  const real = await placed($, spelled)
979  const paths = real && real !== spelled ? [spelled, real] : [spelled]
980  const homes = [m.home, m.homeReal].filter(Boolean)
981  if (paths.some(p => under(p, rules.private) || (SEARCH_TOOLS.has(tool) && homes.includes(p)))) return reason(rules, 'private')
982  if (!EDIT_TOOLS.has(tool)) return ''
983  if (paths.some(p => under(p, rules.records))) return reason(rules, 'records')
984  if (rules.corpus !== null && paths.some(p => under(p, [rules.corpus as string]))) return reason(rules, 'data')
985  return ''
986}
987
988/** For the guard's catch, with no file system call: whether the call names a token file as spelled. */
989function namesPrivate(m: State, e: Json): boolean {
990  const raw = m.active ? pathOf(m, e) : ''
991  if (!raw) return false
992  const p = normal(m, raw)
993  const rules = m.rules ?? fallbackRules(m)
994  return under(p, rules.private) || (SEARCH_TOOLS.has(text(e.tool)) && [m.home, m.homeReal].filter(Boolean).includes(p))
995}
996
997const moduleOn = async ($: Engine): Promise<boolean> => OFF.has(((await $.env.get('THIMBLE_NO_MODULE')) ?? '').trim().toLowerCase())
998
999/** The stamp of this session's marker, <home>/up/<session>.active as app/cli.py hook_marker_path names it; '' for none. */
1000async function markerStamp($: Engine): Promise<string> {
1001  const name = (await $.session.id()).replace(/[^A-Za-z0-9_-]/g, '')
1002  return name ? await stamp($, `${await thimbleHome($)}/up/${name}.active`) : ''
1003}
1004
1005/** At the end of main's turn: whether /thimble's hook left a marker for this session that the module has not seen
1006 *  (module note), and no skill.prompt reported the same /thimble in this turn. With THIMBLE_NO_MODULE it looks at
1007 *  nothing. */
1008async function expanded($: Engine, m: State): Promise<boolean> {
1009  const reported = m.expanded
1010  m.expanded = false
1011  if (!(await moduleOn($))) return false
1012  const seen = await markerStamp($)
1013  if (!seen || seen === m.marker) return false
1014  m.marker = seen
1015  return !reported
1016}
1017
1018export const register: Register = on => {
1019  const m = fresh()
1020
1021  on('session.start', async ($, e, next) => {
1022    const r = await next(e)
1023    m.cwd = e.cwd
1024    m.interactive = e.isInteractive === true
1025    // the scope check, before any fetch or registration: interactive first, then launched by thimble (else idle until
1026    // /thimble, skill.prompt), module not off
1027    if (!e.isInteractive) return r
1028    if (!(await $.env.get('THIMBLE_LAUNCHED'))) {
1029      // a marker the session already has is a /thimble of an earlier run of it (claude -c, --resume), which a resumed
1030      // session types again, as for skill.prompt: it counts as seen (module note)
1031      if (await moduleOn($)) m.marker = await markerStamp($)
1032      return r
1033    }
1034    if (!(await moduleOn($))) return r
1035    m.launched = true
1036    // terminal mode: THIMBLE_WS's launch.json says so (module note); browser mode otherwise
1037    const ws = (await $.env.get('THIMBLE_WS')) ?? ''
1038    const launch = ws ? await readJson($, `${ws}/trusted/launch.json`) : null
1039    if (ws && launch === null) return r // a workspace the launcher named whose launch.json cannot be read: idle
1040    m.active = true
1041    if (launch !== null && launch.mode === 'terminal') await fileBegin($, m, e.cwd, ws, launch)
1042    else await begin($, m, e.cwd, 0)
1043    return r
1044  })
1045
1046  // /thimble in a session the launcher did not start turns the module on, in that session only (module note)
1047  on('skill.prompt', async ($, e, next) => {
1048    const r = await next(e)
1049    if (e.skill !== `${PLUGIN}:thimble`) return r
1050    m.expanded = true // its marker, at the end of this turn, is this /thimble
1051    if (m.interactive && !m.launched && !m.active && (await moduleOn($))) {
1052      m.active = true
1053      m.armed = true
1054      void begin($, m, m.cwd, ACTIVATE_WAIT_MS)
1055    }
1056    return r
1057  })
1058
1059  on('tool.call', async ($, e, next) => {
1060    if (!m.active) return next(e)
1061    const why = await refusal($, m, e as unknown as Json)
1062    return why ? { deny: why } : next(e)
1063  }).catch(($, e, next) => (next.called ? next(e) : namesPrivate(m, e as unknown as Json) ? { deny: reason(m.rules ?? fallbackRules(m), 'private') } : next(e)))
1064
1065  on('agent.spawn', async ($, e, next) => {
1066    if (!m.active) return next(e)
1067    const got = await spawning($, m, e)
1068    const r = await next(got.model ? { ...e, model: got.model } : e)
1069    if (r.agentId) {
1070      if (got.effort !== undefined) m.efforts[r.agentId] = got.effort
1071      if (got.typed) delete m.requests[got.typed]
1072    }
1073    return r
1074  }).catch(($, e, next) => next(e)) // not a guard: if it fails, the call goes on as Claude Code made it
1075
1076  on('turn.step', async function* ($, e, next) {
1077    const effort = m.active && e.agentId !== undefined ? m.efforts[e.agentId] : undefined
1078    // a request with no effort is to a model without one, which takes none
1079    return yield* next(effort !== undefined && e.effort !== undefined ? { ...e, effort: effort as typeof e.effort } : e)
1080  })
1081
1082  // main's own turns, whatever the scope check found, so that a stop of main names the turn that runs (abortTurn)
1083  on('turn.start', async ($, e, next) => {
1084    const r = await next(e)
1085    if (e.agentId === undefined) m.turn = e.turnId
1086    return r
1087  })
1088
1089  on('turn.complete', async ($, e, next) => {
1090    const r = await next(e)
1091    if (e.agentId === undefined && e.turnId === m.turn) {
1092      m.turn = ''
1093      for (const ended of m.turnEnded.splice(0)) ended()
1094    }
1095    if (m.active && e.agentId !== undefined && m.started.has(e.agentId)) {
1096      const refusal = e.reason === 'refusal' && isObj(e.refusal) ? { refusal: e.refusal } : {}
1097      if (m.file) {
1098        m.out.ended = [...m.out.ended, { n: ++m.n, agentId: e.agentId, answer: text(e.answer), reason: text(e.reason), ...refusal, at: Date.now() }].slice(-KEPT)
1099        void writeOut($, m)
1100      } else {
1101        void call($, m, 'POST', '/api/module/ended', { cwd: m.cwd, session: m.session, agentId: e.agentId, answer: e.answer, reason: e.reason, ...refusal })
1102      }
1103    } else if (e.agentId === undefined && m.interactive && !m.launched) {
1104      if ((await expanded($, m)) && !m.active) {
1105        // /thimble's marker, where skill.prompt passed over this plugin: what skill.prompt does (module note)
1106        m.active = true
1107        m.armed = true
1108        void begin($, m, m.cwd, ACTIVATE_WAIT_MS)
1109      } else if (m.armed && !m.active) {
1110        // after /thimble, once the wait for the server ended: one hello at the end of each of main's turns (module note)
1111        m.active = true
1112        void begin($, m, m.cwd, 0)
1113      }
1114    }
1115    return r
1116  })
1117
1118  on('session.end', async ($, e, next) => {
1119    const r = await next(e)
1120    if (e.reason !== 'clear' && e.reason !== 'resume') m.armed = false
1121    if (!m.active) return r
1122    if (e.reason === 'clear' || e.reason === 'resume') void (m.file ? followFile($, m, e.sessionId) : follow($, m, e.sessionId))
1123    else {
1124      stop(m)
1125      if (m.file) {
1126        m.out.gone = true
1127        await writeOut($, m)
1128      }
1129    }
1130    return r
1131  })
1132}
1133