Your own local Claude Tag, in the Claude app, Discord, Telegram, or a custom Claude Code channel.

<a href="../../LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT License" /></a> <a href="https://code.claude.com/docs/en/plugins"><img src="https://img.shields.io/badge/Claude%20Code-plugin-orange.svg" alt="Claude Code Plugin" /></a> <a href="CHANGELOG.md"><img src="https://img.shields.io/badge/version-1.4.22-green.svg" alt="Version 1.4.22" /></a> <img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/gtapps/hermitd/_gh_traffic_stats/.github/badges/clones.json" alt="Downloads" /> <img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" alt="PRs Welcome" /> <a href="https://discord.gg/54sJqAxhUh"><img src="https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white" alt="Join" /></a>
Run an always-on Claude Code agent on your own machine, for you or your team. Start sessions from your chat in any project it can reach, on the model and effort you choose, and steer them through the agent or take over in the Claude app or CLI.
Use it from your terminal or the Claude app via Remote Control, or connect Discord, Telegram, iMessage, or a custom Claude Code channel.
Give it ongoing responsibilities: maintain research, monitor systems, run routines, and follow up on unfinished work. Between requests, it checks those responsibilities, carries progress across sessions, and reaches you when something needs attention.
Run it on your Claude subscription and extend it with your own MCP servers, skills, and plugins.
It's Claude Code. hermitd is a plugin for the official Claude Code CLI, which runs as Anthropic ships it. New Claude models, features, and fixes work as soon as Claude Code supports them.
<img src="assets/cover.png" alt="Always-on Claude Code agent" />
<a id="quick-start"></a>
Choose one installation method below. Run it from the folder where you want your agent, empty or existing. Uses your Claude subscription on Linux, macOS, or Windows via WSL2. See prerequisites.
With Claude Code 2.1.308+ and Bun 1.4+ installed:
claude plugin install hermitd --marketplace gtapps/hermitd --scope local
claude "/hermitd:hatch"
Prepares Claude Code, Bun, and tmux, installs the plugin, and launches setup:
curl -fsSL https://gtapps.github.io/hermitd/install.sh | bash
Both options set up the agent in this folder. Hatch guides you through the agent’s purpose and preferences, then shows how to start it. Choose Quick for defaults you can adjust later.
After setup, follow the printed next steps to start your agent.
Run in a persistent tmux session:
hermitd start
Requires tmux. The watchdog recovers failed sessions while your machine stays on. Claude Code's /sandbox is recommended for unattended use. To connect a chat, run /hermitd:channel-setup as directed by the setup handoff.
Run the guided setup in Claude Code:
/hermitd:docker-setup
Builds and starts the container, then walks you through authentication and channel pairing. Requires Docker Compose v2.
Customize the container. Ask the agent to add tools, packages, or services to its Docker setup. For example: “Add ffmpeg to the container.”
Optional Docker security controls cover local-network access, DNS policy, resource limits, and plugin installation auditing.
raw/ into maintained knowledge in compiled/, alongside Claude Code's auto memory. /recall searches past sessions, knowledge, proposals, and captured channel conversations.Part of your project channel. With passive mode, the agent saves incoming group messages to look back on later, and wakes when someone you allow @mentions it. It also remembers instructions for that channel. Fixed policies you set for a chat change only through an approval prompt, and an optional scheduled review proposes rule updates when the same correction keeps coming up.
Work that belongs to a chat. Routines, watches, and reminders created from a chat report back to that chat. A team chat lists and edits its own routines, and changing one it does not own asks for approval. Third-party channel plugins can join in: a small send script gives them proactive notices and routine chats, and Docker approves them for you.
<a id="configure-it"></a>
Tune from a terminal with /hermit-settings, or change permitted settings from a trusted connected chat. Every write is validated and recorded in a redacted audit ledger; /hermit-settings history [setting] shows what changed. Some of the settings available:
| Key | Default / options (default bold) |
|---|---|
agent_name | your assistant's name |
operator_profile | primary-chat audience: technical / non-technical |
timezone | detected during setup; fallback UTC |
language | detected during setup; fallback en |
escalation | how much it does before asking: conservative / balanced / autonomous |
model | session model: sonnet |
effort | session reasoning effort: unset (Claude Code default) |
permission_mode | how freely the unattended agent acts: auto |
AGENT_HOOK_PROFILE | guardrail profile: minimal / standard (interactive) / strict (always-on) |
channels | Discord / Telegram / iMessage / third-party channel plugins (+ allowed_users) |
channels.primary | which channel gets outbound pings |
channels.<name>.maintainer_channel_id | optional separate chat for technical alerts, diagnostics, and usage details |
push_notifications | native/mobile push on alerts: true |
remote | remote control; false also requires approval for cross-machine peer messages; true |
ask_gate | route unattended questions to a paired channel: true |
budget | optional daily / weekly / monthly caps; alert or binding pause action |
artifacts | dashboard / proposals / weekly review: dashboard and proposals enabled |
heartbeat.enabled | timed idle sweeps: true |
heartbeat.every | idle sweep cadence: 30m |
heartbeat.active_hours | active window: 08:00–23:00 |
heartbeat.model / heartbeat.effort | heartbeat evaluator: haiku at high |
routines | persistent routines managed via /hermit-routines |
monitors | persistent background watches managed via /watch |
scheduled_checks | session-triggered skills at task completion |
reflection.graduation_min_sessions | proposal recurrence bar: 1 |
quality_gate.tier | post-change cleanup spend: budget / balanced / quality |
knowledge.compiled_budget_chars | fresh/resumed startup catalog budget: 2500 |
knowledge.raw_retention_days | raw/ retention: 14 |
knowledge.working_set_warn | warn above N compiled docs: 20 |
auto_session | auto-start session on boot: true |
boot_skill / shutdown_skill | custom boot / teardown skill |
context_hygiene.clear | safe-boundary context clear: enabled, quiet 1h, max age 24h, minimum 20,000 tokens |
context_hygiene.compact | compact long-running active context: enabled, 100000 compactible tokens / 4h cooldown |
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE | auto-compact at % of context: 65 |
MAX_THINKING_TOKENS | thinking-token cap per turn: 10000 |
watchdog.scheduler_enabled | OS scheduler for the watchdog tick: true on tmux always-on (auto-installed at boot); false or hermitd-watchdog uninstall opts out |
watchdog.enabled | recovery/restart tier: false until first scheduler registration (or /docker-setup); hygiene still runs |
Full schema in the Config Reference
Your own prompt. Replace the agent's built-in prompt and rules with .hermit/resident-prompt.md, and spawned helpers' with .hermit/helper-prompt.md. Delete the file to return to the shipped prompt. See Replacing the resident prompt.
Artifacts. The agent uses Claude Code Artifacts to provide an interactive dashboard and custom pages generated on demand that you can view, interact with, and share. Ask it to build your own personalized agent dashboard.
Ask for an update from your terminal or connected chat:
| Command | What it gives you |
|---|---|
/brief | Current status and a summary of recent work. |
/recall | Search past sessions, knowledge, proposals, and captured conversations. |
/hermit-health | Alerts, routines, channels, blockers, and recent learnings. |
/hermit-doctor | Diagnostics for the installation, runtime, scheduling, credentials, and permissions. |
/hermit-evolution | Cost trends, proposal activity, routines, and what the agent has produced over time. |
/cost-reflect | A breakdown of usage by token type, session, and what triggered the work. |
/hermit-dashboard-design | A dashboard designed around what your agent actually tracks. |
The agent reviews evidence from its work and operation. Durable lessons go to memory. When skill learning is enabled, completed work can save or revise reusable skills automatically. Other proposed behavior changes are verified, deduplicated, and brought to you for approval.
The reflection and proposal path works like this:
Work produces evidence
│
▼
Reflect when due
│
▼
Verify and deduplicate
│
┌────┴────┐
▼ ▼
Remember Propose
a lesson a change
│
▼
You approve?
│ │
no yes
│ │
No change Implement
│
▼
Verify result
│
▼
Future evidence
Reflection runs at eligible task or session pauses, daily, and after routines configured to reflect. Approved changes can start now, become a task, or be left for manual implementation. Proposals are resolved when verification passes or later evidence shows the problem is gone.
| Ask | What it does |
|---|---|
“Start X in ~/code/api on Opus at high effort, in its own worktree.” | Starts a session in any project, on your model and effort. |
“Tell me when my session in ~/code/web finishes.” | Watches your other Claude Code sessions. |
!pause · !snooze 2h · !model sonnet · !effort high | Claude Code controls, straight from chat. |
“/later check tomorrow whether those errors have returned.” | Checks whether a fix held up over time. |
| “remind me Monday at 14:00 to pay the invoice” | Delivers a durable reminder at the due minute in monitor mode, even after a restart. |
| “Download last month's invoices from the supplier portal.” | Works in web apps through Claude in Chrome on any machine signed in to the same claude.ai account as the agent, Docker agents included. |
| “When I ask for a status update, include blockers.” | Remembers instructions for that channel. |
| “What else could you be doing for me?” | Proposes new capabilities from your work and its tools. |
Quiet heartbeat checks, skipped routines, and passive chat capture use no model tokens. Work, evaluations, and replies consume usage; context management keeps conversation history bounded.
event: a file, a log line, a webhook, a schedule
│
▼
precheck (plain script, no model tokens)
│
├── nothing changed ──▶ back to sleep
│
▼ something to do
Claude Code turn on your machine
│
├── needs a decision ──▶ asks you in chat
│
▼
result in your chat + usage recorded
/cost-reflect.See budgets and routine scheduling for configuration and scheduler fallback behavior.
Reach the running agent through your connected channels or Claude Code Remote Control. You can also start separate sessions for additional work:
/spawn-session, the agent launches a local Claude Code helper in the project, or in another folder with --cwd, and relays its status when it becomes idle. Claude Code isolates the helper's edits in a Git worktree unless the project sets worktree.bgIsolation to none; pass --worktree to give it one from the start. Set the helper’s model and effort with options such as --model sonnet --effort high.!model or !effort in the thread switch that helper without losing its conversation. A request that continues the same work goes back to the same session./rc-gate, the agent manages a Remote Control server on your machine or server. While the gate is open, you can spawn new Claude Code sessions from the Claude app, using your local files and tools. Each session gets its own Git worktree, while the agent keeps running.Both session-spawning paths require a Git workspace. Remote Control requires a Claude sign-in through /login on the machine running the agent.
Watch other sessions. Through Claude Code cross-session messaging, ask the agent to watch a local Claude Code session, including one you started interactively, and notify you when it next becomes idle.
Claude Code controls from chat. Use !model sonnet, !effort high, !advisor opus, !compact, !clear, !doctor (alias !checkup), and !permission-mode auto directly from your connected chat. Control the agent’s work with !pause, !resume, and !snooze 2h. Use /when-done-switch-to --model sonnet to switch automatically at the end of the current turn.
Optional plugins that add domain tools and workflows to your agent.
You can run separate agents for different responsibilities, each with its own working state, knowledge, and routines. See Creating Your Own Hermit.
External orchestration. Other agents and tools can check the agent’s status, health, and recent work through its MCP interface, and request a wake when needed.
Sign-in renewal from chat. When your agent’s Claude sign-in needs renewing, use /relogin from your connected chat. Open the link in your browser, sign in, and send the code back in chat.
Scheduled backups. Optional backups preserve the agent’s knowledge, session reports, settings, and Claude Code memory in Git, with an optional private remote copy. Backups run without model tokens.
Claude Code 2.1.287 blocks plugins named claude*, so this project moved from claude-code-hermit to hermitd. Stop every agent in this Claude config directory, then follow the migration prompt.
Coming from claude-code-hermit? See how to migrate.
Run hermitd update from the project folder, or hermitd update <name> from anywhere. Docker updates refresh the host core first, then the container. The update waits for a quiet moment, applies migrations, then restarts the agent once and resumes the conversation.
hermitd list shows registered and discovered agents on this host, including stopped and missing projects. hermitd status [name] shows transport, execution and its age, open and waiting tasks, and the first runnable task. Both support --json. Listing never removes entries; hermitd prune removes missing projects.
Use hermitd start|stop|restart|attach [name] for lifecycle commands, hermitd pause [name] on|off|snooze <duration>|status, hermitd watchdog [name] run|install|uninstall, or hermitd run [name] <script> [args] for maintenance. Names match the project folder or agent name; with no name, the nearest project above the current folder is used.
hermitd skills [name] status|pin|unpin|rollback|archive|restore [skill] inspects or controls learned skills. Use status --skill <skill> for one bounded history. Mutations run inside the container when the Docker agent is up. A task close can save a reusable procedure automatically; "keep this skill" pins it and "stop doing it that way" about a named learned skill rolls back its latest revision.
See the Upgrade guide for details.
<a id="tips--tuning"></a>
Join the Discord community for setup help and discussion. See CONTRIBUTING.md for reporting bugs or contributing.
Andrej Karpathy inspired the raw/ → compiled/ knowledge system.
Independent project, not affiliated with Anthropic.
mod/register.ts 423 lines1import type { EngineInterface, Register } from 'claude-code';
2
3type Command = { command: string; arg: string | null };
4type Leg = { command: string; status: 'ok' | 'failed' | 'unknown' | 'skipped'; text: string; submitted_at?: string };
5type Entry = {
6 id: string;
7 source: string;
8 commands: Command[];
9 legs?: Leg[];
10};
11type Decision = Partial<Entry> & {
12 decision: 'pass' | 'run' | 'refuse' | 'ok' | 'queued' | 'send_failed';
13 reason?: string;
14 text?: string;
15 silent?: boolean;
16 state?: string;
17 reply_to?: { source: string; chat_id: string };
18 relays?: { text: string; reply_to: { source: string; chat_id: string } }[];
19};
20const TICK_MS = 2000;
21// The deadline only records an uncertain outcome; the run keeps its slot until it settles.
22const deadlineFor = (command: Command) => command.command === '/compact' ? 300_000 : 120_000;
23const SKILL_RE = /^\/[a-z0-9][a-z0-9-]*:[a-z0-9][a-z0-9-]*$/i;
24const EFFORT_LEVELS = new Set(['low', 'medium', 'high', 'xhigh', 'max']);
25
26// Only a cheap shape filter here. The bridge owns envelope parsing, addressing,
27// authorization and residency; ordinary prompts never start a process.
28export function isCommandPrompt(text: string): boolean {
29 const body = /^\s*<channel\b[^>]*>([\s\S]*)<\/channel>\s*$/.exec(text)?.[1] ?? '';
30 return /^(?:(?:<@!?\d+>|@\S+)\s*)?!(?:model|effort|compact|clear|advisor|doctor|checkup)(?:@[^\s]+)?(?:\s|$)/i.test(body.trim());
31}
32
33export function classifyStdout(command: string, text: string): 'ok' | 'failed' {
34 const success = command === '/model' ? /^Set model to\b/i.test(text)
35 : command === '/advisor' ? /^(?:Advisor set to\b|Advisor (?:disabled|turned off)\b)/i.test(text)
36 : command === '/reload-plugins' ? /^Reloaded:/.test(text)
37 : command === '/clear' && text === '';
38 return success ? 'ok' : 'failed';
39}
40
41async function bridge($: EngineInterface, verb: string, payload = ''): Promise<Decision> {
42 const [id, cwd] = await Promise.all([$.session.id(), $.session.cwd()]);
43 const result = await $.process.run([
44 'bash', `${$.plugin.root}/scripts/hermitd-exec.sh`, 'harness-mod', verb, id, payload,
45 ], { cwd });
46 if (result.exitCode !== 0 || !result.stdout.trim()) throw new Error(`Harness bridge ${verb} failed`);
47 return JSON.parse(result.stdout);
48}
49
50let timer: { cancel(): void } | undefined;
51let stateDir: string | undefined;
52let lastId: string | undefined;
53// Retries used for the current id when the bridge answered `pass` (resident id not stamped yet).
54let loadRetry = 0;
55const LOAD_RETRIES = 5;
56let recovered = false;
57let ticking = false;
58// The main loop's running turn, from turn.start; subagent turns never gate the queue.
59let mainTurn: string | undefined;
60let request: Entry | undefined;
61let legs: Leg[] = [];
62// One $.command.run outstanding at a time, held until it settles.
63let running = false;
64let active: {
65 command: Command;
66 resolved: boolean;
67 evidence?: Leg;
68 stdoutStarted: boolean;
69 expectedModel: string | null;
70 timer: { cancel(): void };
71} | undefined;
72let approval: string | null = null;
73// The resident's chat-set effort, applied per main-thread request; the session's own level stays.
74let effort: string | undefined;
75
76const busy = () => !!(request || running || active);
77const errorText = (error: unknown) => error instanceof Error ? error.message : String(error);
78
79// A reply the channel could not take is handed to the session to relay once.
80async function relay($: EngineInterface, result: Pick<Decision, 'text' | 'reply_to'>) {
81 await $.prompt.submit({ text: `Relay this harness command result once to ${JSON.stringify(result.reply_to)}: ${JSON.stringify(result.text)}. Do not run the command again.` });
82}
83
84// Requests the queue settled without running answer their chat from the claim or recover call.
85async function relayUnanswered($: EngineInterface, result: Decision) {
86 for (const failed of result.relays ?? []) await relay($, failed);
87}
88
89async function finalize($: EngineInterface, input: unknown) {
90 const result = await bridge($, 'finalize', JSON.stringify(input));
91 if (result.decision === 'send_failed') await relay($, result);
92}
93
94// Stops at the first leg that is not ok: a dependent leg never runs after an uncertain one.
95async function settle($: EngineInterface, leg: Leg) {
96 const current = request;
97 if (!current) return;
98 legs.push(leg);
99 try {
100 if (leg.status !== 'ok' || legs.length === current.commands.length) {
101 const done = legs;
102 request = undefined;
103 legs = [];
104 await finalize($, { id: current.id, legs: done });
105 } else {
106 // Progress survives a reload that replaces this copy, so the next copy knows where it stopped.
107 await bridge($, 'leg', JSON.stringify({ id: current.id, legs }));
108 }
109 } finally {
110 // A failed reply must not strand the work queued behind this one.
111 schedule($);
112 }
113}
114
115async function finish($: EngineInterface, leg: Leg) {
116 if (!active) return;
117 active.timer.cancel();
118 active = undefined;
119 approval = null;
120 await settle($, leg);
121}
122
123function observe($: EngineInterface) {
124 if (!active?.resolved || !active.evidence) return;
125 const current = active;
126 // Finish outside the observing hook, so the next command cannot re-enter it.
127 $.clock.after(0, () => {
128 if (active === current) return finish($, current.evidence!);
129 });
130}
131
132async function dispatch($: EngineInterface) {
133 if (!request || active || running) return;
134 const command = request.commands[legs.length];
135 if (command.command === '/doctor') return runDoctor($, request);
136 if (command.command === '/effort') return setEffort($, command.arg ?? '');
137 const current = {
138 command, resolved: false, stdoutStarted: false, expectedModel: null as string | null,
139 evidence: undefined as Leg | undefined,
140 timer: $.clock.after(deadlineFor(command), () => {
141 if (active === current) return finish($, { command: command.command, status: 'unknown', text: 'deadline reached' });
142 }),
143 };
144 active = current;
145 running = true;
146 approval = command.command === '/model' ? command.arg : null;
147 try {
148 const out = await $.command.run({ command: command.command.slice(1), args: command.arg ?? '' });
149 if (active !== current) return;
150 current.resolved = true;
151 // A skill is a prompt for the model: resolving at submit is all a run reports.
152 if (SKILL_RE.test(command.command)) current.evidence = { command: command.command, status: 'ok', text: 'submitted', submitted_at: new Date().toISOString() };
153 // A reload returns its own output, so a recognized success needs no transcript row; any
154 // other text is left to the transcript row or the deadline.
155 else if (command.command === '/reload-plugins' && typeof out?.text === 'string'
156 && classifyStdout(command.command, out.text) === 'ok') {
157 current.evidence ??= { command: command.command, status: 'ok', text: out.text };
158 }
159 observe($);
160 } catch (error) {
161 if (active === current) await finish($, { command: command.command, status: 'failed', text: errorText(error) });
162 } finally {
163 running = false;
164 if (!active) schedule($);
165 }
166}
167
168// /doctor is a prompt-type command: run resolves at submit and prints no stdout, and its
169// own turn replies to the chat through the skill-relay marker written first.
170async function runDoctor($: EngineInterface, doctor: Entry) {
171 running = true;
172 let leg: Leg;
173 try {
174 // The bridge answers `pass` rather than exiting non-zero when it cannot record the target.
175 if ((await bridge($, 'relay', JSON.stringify(doctor))).decision !== 'ok') throw new Error('Reply target not recorded');
176 await $.command.run({ command: 'doctor', args: '' });
177 leg = { command: '/doctor', status: 'ok', text: 'submitted', submitted_at: new Date().toISOString() };
178 } catch (error) {
179 leg = { command: '/doctor', status: 'failed', text: errorText(error) };
180 } finally {
181 running = false;
182 }
183 await settle($, leg).catch(() => undefined);
184}
185
186// /effort with a warm cache opens a confirmation no mod can answer and rewrites the user's
187// default, so the level is applied to each request instead and kept in state for a reload.
188async function setEffort($: EngineInterface, level: string) {
189 running = true;
190 let leg: Leg;
191 try {
192 // `auto` clears the override, as the native command resets to the model default.
193 const clear = level === 'auto';
194 if (!clear && !EFFORT_LEVELS.has(level)) throw new Error(`Unknown effort level: ${level}`);
195 if (!stateDir) throw new Error('No resident state directory');
196 await $.fs.write(`${stateDir}/effort-override.json`, JSON.stringify({ level: clear ? null : level, set_at: new Date().toISOString() }) + '\n');
197 effort = clear ? undefined : level;
198 leg = { command: '/effort', status: 'ok', text: clear ? 'Effort override cleared; the launch level applies' : `Effort set to ${level}; the status line still shows the launch level` };
199 } catch (error) {
200 leg = { command: '/effort', status: 'failed', text: errorText(error) };
201 } finally {
202 running = false;
203 }
204 await settle($, leg).catch(() => undefined);
205}
206
207async function readEffort($: EngineInterface, dir: string) {
208 try {
209 const level = JSON.parse(String(await $.fs.read(`${dir}/effort-override.json`))).level;
210 effort = EFFORT_LEVELS.has(level) ? level : undefined;
211 } catch {
212 effort = undefined;
213 }
214}
215
216// A pause ends the running turn natively: a dialog it holds closes unanswered, and
217// later commands keep working, which an Escape keystroke would not allow.
218async function runPause($: EngineInterface, entry: Decision) {
219 let leg: Leg = { command: 'turn.abort', status: 'ok', text: 'no turn' };
220 if (mainTurn) {
221 try {
222 await $.turn.abort({ turnId: mainTurn });
223 leg = { ...leg, text: 'turn aborted' };
224 } catch (error) {
225 leg = { ...leg, status: 'failed', text: errorText(error) };
226 }
227 }
228 await finalize($, { id: entry.id, legs: [leg] });
229}
230
231function schedule($: EngineInterface) {
232 $.clock.after(0, () => dispatch($));
233}
234
235function start($: EngineInterface, entry: Decision) {
236 request = { id: entry.id!, source: entry.source!, commands: entry.commands ?? [] };
237 legs = [...(entry.legs ?? [])];
238 schedule($);
239}
240
241// Called once per session id, never per tick: a guest session costs one process per id change,
242// plus at most LOAD_RETRIES while the bridge answers `pass`.
243// A bridge failure is not a verdict, so the next tick tries the same id again.
244async function loadedFor($: EngineInterface, id: string) {
245 if (id !== lastId) loadRetry = 0;
246 lastId = id;
247 const result = await bridge($, 'loaded').catch(error => {
248 lastId = undefined;
249 throw error;
250 });
251 if (result.decision !== 'ok' || !result.state) {
252 stateDir = undefined;
253 effort = undefined;
254 // session.start can run before the SessionStart hook stamps the resident id, and the
255 // classic.SessionStart retry may never run, so a `pass` is retried a few times with backoff.
256 if (loadRetry < LOAD_RETRIES) {
257 const delay = 2000 * 2 ** loadRetry++;
258 $.clock.after(delay, async () => {
259 if (lastId === id && !stateDir) await loadedFor($, id).catch(() => undefined);
260 });
261 }
262 return;
263 }
264 stateDir = result.state;
265 await readEffort($, result.state);
266 if (recovered) return;
267 recovered = true;
268 const resumed = await bridge($, 'recover');
269 await relayUnanswered($, resumed);
270 if (resumed.decision === 'run' && !busy()) start($, resumed);
271}
272
273async function hasPause($: EngineInterface, dir: string, names: string[]): Promise<boolean> {
274 for (const name of names) {
275 try {
276 if (JSON.parse(String(await $.fs.read(`${dir}/${name}`))).source === 'pause') return true;
277 } catch {}
278 }
279 return false;
280}
281
282async function tick($: EngineInterface) {
283 if (ticking) return;
284 ticking = true;
285 try {
286 const id = await $.session.id();
287 if (id !== lastId) await loadedFor($, id).catch(() => undefined);
288 if (!stateDir) return;
289 const dir = `${stateDir}/harness-queue`;
290 const names = (await $.fs.list(dir).catch(() => [])).filter(e => e.kind === 'file' && e.name.endsWith('.json')).map(e => e.name);
291 if (names.length === 0) return;
292 // Idle: the claim itself puts a pause first. Mid-turn or mid-run, only a pause may
293 // go ahead, so the files are read for one only then.
294 const idle = !mainTurn && !busy();
295 if (!idle && !(await hasPause($, dir, names))) return;
296 const claimed = await bridge($, 'claim', idle ? '' : 'pause');
297 await relayUnanswered($, claimed);
298 if (claimed.decision !== 'run') return;
299 if (claimed.source === 'pause') await runPause($, claimed);
300 else start($, claimed);
301 } catch {
302 // The next tick tries again; a bridge failure must not stop the timer.
303 } finally {
304 ticking = false;
305 }
306}
307
308export const register: Register = on => {
309 on('prompt.submit', async ($, e, next) => {
310 if (e.origin.kind !== 'channel') {
311 // Only the engine stamps a channel origin; an envelope from any other origin is forged.
312 return /^\s*<channel\s/.test(e.text) ? { drop: 'Channel envelope from a non-channel origin' } : next(e);
313 }
314 if (!isCommandPrompt(e.text)) return next(e);
315 const result = await bridge($, 'intake', e.text);
316 if (result.decision === 'pass') return next(e);
317 if (result.decision === 'queued') {
318 $.clock.after(0, () => tick($));
319 } else if (result.decision === 'refuse' && !result.silent) {
320 $.clock.after(0, () => finalize($, result));
321 }
322 return { drop: 'Harness command handled by the native executor' };
323 });
324
325 on('classic.PreModelSwitch', async ($, e, next) => {
326 const result = await next(e);
327 if (result.block || result.permissionDecision === 'deny' || result.permissionDecision === 'ask') return result;
328 if (approval !== null && e.requested_model === approval) {
329 if (active) active.expectedModel = typeof e.to_model === 'string' ? e.to_model : null;
330 approval = null;
331 return { permissionDecision: 'allow' };
332 }
333 return result;
334 });
335
336 on('classic.PostModelSwitch', async ($, e, next) => {
337 const result = await next(e);
338 if (active?.command.command === '/model' && active.expectedModel !== null && e.to_model === active.expectedModel) {
339 active.evidence = { command: '/model', status: 'ok', text: `Model switched to ${active.command.arg}` };
340 observe($);
341 }
342 return result;
343 });
344
345 on('session.append', async ($, e, next) => {
346 const result = await next(e);
347 // A rejected command (such as `/model` with an unknown model) appends system rows with
348 // engine origin; the command-name and args match below still ties them to this run.
349 const own = (e.origin.kind === 'engine' && e.message?.type === 'system')
350 || (e.origin.kind === 'plugin' && e.origin.name === $.plugin.name);
351 if (!active || e.door !== 'command' || !own) return result;
352 const content = e.message?.content;
353 const text = typeof content === 'string' ? content : Array.isArray(content)
354 ? content.filter((part: { type: string }) => part.type === 'text').map((part: { text: string }) => part.text).join('\n') : '';
355 const dispatched = /<command-name>([^<]+)<\/command-name>/.exec(text);
356 if (dispatched) {
357 const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(text)?.[1] ?? '';
358 active.stdoutStarted = dispatched[1] === active.command.command && args === (active.command.arg ?? '');
359 }
360 const stdout = /<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/.exec(text);
361 if (!stdout || !active.stdoutStarted) return result;
362 const command = active.command.command;
363 if (command === '/compact' || SKILL_RE.test(command)) return result;
364 const observed = stdout[1];
365 const status = classifyStdout(command, observed);
366 // A cleared context is reported from classic.SessionStart, once the resident id is current.
367 if (command === '/clear' && status === 'ok') return result;
368 active.evidence = { command, status, text: observed };
369 observe($);
370 return result;
371 });
372
373 on('session.compact', async ($, e, next) => {
374 const result = await next(e);
375 if (active?.command.command === '/compact' && typeof result.tokensBefore === 'number' && typeof result.tokensAfter === 'number') {
376 active.evidence = { command: '/compact', status: 'ok', text: `Compacted ${result.tokensBefore} to ${result.tokensAfter} tokens` };
377 observe($);
378 }
379 return result;
380 });
381
382 on('session.start', async ($, e, next) => {
383 const result = await next(e);
384 timer ??= $.clock.every(TICK_MS, () => tick($));
385 await loadedFor($, await $.session.id()).catch(() => undefined);
386 return result;
387 });
388
389 // A /clear or a forked resume changes the session id, and session.start can run before
390 // the plugin's own SessionStart command hook restamps the resident id. next(e) resolves
391 // after that hook, while session.end and $.command.run resolve before it starts.
392 on('classic.SessionStart', async ($, e, next) => {
393 const result = await next(e);
394 if (e.source === 'clear' && active?.command.command === '/clear') {
395 active.evidence = { command: '/clear', status: 'ok', text: 'Context cleared' };
396 observe($);
397 }
398 $.clock.after(0, async () => loadedFor($, await $.session.id()).catch(() => undefined));
399 return result;
400 });
401
402 // Subagents keep their own level, and a model with no effort setting is sent none.
403 on('turn.step', async function* ($, e, next) {
404 return yield* next(effort && e.agentId === undefined && e.effort !== undefined ? { ...e, effort } : e);
405 });
406
407 on('turn.start', async ($, e, next) => {
408 const result = await next(e);
409 if (e.agentId === undefined) mainTurn = e.turnId;
410 return result;
411 });
412
413 on('turn.complete', async ($, e, next) => {
414 const result = await next(e);
415 if (!e.agentId) {
416 mainTurn = undefined;
417 // A request queued mid-turn is claimed now, before the next turn can start.
418 $.clock.after(0, () => tick($));
419 }
420 return result;
421 });
422};
423