I kept doing the same thing with Claude Code: start a task, switch to another window, and come back five minutes later to find it had been sitting on a permission prompt the whole time.
So I built a small pixel cat that sits on my desktop and watches the agent for me. She narrates what Claude is doing, jumps and chimes when it needs my OK, and gets sleepy when the context window fills up. Everything runs on Claude Code's hooks, which turned out to be a really nice API for this, so here's how the plumbing works in case you want to build your own.
Claude Code can run a shell command at points in its lifecycle. You register them in ~/.claude/settings.json:
{
"hooks": {
"PreToolUse": [
{ "matcher": "*", "hooks": [{ "type": "command", "command": "node ~/.mochi/app/hook.js", "timeout": 5 }] }
],
"Notification": [{ "hooks": [{ "type": "command", "command": "node ~/.mochi/app/hook.js" }] }],
"Stop": [{ "hooks": [{ "type": "command", "command": "node ~/.mochi/app/hook.js" }] }],
"UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "node ~/.mochi/app/hook.js" }] }],
"SessionStart": [{ "hooks": [{ "type": "command", "command": "node ~/.mochi/app/hook.js" }] }]
}
}
Each run gets a JSON payload on stdin. The fields I ended up using:
| Field | What it tells you | |---|---| | hook_event_name | PreToolUse ,Notification ,Stop , ... | | tool_name ,tool_input | e.g. Bash +{ "command": "npm test" } , orRead +{ "file_path": "src/auth.ts" } | | cwd | the project folder | | message | for Notification , e.g. "Claude needs your permission to use Bash" | | transcript_path | the session's JSONL transcript (more on this below) |
That's enough to map the agent's state onto a pet:
| Event | Mood | |---|---| | UserPromptSubmit ,PreToolUse | working | | Notification | needs you (jump + chime) | | Stop | done (confetti) | | nothing for 5 minutes | napping |
This was the most important design constraint. A hook that hangs or prints the wrong thing makes the agent worse, so mine:
UserPromptSubmit and SessionStart), whatever a hook writes to stdout gets added to Claude's context. A chatty hook would quietly burn your tokens.
// hook.js: forward the event to the pet, never block Claude
const http = require('http');
let input = '';
process.stdin.on('data', d => (input += d));
process.stdin.on('end', () => {
const ev = JSON.parse(input || '{}');
const ti = ev.tool_input || {};
const slim = JSON.stringify({ // send only what the pet needs
hook_event_name: ev.hook_event_name, cwd: ev.cwd, tool_name: ev.tool_name,
message: ev.message, transcript_path: ev.transcript_path,
tool_input: { file_path: ti.file_path, command: (ti.command || '').slice(0, 200), pattern: ti.pattern },
});
const req = http.request({ host: '127.0.0.1', port: 4777, path: '/hook', method: 'POST', timeout: 700,
headers: { 'content-type': 'application/json' } }, res => { res.resume(); res.on('end', () => process.exit(0)); });
req.on('error', () => process.exit(0));
req.on('timeout', () => { req.destroy(); process.exit(0); });
req.end(slim);
});
setTimeout(() => process.exit(0), 2500).unref(); // hard stop no matter what
Note the "slim" payload: the pet never sees file contents, just names.
PreToolUse fires before every tool call, so a tiny mapper gives you a running commentary:
function narrate(tool, inp = {}) {
const base = p => (p || '').split('/').pop();
switch (tool) {
case 'Read': return `reading ${base(inp.file_path)}`;
case 'Edit': return `editing ${base(inp.file_path)}`;
case 'Grep': return `searching "${inp.pattern}"`;
case 'Bash':
if (/\b(test|jest|pytest|vitest)\b/.test(inp.command)) return 'running tests';
if (/\bgit\s+commit\b/.test(inp.command)) return 'committing';
return `$ ${inp.command.split(/\s+/).slice(0, 2).join(' ')}`;
default: return tool.startsWith('mcp__') ? `using ${tool.split('__')[1]}` : tool.toLowerCase();
}
}
Only the first two words of a shell command are shown, so secrets in arguments don't end up in a speech bubble.
Every hook payload includes transcript_path, the JSONL file of the session. Assistant turns in it carry a usage block, so you can read the tail of the file, find the last one and add up the input-side tokens:
function contextTokens(transcriptPath) {
const { size } = fs.statSync(transcriptPath);
const n = Math.min(size, 400_000), buf = Buffer.alloc(n), fd = fs.openSync(transcriptPath, 'r');
fs.readSync(fd, buf, 0, n, size - n); fs.closeSync(fd);
for (const line of buf.toString('utf8').split('\n').reverse()) {
if (!line.includes('"usage"')) continue;
try {
const u = JSON.parse(line).message?.usage;
if (u) return u.input_tokens + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
} catch {}
}
return null;
}
Divide by your context window (200k, or 1M if you use a 1M model) and you get a percentage. The cat starts drooping past ~70% and suggests /compact. It turned out to be the feature I use most: it's a passive reminder that the session is getting expensive and slow before it auto-compacts at a bad moment.
If you build something like this, two cheap protections go a long way:
127.0.0.1 and check the Host headerx-mochi: 1). Browsers can't send custom headers cross-origin without a CORS preflight, and if you never answer the preflight, websites simply can't post fake events. The hooks + a tiny Node server became Mochi, a Mac app with:
claude -p, so no API key is needed) It's $3.99 at launch, or $14.99 with the full source if you want to build your own pet on top of it. It's also free in the Mega Pack with my Claude Code skill tree.
But honestly, the hook script above is the whole trick. If you build something with it, a Pomodoro timer or a Slack ping or a lamp that turns red when Claude needs you, I'd love to see it in the comments.
原文来源:dev.to