Buddy: a pet sidekick for Claude Code. Sees all your chats, keeps your to-do list when Claude needs you, covers your secrets while you film, runs a team of…

Claude Code once had an April Fools pet called Buddy. He's gone, so this mod brings him back as a sidekick that does real work.
Hatch him from an egg and he lives in a panel next to your chat. He naps, walks around while Claude works, and dances when a task finishes. Meanwhile he does this:
Does things for you
Claude is the boss of Codex (Codex tab)
Runs a team (Threads tab)
/thread <task>, or Claude starts them itself). Its answer comes back to the chat that started it, and you can send it follow-ups. Works on Windows and Mac; no tmux.Manages your skills (Skills tab)
Sees everything at a glance
One-click power moves
A safety net you can switch on
.env (or anything you add). Delete check is there too, off by default.The fun part: pick a bunny, cat, dog, bear, frog, owl, ghost or dragon. Hatch, rename, pet.
You need Claude Code 2.1.287 or later (claude --version; claude update if older). Buddy draws in the terminal and in the Code tab of the Claude desktop app (not in the VS Code chat panel or WSL).
claude plugin marketplace add joshpocock/claude-buddy
claude plugin install buddy@claude-buddy --scope user
Open a new chat and type /buddy. If the installer says options are "not yet set", that's fine: Buddy uses sensible defaults, and you can change everything in his Settings tab.
Check it first, like any mod: after cloning, run claude plugin validate ./buddy. It lists everything Buddy can do: no internet access; he reads and writes small status files in ~/.claude/buddy/ for the chats board; the programs he runs are Claude itself (for separate chats you start), Codex (only if you switch it on), and your system's copy and delete commands (only when you copy, move or delete a skill).
/buddy opens the panel. Tabs: Status, Chats, Jobs, Pets, Settings, Help/buddy rec recording mode on or off/thread <task> start a separate background chat/buddy-skills what the Skills tab runs (scan, copy, move, delete)/buddy hatch new egg · /buddy pet dragon pick a pet · /buddy name Rex rename · /buddy reset zero the counter/handoff save a handoff note · /codex <question> ask Codex (when on)claude plugin marketplace update claude-buddy
claude plugin update buddy@claude-buddy
claude plugin uninstall buddy@claude-buddy
Buddy is a starting point, not a finished product. Fork it, change it, add your own jobs. Every job is its own file in buddy/hooks/jobs/, so adding one is easy. Pull requests welcome.
MIT licensed. Made by Josh Pocock.
hooks/register.tsx 1699 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import { registerExtras } from './jobs/extras.tsx'
5import { registerGuards } from './jobs/guards.tsx'
6import { registerPower } from './jobs/power.tsx'
7import { registerThreads } from './jobs/threads.tsx'
8import { frontmatter, norm, registerSkills } from './jobs/skills.tsx'
9import { registerCodexTeam } from './jobs/codexteam.tsx'
10import type { CodexJob } from './jobs/codexteam.tsx'
11import { byProject, convArgv, dayDirs, dumpArgv, guardianIds, idFromFile, parseConversation, parseDump, parseIndex, parseProjects, pickPerProject, projectCounts, projectsArgv, projectsArgvFiles } from './lib/codexthreads.ts'
12import type { ConvEntry } from './lib/codexthreads.ts'
13import type { CodexThread } from './lib/codexthreads.ts'
14import type { SkillItem, SkillScan, SkillUse } from './jobs/skills.tsx'
15import type { AgentLive, ChatThread } from './jobs/threads.tsx'
16import type { Todo } from './jobs/power.tsx'
17import { maskText, nameList } from './lib/mask.ts'
18import { registerWatch } from './jobs/watch.tsx'
19import type { AgentRow, Caught, Limit, Mood, Receipt } from '../types'
20
21// Buddy's shared state (same keys in every file, so every job sees the same values).
22const agents = atom({ plugin: 'buddy', key: 'agents' } as const, [] as AgentRow[])
23const caught = atom({ plugin: 'buddy', key: 'caught' } as const, { send: 0, spend: 0, danger: 0 } as Caught)
24const lastHeld = atom({ plugin: 'buddy', key: 'lastHeld' } as const, '')
25const memory = atom({ plugin: 'buddy', key: 'memory' } as const, 0)
26const mood = atom({ plugin: 'buddy', key: 'mood' } as const, 'sleepy' as Mood)
27const tick = atom({ plugin: 'buddy', key: 'tick' } as const, 0)
28const limits = atom({ plugin: 'buddy', key: 'limits' } as const, [] as Limit[])
29const cost = atom({ plugin: 'buddy', key: 'cost' } as const, 0)
30const receipt = atom({ plugin: 'buddy', key: 'receipt' } as const, null as Receipt | null)
31const codexLog = atom({ plugin: 'buddy', key: 'codexLog' } as const, [] as string[])
32const codexStatus = atom({ plugin: 'buddy', key: 'codexStatus' } as const, '')
33const tab = atom({ plugin: 'buddy', key: 'tab' } as const, 'status' as 'status' | 'chats' | 'threads' | 'codex' | 'skills' | 'jobs' | 'pets' | 'settings' | 'help')
34
35// The pets Buddy can be. A new install starts as an egg that hatches into a random one.
36const SPECIES = ['bunny', 'cat', 'dog', 'bear', 'frog', 'owl', 'ghost', 'dragon'] as const
37type PetInfo = { stage: 'egg' | 'pet'; species: (typeof SPECIES)[number]; name: string; pets: number }
38const NEW_PET: PetInfo = { stage: 'egg', species: 'bunny', name: 'Buddy', pets: 0 }
39const lastTurnAt = atom({ plugin: 'buddy', key: 'lastTurnAt' } as const, 0)
40const second = atom({ plugin: 'buddy', key: 'second' } as const, 0)
41const recOn = atom({ plugin: 'buddy', key: 'recOn' } as const, false)
42const agentLive = atom({ plugin: 'buddy', key: 'agentLive' } as const, {} as Record<string, AgentLive>)
43const chatThreads = atom({ plugin: 'buddy', key: 'chatThreads' } as const, [] as ChatThread[])
44const threadModel = atom({ plugin: 'buddy', key: 'threadModel' } as const, 'sonnet')
45const threadKind = atom({ plugin: 'buddy', key: 'threadKind' } as const, 'helper' as 'helper' | 'chat')
46const forecast = atom({ plugin: 'buddy', key: 'forecast' } as const, { limits: {}, repliesLeft: null } as { limits: Record<string, { fullAt?: number; resetsAt?: string }>; repliesLeft: number | null })
47const codexJobs = atom({ plugin: 'buddy', key: 'codexJobs' } as const, [] as CodexJob[])
48const cxThreads = atom({ plugin: 'buddy', key: 'cxThreads' } as const, null as CodexThread[] | null)
49const cxCounts = atom({ plugin: 'buddy', key: 'cxCounts' } as const, {} as Record<string, number>)
50const cxOpen = atom({ plugin: 'buddy', key: 'cxOpen' } as const, { project: '', thread: '' })
51const cxConv = atom({ plugin: 'buddy', key: 'cxConv' } as const, { id: '', name: '', folder: '', loading: false, entries: [] as ConvEntry[], cutOff: false, loadedAt: 0, shown: 20, bytes: 4194304 })
52const cxSteps = atom({ plugin: 'buddy', key: 'cxSteps' } as const, false)
53const cxEdit = atom({ plugin: 'buddy', key: 'cxEdit' } as const, false)
54const skillScan = atom({ plugin: 'buddy', key: 'skillScan' } as const, null as SkillScan | null)
55const skillView = atom({ plugin: 'buddy', key: 'skillView' } as const, { q: '', sort: 'used' as 'used' | 'unused' | 'big', shown: 15, open: '' })
56const peek = atom({ plugin: 'buddy', key: 'peek' } as const, null as { id: string; text: string } | null)
57
58// Buddy: Claude Code's old pet, back with real jobs.
59// Jobs live in ./jobs; this file draws Buddy and wires the jobs in.
60
61
62// The all-chats board: each chat's Buddy keeps one small status file in ~/.claude/buddy/chats,
63// and every Buddy reads them all. One file per chat, so chats never overwrite each other.
64type ChatStatus = 'working' | 'waiting' | 'done' | 'idle' | 'closed'
65type ChatRow = { id: string; title: string; folder: string; status: ChatStatus; since: number; updatedAt: number }
66
67async function chatDir($: any): Promise<string> {
68 const home = ((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.') as string
69 return `${home.replace(/\\/g, '/')}/.claude/buddy/chats`
70}
71
72async function writeChat($: any, patch: Partial<ChatRow>) {
73 const id = await $.session.id()
74 const file = `${await chatDir($)}/${id}.json`
75 let cur: Partial<ChatRow> = {}
76 try {
77 cur = JSON.parse(await $.fs.read(file))
78 } catch {
79 cur = {}
80 }
81 const now = Date.now()
82 const next = { ...cur, ...patch, id, updatedAt: now } as ChatRow
83 if (patch.status && patch.status !== cur.status) next.since = now
84 if (!next.since) next.since = now
85 await $.fs.write(file, JSON.stringify(next))
86}
87
88const PANE = 'buddy'
89
90// Statuses seen last time, so Buddy can ping you when another chat finishes or needs you.
91const seenStatus: Record<string, ChatStatus> = {}
92let selfId = ''
93// The reply Buddy already warned about, so the 'cache going cold' ping fires once.
94let warnedTurn = 0
95
96const ago = (ms: number) => {
97 const s = Math.max(0, Math.round(ms / 1000))
98 return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m` : `${Math.floor(s / 3600)}h`
99}
100
101async function readChats($: any): Promise<ChatRow[]> {
102 const dir = await chatDir($)
103 if (!(await $.fs.exists(dir))) return []
104 const entries = await $.fs.list(dir)
105 const rows: ChatRow[] = []
106 for (const ent of entries) {
107 if (ent.kind !== 'file' || !ent.name.endsWith('.json')) continue
108 // A chat that hasn't checked in for 3 minutes is gone; skip its file without reading it.
109 if (ent.mtimeMs && Date.now() - ent.mtimeMs > 180000) continue
110 try {
111 const row = JSON.parse(await $.fs.read(`${dir}/${ent.name}`)) as ChatRow
112 // A chat that stopped checking in for 3 minutes is gone (closed or crashed).
113 if (row.status !== 'closed' && Date.now() - row.updatedAt < 180000) rows.push(row)
114 } catch {
115 // skip unreadable files
116 }
117 }
118 const rank: Record<string, number> = { waiting: 0, working: 1, done: 2, idle: 3 }
119 return rows.sort((a, b) => (rank[a.status] ?? 9) - (rank[b.status] ?? 9) || b.since - a.since)
120}
121
122
123let lastCodexScan = 0
124
125async function scanCodexForPanel($: any, focus = '') {
126 if (!focus && Date.now() - lastCodexScan < 30000) return
127 lastCodexScan = Date.now()
128 const home = (((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.') as string).replace(/\\/g, '/')
129 const windows = (await $.env.get('OS')) === 'Windows_NT'
130 const dirs = dayDirs(home, 60)
131 let names: Record<string, string> = {}
132 try {
133 names = parseIndex(await $.fs.read(`${home}/.codex/session_index.jsonl`))
134 } catch {
135 names = {}
136 }
137 const skip = guardianIds(names)
138 const files: { path: string; id: string; mtime: number }[] = []
139 for (const dir of dirs) {
140 if (!(await $.fs.exists(dir))) continue
141 for (const ent of await $.fs.list(dir)) {
142 const id = idFromFile(ent.name)
143 if (ent.kind === 'file' && id && !skip.has(id)) files.push({ path: `${dir}/${ent.name}`, id, mtime: ent.mtimeMs })
144 }
145 }
146 if (files.length === 0) {
147 await update($, cxThreads, () => [])
148 return
149 }
150 try {
151 // Pass 1: which project each log belongs to. Remembered, so only new logs are read.
152 const cache = (((await $.store.get('cxProjectCache')) ?? {}) as Record<string, string>)
153 const missing = files.filter(f => cache[f.id] === undefined)
154 if (missing.length > 0) {
155 const argv = missing.length <= 150 ? projectsArgvFiles(windows, missing.map(f => f.path)) : projectsArgv(windows, dirs)
156 const r1 = await $.process.run(argv, { timeoutMs: 120000 })
157 Object.assign(cache, parseProjects(String(r1.stdout ?? '')))
158 for (const f of missing) if (cache[f.id] === undefined) cache[f.id] = ''
159 const keep = new Set(files.map(f => f.id))
160 await $.store.set('cxProjectCache', Object.fromEntries(Object.entries(cache).filter(([id]) => keep.has(id))))
161 }
162 await update($, cxCounts, () => projectCounts(Object.fromEntries(files.map(f => [f.id, cache[f.id] ?? '']))))
163 // Pass 2: details for the newest few threads of each project (all of the one you opened).
164 const picked = pickPerProject(files, cache, 4, focus, 140)
165 const r2 = await $.process.run(dumpArgv(windows, picked.map(f => f.path)), { timeoutMs: 60000 })
166 const threads = parseDump(String(r2.stdout ?? ''), names, Object.fromEntries(picked.map(f => [f.id, f.mtime])))
167 await update($, cxThreads, () => threads)
168 await $.store.set('cxThreadsCache', { threads, counts: await read($, cxCounts) })
169 } catch {
170 await update($, cxThreads, () => [])
171 }
172}
173
174// Jump the panel to the newest message, like a chat app. Waits a moment so the new rows are drawn first.
175async function scrollConvToEnd($: any) {
176 try {
177 await $.clock.sleep(250)
178 await $.ui.scroll({ in: 'buddy', to: 'end' })
179 } catch {
180 // scrolling is a nicety
181 }
182}
183
184async function loadCodexConversation($: any, id: string, name: string, folder: string, bytes = 4194304, shown = 20) {
185 await update($, cxConv, c => ({ id, name, folder, loading: true, entries: c.id === id ? c.entries : [], cutOff: false, loadedAt: Date.now(), shown, bytes }))
186 const home = (((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.') as string).replace(/\\/g, '/')
187 const windows = (await $.env.get('OS')) === 'Windows_NT'
188 let file = ((await read($, cxThreads)) ?? []).find(t => t.id === id)?.file ?? ''
189 if (!file) {
190 for (const dir of dayDirs(home, 60)) {
191 if (!(await $.fs.exists(dir))) continue
192 const hit = (await $.fs.list(dir)).find((e: any) => e.name.includes(id))
193 if (hit) {
194 file = `${dir}/${hit.name}`
195 break
196 }
197 }
198 }
199 if (!file) {
200 await update($, cxConv, c => ({ ...c, loading: false, entries: [{ role: 'step', text: "Couldn't find this thread's log on disk." }] }))
201 return
202 }
203 try {
204 const r = await $.process.run(convArgv(windows, file, bytes), { timeoutMs: 60000 })
205 const { entries, cutOff } = parseConversation(String(r.stdout ?? ''))
206 const big = (await $.fs.stat(file)).size > bytes
207 await update($, cxConv, c => (c.id === id ? { ...c, loading: false, entries, cutOff: cutOff || big, loadedAt: Date.now() } : c))
208 if (bytes === 4194304) await scrollConvToEnd($)
209 } catch {
210 await update($, cxConv, c => ({ ...c, loading: false, entries: [{ role: 'step', text: "Couldn't read this conversation." }] }))
211 }
212}
213
214async function scanSkillDir($: any, dir: string, scope: 'global' | 'project'): Promise<SkillItem[]> {
215 if (!(await $.fs.exists(dir))) return []
216 const out: SkillItem[] = []
217 for (const ent of await $.fs.list(dir)) {
218 if (ent.name.startsWith('.') || (ent.kind !== 'dir' && !ent.isLink)) continue
219 const path = `${dir}/${ent.name}`
220 let text = ''
221 try {
222 text = await $.fs.read(`${path}/SKILL.md`)
223 } catch {
224 continue
225 }
226 const fm = frontmatter(text)
227 const name = fm.name || ent.name
228 out.push({ name, scope, path, isLink: Boolean(ent.isLink), descChars: fm.description.length + name.length, description: fm.description.slice(0, 220) })
229 }
230 return out
231}
232
233async function scanAllSkills($: any) {
234 const home = norm(((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.') as string)
235 const cwd = norm(await $.session.cwd())
236 const global = await scanSkillDir($, `${home}/.claude/skills`, 'global')
237 const project = cwd === home ? [] : await scanSkillDir($, `${cwd}/.claude/skills`, 'project')
238 const codexLink = await $.fs.exists(`${cwd}/.agents/skills`)
239 await update($, skillScan, () => ({ at: Date.now(), cwd, items: [...project, ...global], codexLink }))
240}
241
242const FACES: Record<Mood, [string, string]> = {
243 sleepy: ['( -.- ) zz', 'waiting on you'],
244 working: ['( o.o )', 'on it'],
245 happy: ['( ^.^ )/', 'done!'],
246 holding: ['( O.O )!', 'holding something for you'],
247 tired: ['( x_x )', "I'm full. Time to compact."],
248}
249
250const faceFor = (m: Mood, mem: number): [string, string] => (m !== 'holding' && mem >= 80 ? FACES.tired : FACES[m])
251
252const bar = (percent: number, width = 12) => {
253 const filled = Math.max(0, Math.min(width, Math.round((percent / 100) * width)))
254 return '█'.repeat(filled) + '░'.repeat(width - filled)
255}
256
257const tone = (percent: number) => (percent >= 80 ? 'red' : percent >= 50 ? 'yellow' : 'green')
258
259const elapsed = (row: AgentRow, now: number) => {
260 const s = Math.max(0, Math.round(((row.endedAt ?? now) - row.startedAt) / 1000))
261 return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
262}
263
264const total = (c: Caught) => c.send + c.spend + c.danger
265
266const baseName = (p: string) => p.replace(/\\/g, '/').split('/').pop() ?? p
267
268// Every job Buddy does, for the Jobs and Help tabs. `live` jobs switch instantly from the panel.
269const JOBS: { id: string; group: string; name: string; what: string; live: boolean }[] = [
270 { id: 'sendGate', group: 'Guards', name: 'Send gate', what: 'Holds emails, Slack, invites, shares, git push, deploys and posts to outside APIs until you choose', live: true },
271 { id: 'spendGate', group: 'Guards', name: 'Spend gate', what: 'Holds paid API calls (OpenAI, Anthropic, Gemini, ElevenLabs, Replicate, fal, Apify and any you add in settings)', live: true },
272 { id: 'dangerGuard', group: 'Guards', name: 'Danger guard', what: 'Holds deletes, wipes, force pushes and database drops (Bash and PowerShell)', live: true },
273 { id: 'lockedFiles', group: 'Guards', name: 'Locked files', what: 'Claude cannot edit the files you lock in settings (.env by default)', live: true },
274 { id: 'chatBoard', group: 'Watches', name: 'Chats board', what: 'Shows every open Claude Code chat and pings you when one finishes or needs you', live: true },
275 { id: 'cacheCheck', group: 'Watches', name: 'Cache price check', what: 'After a break, tells you what your next message costs (the cache went cold) and offers to compact first', live: true },
276 { id: 'agentWatcher', group: 'Watches', name: 'Agent watcher', what: 'Lists every helper agent, running or done, with times', live: true },
277 { id: 'donePing', group: 'Watches', name: 'Done ping', what: 'Pops up when a long task finishes, so you can walk away', live: true },
278 { id: 'todoInbox', group: 'Helps', name: 'To-do inbox', what: 'When Claude needs you (add a key, log in, approve), it lands on your to-do list. Press Done and Claude carries on', live: true },
279 { id: 'houseRules', group: 'Helps', name: 'House rules', what: 'Reminds Claude of your rules and flags banned words in replies', live: true },
280 { id: 'codex', group: 'Helps', name: 'Codex sidekick', what: 'Ask Codex for a read-only second opinion: /codex <task>. Turn on in settings (sends the task to OpenAI)', live: false },
281]
282
283const LIMIT_NAMES: Record<string, string> = { five_hour: '5-hour', seven_day: 'weekly', '5h': '5-hour', '7d': 'weekly' }
284
285export const register: Register = (on, options) => {
286 const o = options as any
287 registerGuards(on, o)
288 registerWatch(on, o)
289 registerExtras(on, o)
290 registerPower(on, o)
291 registerThreads(on, o)
292 registerSkills(on)
293 registerCodexTeam(on, o)
294
295 on('session.start', async ($, e, next) => {
296 const started = await next(e)
297 await $.command.register({ name: 'buddy', description: 'Open Buddy: your pet who watches and guards Claude' })
298 await $.command.register({ name: 'handoff', description: 'Buddy writes a handoff note for continuing in a fresh chat' })
299 const panel = ((await $.store.get('settings')) ?? {}) as Record<string, unknown>
300 await $.command.register({ name: 'codex', description: 'Ask Codex (read-only) for a second opinion: /codex <task>' })
301 if (o.codexEnabled === true || panel.codexEnabled === true) {
302 await $.tool.register({
303 name: 'codex',
304 description:
305 'Ask OpenAI Codex (a second, independent coding agent) for a read-only second opinion or review. Give it one clear, self-contained task. It cannot edit files. Returns its answer.',
306 inputSchema: { type: 'object', properties: { task: { type: 'string' } }, required: ['task'] },
307 })
308 }
309 await $.tool.register({
310 name: 'todo_for_you',
311 description:
312 "Put a task on the user's Buddy to-do list: something only they can do (add an API key, log in, approve or pay, check something by hand, decide). The user presses Done when finished and you get a message. One task per call.",
313 inputSchema: {
314 type: 'object',
315 properties: {
316 task: { type: 'string', description: 'One short sentence starting with a verb, e.g. "Add your OpenAI key to .env"' },
317 doneWhen: { type: 'string', description: 'Optional: how the user knows it is done' },
318 },
319 required: ['task'],
320 },
321 })
322 if ((await $.env.get('BUDDY_CHILD')) !== '1') {
323 await $.command.register({ name: 'buddy-codex', description: 'Buddy: start or message Codex agents (the Codex tab uses this)' })
324 await $.tool.register({
325 name: 'codex_threads',
326 description: "List the user's recent OpenAI Codex threads (from the Codex app and CLI: id, name, folder, working or idle, last reply) and the Codex agents started from this chat.",
327 inputSchema: { type: 'object', properties: {} },
328 })
329 await $.tool.register({
330 name: 'codex_start',
331 description:
332 'Start an OpenAI Codex agent on a self-contained task (a second AI working in parallel: research, review, a separate build). Read-only unless canEdit is true, which asks the user first. Returns at once and the answer arrives later as a message from Buddy; set wait to true to wait for the answer instead.',
333 inputSchema: {
334 type: 'object',
335 properties: {
336 task: { type: 'string', description: 'Complete instructions; Codex sees nothing of this chat' },
337 model: { type: 'string', description: 'Codex model, default from Buddy settings (gpt-5.5)' },
338 canEdit: { type: 'boolean', description: 'Let Codex edit files in this project (the user is asked)' },
339 wait: { type: 'boolean', description: 'Wait for the answer instead of getting it later' },
340 },
341 required: ['task'],
342 },
343 })
344 await $.tool.register({
345 name: 'codex_message',
346 description:
347 "Send the next message to a Codex thread or agent (a thread id from codex_threads, or an agent id from codex_start). Codex continues that conversation with its memory. Don't message a thread that is working.",
348 inputSchema: {
349 type: 'object',
350 properties: { threadId: { type: 'string' }, text: { type: 'string' }, wait: { type: 'boolean' } },
351 required: ['threadId', 'text'],
352 },
353 })
354 await $.command.register({ name: 'buddy-skills', description: 'Buddy: scan, copy, move or delete skills (the Skills tab uses this)' })
355 await $.command.register({ name: 'thread', description: 'Buddy: start a separate background chat: /thread <task>' })
356 await $.tool.register({
357 name: 'list_chats',
358 description: "List the user's other open Claude Code chats (id, title, folder, status: working, waiting, done, idle) and the separate background chats started from this one, with their answers.",
359 inputSchema: { type: 'object', properties: {} },
360 })
361 await $.tool.register({
362 name: 'message_chat',
363 description:
364 'Send a message to another open Claude Code chat (chatId from list_chats) or to a separate chat started with start_chat (its id). Use it to hand work to another chat or to steer it.',
365 inputSchema: { type: 'object', properties: { chatId: { type: 'string' }, text: { type: 'string' } }, required: ['chatId', 'text'] },
366 })
367 await $.tool.register({
368 name: 'start_chat',
369 description:
370 'Start a separate Claude Code chat in the background with its own model and a self-contained task, so several jobs run in parallel as independent threads. Returns at once; the answer arrives later as a message from Buddy. For quick side tasks inside this chat, use a background subagent instead.',
371 inputSchema: {
372 type: 'object',
373 properties: { task: { type: 'string', description: 'Complete, self-contained instructions' }, model: { type: 'string', description: 'sonnet, opus or fable (default sonnet)' } },
374 required: ['task'],
375 },
376 })
377 }
378 const recSaved = (await $.store.get('rec')) === true
379 await update($, recOn, () => recSaved)
380 // Lifetime caught counter, kept between sessions.
381 const saved = (await $.store.get('caught')) as Caught | undefined
382 if (saved) await update($, caught, () => saved)
383 // First memory reading, so Buddy's face is right before the first turn.
384 const usage = await $.session.usage()
385 if (usage?.context?.window) {
386 const pct = Math.round(usage.context.percent ?? ((usage.context.tokens ?? 0) / usage.context.window) * 100)
387 await update($, memory, () => pct)
388 }
389 // Redraw once a second so agent timers move.
390 $.clock.every(1000, () => update($, second, n => n + 1))
391 // Join the all-chats board, check in every 20s, and ping when another chat needs you.
392 try {
393 selfId = await $.session.id()
394 const folder = String(e.cwd ?? '').replace(/\\/g, '/').split('/').filter(Boolean).pop() ?? ''
395 await writeChat($, { status: 'idle', folder })
396 } catch {
397 // board only
398 }
399 $.clock.every(20000, async () => {
400 try {
401 // Recording mode is shared: switching it in one chat masks every chat within 20s.
402 const recNow = (await $.store.get('rec')) === true
403 if (recNow !== (await read($, recOn))) await update($, recOn, () => recNow)
404 await writeChat($, {})
405 const live = ((await $.store.get('jobs')) ?? {}) as Record<string, boolean>
406 // About a minute before the cache goes cold, say so, once per reply.
407 const last = await read($, lastTurnAt)
408 const panel = ((await $.store.get('settings')) ?? {}) as Record<string, unknown>
409 const ttl = Math.max(1, Number(panel.cacheMinutes ?? o.cacheMinutes ?? 60)) * 60000
410 const left = last + ttl - Date.now()
411 if ((live.cacheCheck ?? o.cacheCheck) === true && last > 0 && last !== warnedTurn && left > 0 && left <= 70000) {
412 warnedTurn = last
413 $.ui.toast('Buddy: your cache goes cold in about a minute. Send your next message now to keep it cheap.')
414 }
415 for (const row of await readChats($)) {
416 const before = seenStatus[row.id]
417 seenStatus[row.id] = row.status
418 if (row.id === selfId || before === undefined || before === row.status || live.chatBoard === false) continue
419 const name = row.title || row.folder || 'another chat'
420 if (row.status === 'waiting') $.ui.toast(`Buddy: "${name}" is waiting on you`)
421 else if (row.status === 'done' && before === 'working') $.ui.toast(`Buddy: "${name}" just finished`)
422 }
423 } catch {
424 // board only
425 }
426 })
427 return started
428 })
429
430 on('command.run', { command: 'buddy' }, async ($, e) => {
431 const [word, ...rest] = String(e.args ?? '').trim().split(/\s+/)
432 const pet = (((await $.store.get('pet')) as PetInfo | undefined) ?? NEW_PET)
433 if (word === 'reset') {
434 await update($, caught, () => ({ send: 0, spend: 0, danger: 0 }))
435 await $.store.set('caught', { send: 0, spend: 0, danger: 0 })
436 return { text: 'Buddy reset his "saved you from" counter.' }
437 }
438 if (word === 'rec') {
439 const turnOn = rest[0] === 'on' ? true : rest[0] === 'off' ? false : !(await read($, recOn))
440 await $.store.set('rec', turnOn)
441 await update($, recOn, () => turnOn)
442 return { text: turnOn ? 'Recording mode ON: keys, emails, phone numbers, money and hidden names are covered on screen in every chat.' : 'Recording mode OFF.' }
443 }
444 if (word === 'hatch') {
445 await $.store.set('pet', { ...pet, stage: 'egg' })
446 await update($, tick, n => n + 1)
447 await $.ui.open({ id: PANE, title: 'Buddy' })
448 return { text: 'A new egg appeared. Click it to hatch.' }
449 }
450 if (word === 'pet' && (SPECIES as readonly string[]).includes(rest[0] ?? '')) {
451 await $.store.set('pet', { ...pet, stage: 'pet', species: rest[0] })
452 await update($, tick, n => n + 1)
453 return { text: `${pet.name} is now a ${rest[0]}.` }
454 }
455 if (word === 'name' && rest.length > 0) {
456 const name = rest.join(' ').slice(0, 20)
457 await $.store.set('pet', { ...pet, name })
458 await update($, tick, n => n + 1)
459 return { text: `Your pet is now called ${name}.` }
460 }
461 await $.ui.open({ id: PANE, title: 'Buddy' })
462 return { text: 'Buddy is back. Try /buddy pet cat, /buddy name Rex, or /buddy hatch.' }
463 })
464
465 // Leaving the board when the chat ends.
466 on('session.end', async ($, e, next) => {
467 try {
468 await writeChat($, { status: 'closed' })
469 } catch {
470 // board only
471 }
472 return next(e)
473 })
474
475 // Any question to you (Claude's or Buddy's own) marks this chat "waiting on you" on the board.
476 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
477 try {
478 await writeChat($, { status: 'waiting' })
479 } catch {
480 // board only
481 }
482 const answered = await next(e)
483 try {
484 await writeChat($, { status: 'working' })
485 } catch {
486 // board only
487 }
488 return answered
489 })
490
491 // The pet posts here: an egg finished hatching, or someone petted it.
492 on('ui.message', async ($, e, next) => {
493 const data = (e.data ?? {}) as { hatched?: boolean; petted?: boolean }
494 const pet = (((await $.store.get('pet')) as PetInfo | undefined) ?? NEW_PET)
495 if (data.hatched && pet.stage === 'egg') {
496 const species = SPECIES[Math.floor(Math.random() * SPECIES.length)]
497 await $.store.set('pet', { ...pet, stage: 'pet', species })
498 $.ui.toast(`Your egg hatched: ${pet.name} is a ${species}!`)
499 await update($, tick, n => n + 1)
500 } else if (data.petted) {
501 await $.store.set('pet', { ...pet, pets: (pet.pets ?? 0) + 1 })
502 }
503 return next(e)
504 })
505
506 // Always-on strip above the prompt: works at any window width.
507 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
508 if (e.props?.hasSurvey) return next(e)
509 const { Box, Text } = $.ui.resolve(e)
510 const m = await read($, mood)
511 const mem = await read($, memory)
512 const c = await read($, caught)
513 const pet = (((await $.store.get('pet')) as PetInfo | undefined) ?? NEW_PET)
514 const [face] = faceFor(m, mem)
515 const rec = await read($, recOn)
516 await read($, tick)
517 const bandSettings = ((await $.store.get('settings')) ?? {}) as Record<string, unknown>
518 const bandKeep = Math.max(0.1, Number(bandSettings.todoDays ?? 1) || 1) * 86400000
519 const todoCount = (((await $.store.get('todos')) ?? []) as Todo[]).filter(t => !t.done && Date.now() - t.at < bandKeep).length
520 return (
521 <Box>
522 {rec && <Text color="red" bold>● REC </Text>}
523 {todoCount > 0 && <Text color="yellow" bold>☐ {todoCount} for you </Text>}
524 <Text color="yellow">{face} </Text>
525 <Text dimColor>
526 {pet.name} the {pet.stage === 'egg' ? 'egg' : pet.species} · memory {mem}% · saved you {total(c)}x · /buddy
527 </Text>
528 </Box>
529 )
530 })
531
532 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
533 const { Box, Button, Text } = $.ui.resolve(e)
534 await read($, tick)
535 const view = await read($, tab)
536 // Only the tabs with live timers redraw every second; the rest redraw when something changes.
537 if (view === 'status' || view === 'chats' || view === 'threads') await read($, second)
538 const now = await $.clock.now()
539 const m = await read($, mood)
540 const mem = await read($, memory)
541 const c = await read($, caught)
542 const [face, caption] = faceFor(m, mem)
543 const live = ((await $.store.get('jobs')) ?? {}) as Record<string, boolean>
544 // Anything that pops up a question is off until you switch it on; everything else is on.
545 const ASKS = ['sendGate', 'spendGate', 'dangerGuard', 'cacheCheck']
546 const isOn = (id: string) => (id === 'codex' ? o.codexEnabled === true : live[id] !== undefined ? live[id] : ASKS.includes(id) ? o[id] === true : o[id] !== false)
547
548 const switchTo = async (command: string, args: string) => {
549 try {
550 await $.command.run({ command, args })
551 } catch {
552 $.ui.toast(`Type /${command} ${args} to switch`)
553 }
554 }
555 const toggle = async (id: string) => {
556 const jobs = ((await $.store.get('jobs')) ?? {}) as Record<string, boolean>
557 const turnedOn = !isOn(id)
558 await $.store.set('jobs', { ...jobs, [id]: turnedOn })
559 $.ui.toast(`Buddy: ${JOBS.find(j => j.id === id)?.name} ${turnedOn ? 'ON' : 'OFF'}`)
560 await update($, tick, n => n + 1)
561 }
562 const compactNow = async () => {
563 try {
564 await $.session.compact({})
565 $.ui.toast('Buddy compacted the chat')
566 } catch {
567 $.ui.toast('Type /compact to compact')
568 }
569 }
570 const handoffNow = async () => {
571 try {
572 await $.command.run({ command: 'handoff', args: '' })
573 } catch {
574 $.ui.toast('Type /handoff')
575 }
576 }
577 const resetCount = async () => {
578 await update($, caught, () => ({ send: 0, spend: 0, danger: 0 }))
579 await $.store.set('caught', { send: 0, spend: 0, danger: 0 })
580 $.ui.toast('Buddy reset his caught counter')
581 }
582
583 // A titled card with a rounded border.
584 const card = (title: string, children: any, color = 'gray') => (
585 <Box flexDirection="column" borderStyle="round" borderColor={color} paddingX={1} marginBottom={1}>
586 <Text bold color={color === 'gray' ? undefined : color}>{title}</Text>
587 {children}
588 </Box>
589 )
590
591 const pet = (((await $.store.get('pet')) as PetInfo | undefined) ?? NEW_PET)
592 const { Client } = $.ui.resolve(e) as any
593 const rec = await read($, recOn)
594 const panelNames = ((await $.store.get('settings')) ?? {}) as Record<string, any>
595 const hide = nameList(panelNames.hideNames ?? o.hideNames)
596 const shown = (s: string) => (rec ? maskText(s, hide) : s)
597 const toggleRec = async () => {
598 const turnOn = !rec
599 await $.store.set('rec', turnOn)
600 await update($, recOn, () => turnOn)
601 $.ui.toast(turnOn ? 'Buddy: recording mode ON. Secrets, emails, money and hidden names are covered.' : 'Buddy: recording mode OFF')
602 }
603 // To-dos fade after a few days (Settings: To-dos last), so the list only holds what's blocking you now.
604 const todoSettings = ((await $.store.get('settings')) ?? {}) as Record<string, unknown>
605 const todoDays = Math.max(0.1, Number(todoSettings.todoDays ?? 1) || 1)
606 const todos = (((await $.store.get('todos')) ?? []) as Todo[]).filter(t => !t.done && Date.now() - t.at < todoDays * 86400000)
607 const doneAll = async () => {
608 for (const todo of todos) await finishTodo(todo, true)
609 }
610 const clearTodos = async () => {
611 const all = ((await $.store.get('todos')) ?? []) as Todo[]
612 const home = ((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.') as string
613 const file = `${home.replace(/\\/g, '/')}/.claude/buddy/todo-archive.json`
614 let old: unknown[] = []
615 try {
616 old = JSON.parse(await $.fs.read(file))
617 } catch {
618 old = []
619 }
620 await $.fs.write(file, JSON.stringify([...old, ...all.map(t => ({ ...t, clearedAt: Date.now() }))], null, 1))
621 await $.store.set('todos', [])
622 $.ui.toast('Buddy cleared your to-dos (saved in ~/.claude/buddy/todo-archive.json)')
623 await update($, tick, n => n + 1)
624 }
625 const finishTodo = async (todo: Todo, tell: boolean) => {
626 const all = ((await $.store.get('todos')) ?? []) as Todo[]
627 await $.store.set('todos', all.filter(t => t.id !== todo.id && !t.done).slice(-20))
628 await update($, tick, n => n + 1)
629 if (!tell) return
630 const text = `Done: ${todo.task}. Carry on.`
631 try {
632 if (todo.sessionId === selfId) await $.prompt.submit({ text })
633 else await $.session.send({ to: { sessionId: todo.sessionId }, text })
634 $.ui.toast("Buddy told Claude it's done")
635 } catch {
636 $.ui.toast(`Buddy couldn't reach that chat. Tell it: ${text}`)
637 }
638 }
639 const petMood = m !== 'holding' && mem >= 80 ? 'tired' : m
640
641 const header = (
642 <Box flexDirection="column" marginBottom={1}>
643 <Box borderStyle="round" borderColor="yellow" paddingX={1} flexDirection="column">
644 <Client
645 key="pet"
646 module="./pet.tsx"
647 height={7}
648 props={{ species: pet.species, mood: petMood, stage: pet.stage, name: pet.name, label: pet.stage === 'egg' ? '' : caption }}
649 />
650 </Box>
651 <Box gap={2}>
652 <Button key="rec-switch" variant={rec ? 'primary' : 'secondary'} label={rec ? '● REC ON' : 'Recording mode'} onPress={toggleRec} />
653 <Text dimColor>{rec ? 'Keys, emails, money and hidden names are covered on screen.' : 'Filming or sharing your screen? Press this first.'}</Text>
654 </Box>
655 <Box gap={2} marginTop={1} flexWrap="wrap">
656 <Button key="tab-status" variant={view === 'status' ? 'primary' : 'secondary'} label="Status" onPress={() => update($, tab, () => 'status')} />
657 <Button key="tab-chats" variant={view === 'chats' ? 'primary' : 'secondary'} label="Chats" onPress={() => update($, tab, () => 'chats')} />
658 <Button key="tab-threads" variant={view === 'threads' ? 'primary' : 'secondary'} label="Threads" onPress={() => update($, tab, () => 'threads')} />
659 <Button
660 key="tab-codex"
661 variant={view === 'codex' ? 'primary' : 'secondary'}
662 label="Codex"
663 onPress={async () => {
664 await update($, tab, () => 'codex')
665 // Show the remembered list at once, then refresh it in the background.
666 if ((await read($, cxThreads)) === null) {
667 const cached = (await $.store.get('cxThreadsCache')) as { threads: CodexThread[]; counts: Record<string, number> } | undefined
668 if (cached?.threads) {
669 await update($, cxThreads, () => cached.threads)
670 await update($, cxCounts, () => cached.counts ?? {})
671 }
672 }
673 void scanCodexForPanel($)
674 }}
675 />
676 <Button
677 key="tab-skills"
678 variant={view === 'skills' ? 'primary' : 'secondary'}
679 label="Skills"
680 onPress={async () => {
681 await update($, tab, () => 'skills')
682 void scanAllSkills($)
683 }}
684 />
685 <Button key="tab-jobs" variant={view === 'jobs' ? 'primary' : 'secondary'} label="Jobs" onPress={() => update($, tab, () => 'jobs')} />
686 <Button key="tab-pets" variant={view === 'pets' ? 'primary' : 'secondary'} label="Pets" onPress={() => update($, tab, () => 'pets')} />
687 <Button key="tab-settings" variant={view === 'settings' ? 'primary' : 'secondary'} label="Settings" onPress={() => update($, tab, () => 'settings')} />
688 <Button key="tab-help" variant={view === 'help' ? 'primary' : 'secondary'} label="Help" onPress={() => update($, tab, () => 'help')} />
689 </Box>
690 </Box>
691 )
692
693
694 const chats = await readChats($)
695 const ICON: Record<string, [string, string, string]> = {
696 waiting: ['⏳', 'yellow', 'waiting on you'],
697 working: ['●', 'cyan', 'working'],
698 done: ['✓', 'green', 'your turn'],
699 idle: ['○', 'gray', 'idle'],
700 }
701 const todoBy = (id: string) => todos.filter(t => t.sessionId === id).length
702 const { Input: BoardInput } = $.ui.resolve(e) as any
703 const messageChat = async (id: string, text: string) => {
704 if (!text.trim()) return
705 try {
706 const sent = await $.session.send({ to: { sessionId: id }, text: `[from another chat, via Buddy] ${text.trim()}` })
707 $.ui.toast(sent.isDelivered ? 'Buddy delivered your message' : `Not delivered: ${sent.reason}`)
708 } catch {
709 $.ui.toast("Buddy couldn't reach that chat")
710 }
711 }
712 const chatRow = (row: ChatRow) => {
713 const [icon, color, word] = ICON[row.status] ?? ['○', 'gray', row.status]
714 return (
715 <Box flexDirection="column">
716 <Text>
717 <Text color={color}>{icon} {word}</Text>
718 <Text dimColor> {ago(Date.now() - row.since)}</Text>
719 <Text bold> {shown(row.title || 'new chat')}</Text>
720 {row.id === selfId ? <Text dimColor> (this chat)</Text> : null}
721 </Text>
722 <Text dimColor> {shown(row.folder)}{todoBy(row.id) > 0 ? ` · ☐ ${todoBy(row.id)} for you` : ''}</Text>
723 {view === 'chats' && row.id !== selfId && (
724 <BoardInput key={`msg-${row.id}`} placeholder="Message this chat..." submitLabel="send" onSubmit={(v: string) => messageChat(row.id, v)} />
725 )}
726 </Box>
727 )
728 }
729 const waitingCount = chats.filter(r => r.status === 'waiting').length
730 const boardCard = card(
731 waitingCount > 0 ? `Your chats · ${waitingCount} waiting on you` : `Your chats · ${chats.length} open`,
732 <Box flexDirection="column" gap={1}>
733 {chats.length === 0 && <Text dimColor>Open Claude Code chats show up here.</Text>}
734 {chats.slice(0, view === 'chats' ? 20 : 3).map(chatRow)}
735 {view !== 'chats' && chats.length > 3 && <Text dimColor>+{chats.length - 3} more in the Chats tab</Text>}
736 </Box>,
737 waitingCount > 0 ? 'yellow' : 'cyan',
738 )
739
740 const todoCard =
741 todos.length > 0 &&
742 card(
743 `For you to do · ${todos.length}`,
744 <Box flexDirection="column" gap={1}>
745 {todos.slice(0, 5).map(todo => (
746 <Box flexDirection="column">
747 <Box gap={2}>
748 <Button key={`todo-done-${todo.id}`} variant="primary" label="Done" onPress={() => finishTodo(todo, true)} />
749 <Button key={`todo-skip-${todo.id}`} label="Skip" onPress={() => finishTodo(todo, false)} />
750 <Text bold>{shown(todo.task)}</Text>
751 </Box>
752 <Text dimColor>
753 {' '}
754 {todo.chat ? `from "${shown(todo.chat)}"` : 'from a chat'}
755 {todo.sessionId === selfId ? ' (this chat)' : ''}
756 {todo.doneWhen ? ` · done when ${shown(todo.doneWhen)}` : ''}
757 </Text>
758 </Box>
759 ))}
760 {todos.length > 5 && <Text dimColor>+{todos.length - 5} more</Text>}
761 <Box gap={2}>
762 <Button key="todo-done-all" label="Done all" onPress={doneAll} />
763 <Button key="todo-clear" label="Skip all" onPress={clearTodos} />
764 </Box>
765 <Box>
766 <Text dimColor>
767 Done tells that chat to carry on. Skip clears it. To-dos fade after {todoDays} day{todoDays === 1 ? '' : 's'} (change it in Settings).
768 </Text>
769 </Box>
770 </Box>,
771 'yellow',
772 )
773
774 if (view === 'codex') {
775 const { Input: CInput } = $.ui.resolve(e) as any
776 const panel = ((await $.store.get('settings')) ?? {}) as Record<string, any>
777 const cxOn = (panel.codexEnabled ?? o.codexEnabled) === true
778 const cxModel = String(panel.codexModel ?? o.codexModel ?? 'gpt-5.5')
779 const jobs = await read($, codexJobs)
780 const threads = await read($, cxThreads)
781 const counts = await read($, cxCounts)
782 const cxo = await read($, cxOpen)
783 const canEdit = await read($, cxEdit)
784 const peeked = await read($, peek)
785 const cx = async (args: string) => {
786 try {
787 await $.command.run({ command: 'buddy-codex', args })
788 } catch {
789 $.ui.toast(`Type /buddy-codex ${args}`)
790 }
791 }
792 const turnOn = async () => {
793 const cur = ((await $.store.get('settings')) ?? {}) as Record<string, unknown>
794 await $.store.set('settings', { ...cur, codexEnabled: true })
795 $.ui.toast('Buddy: Codex team ON')
796 await update($, tick, n => n + 1)
797 }
798 const jobIcon = (s: string) => (s === 'running' ? ['● working', 'cyan'] : s === 'failed' ? ['✗ failed', 'red'] : ['✓ done', 'green'])
799 if (!cxOn) {
800 return (
801 <Box flexDirection="column">
802 {header}
803 {card(
804 'Codex team is off',
805 <Box flexDirection="column" gap={1}>
806 <Text>Turn it on to let Claude start and message OpenAI Codex agents, and to see your Codex threads here.</Text>
807 <Text dimColor>Needs the Codex CLI installed and logged in. Whatever you or Claude send to Codex goes to OpenAI.</Text>
808 <Box>
809 <Button key="cx-on" variant="primary" label="Turn on Codex team" onPress={turnOn} />
810 </Box>
811 </Box>,
812 'magenta',
813 )}
814 </Box>
815 )
816 }
817 const conv = await read($, cxConv)
818 if (conv.id) {
819 const { Markdown } = $.ui.resolve(e) as any
820 const steps = await read($, cxSteps)
821 const live = jobs.filter(j => j.threadId === conv.id || j.id === conv.id).sort((a, b) => b.startedAt - a.startedAt)[0]
822 const pending = live && (live.status === 'running' || (live.endedAt ?? 0) > conv.loadedAt) ? live : undefined
823 const all = conv.entries.filter(en => steps || en.role !== 'step')
824 // Show the last `shown` messages (steps between them ride along).
825 let cut = all.length
826 for (let n = 0; cut > 0 && n < conv.shown; ) {
827 cut--
828 if (all[cut].role !== 'step') n++
829 }
830 const visible = all.slice(cut)
831 // Like the Codex app: your messages in a bubble on the right, Codex's replies on the left.
832 const say = (role: 'you' | 'codex', text: string, k: string) =>
833 role === 'you' ? (
834 <Box flexDirection="row" justifyContent="flex-end" marginBottom={1}>
835 <Box width="75%" borderStyle="round" borderColor="gray" paddingX={1}>
836 <Text>{shown(text.slice(0, 9000))}</Text>
837 </Box>
838 </Box>
839 ) : (
840 <Box flexDirection="column" marginBottom={1} width="95%">
841 {Markdown ? <Markdown key={k} text={shown(text.slice(0, 9000))} /> : <Text>{shown(text.slice(0, 9000))}</Text>}
842 </Box>
843 )
844 return (
845 <Box flexDirection="column">
846 {header}
847 <Box gap={2} flexWrap="wrap">
848 <Button key="cx-back" label="← Back" onPress={() => update($, cxConv, c => ({ ...c, id: '' }))} />
849 <Text bold>{shown(conv.name)}</Text>
850 <Text dimColor>{shown(conv.folder)}</Text>
851 <Button key="cx-steps" plain label={steps ? 'Hide steps' : 'Show steps'} onPress={() => update($, cxSteps, s => !s)} />
852 <Button key="cx-reload" plain label="Reload" onPress={() => loadCodexConversation($, conv.id, conv.name, conv.folder, conv.bytes, conv.shown)} />
853 </Box>
854 <Text> </Text>
855 {conv.loading && <Text dimColor>Loading the conversation...</Text>}
856 {!conv.loading && (all.length > visible.length || (conv.cutOff && conv.bytes < 50331648)) && (
857 <Box marginBottom={1}>
858 <Button
859 key="cx-earlier"
860 plain
861 label="↑ Load earlier messages"
862 onPress={() =>
863 all.length > visible.length
864 ? update($, cxConv, c => ({ ...c, shown: c.shown + 20 }))
865 : loadCodexConversation($, conv.id, conv.name, conv.folder, Math.min(conv.bytes * 4, 50331648), conv.shown + 20)
866 }
867 />
868 </Box>
869 )}
870 {!conv.loading && conv.cutOff && conv.bytes >= 50331648 && all.length <= visible.length && <Text dimColor>That's as far back as Buddy reads in a very long thread.</Text>}
871 {!conv.loading && all.length === 0 && <Text dimColor>No messages yet.</Text>}
872 {visible.map((en, i) => (en.role === 'step' ? <Text dimColor> · {shown(en.text)}</Text> : say(en.role, en.text, `cx-m-${i}`)))}
873 {pending && pending.lastPrompt && say('you', pending.lastPrompt, 'cx-pending-you')}
874 {pending && pending.status === 'running' && <Text color="cyan">● Codex is working{pending.lastAction ? `: ${shown(pending.lastAction)}` : '...'}</Text>}
875 {pending && pending.status !== 'running' && pending.answer && say('codex', pending.answer, 'cx-pending-codex')}
876 {(!pending || pending.status !== 'running') && (
877 <CInput
878 key={`cx-conv-msg-${conv.id}`}
879 placeholder="Message Codex..."
880 submitLabel="send"
881 onSubmit={async (v: string) => {
882 if (!v.trim()) return
883 await cx(`msg ${conv.id} ${v.trim()}`)
884 await scrollConvToEnd($)
885 }}
886 />
887 )}
888 </Box>
889 )
890 }
891 return (
892 <Box flexDirection="column">
893 {header}
894 <Text dimColor>Claude is the lead; Codex agents work for it. Start one, message any Codex thread, watch them work.</Text>
895 <Text> </Text>
896 {card(
897 'Start a Codex agent',
898 <Box flexDirection="column" gap={1}>
899 <Box gap={2} flexWrap="wrap">
900 <Button key="cx-read" variant={!canEdit ? 'primary' : 'secondary'} label="Read-only" onPress={() => update($, cxEdit, () => false)} />
901 <Button key="cx-edit" variant={canEdit ? 'primary' : 'secondary'} label="Can edit files" onPress={() => update($, cxEdit, () => true)} />
902 <Text dimColor>Model: {cxModel} (change it in Settings)</Text>
903 </Box>
904 <CInput
905 key="cx-task"
906 placeholder="What should Codex do? e.g. review notes.md and list every weak sentence"
907 submitLabel="start"
908 onSubmit={(v: string) => v.trim() && cx(`start ${cxModel} ${canEdit ? 'edit' : 'read'} ${v.trim()}`)}
909 />
910 <Text dimColor>{canEdit ? 'Can edit files: you are asked to confirm before it starts.' : 'Read-only: Codex can look but not change anything.'}</Text>
911 </Box>,
912 'magenta',
913 )}
914 {card(
915 jobs.some(j => j.status === 'running') ? `Codex agents · ${jobs.filter(j => j.status === 'running').length} working` : 'Codex agents',
916 <Box flexDirection="column" gap={1}>
917 {jobs.length === 0 && <Text dimColor>None yet. Start one above, or ask Claude to "have Codex review this".</Text>}
918 {jobs.map(job => {
919 const [icon, color] = jobIcon(job.status)
920 const busy = job.status === 'running'
921 return (
922 <Box flexDirection="column">
923 <Text>
924 <Text color={color}>{icon}</Text>
925 <Text bold> {shown(job.task.slice(0, 60))}</Text>
926 <Text dimColor>
927 {' '}· started by {job.by} · {job.model} · {job.canEdit ? 'can edit' : 'read-only'} · {ago((job.endedAt ?? Date.now()) - job.startedAt)}
928 {job.tokens ? ` · ${Math.round(job.tokens / 1000)}K tokens` : ''}
929 {busy && job.lastAction ? ` · now: ${shown(job.lastAction)}` : ''}
930 </Text>
931 </Text>
932 {!busy && (
933 <Box gap={2} marginLeft={3}>
934 {job.answer && (
935 <Button key={`cx-ans-${job.id}`} label={peeked?.id === job.id ? 'Hide answer' : 'Answer'} onPress={() => update($, peek, () => (peeked?.id === job.id ? null : { id: job.id, text: job.answer ?? '' }))} />
936 )}
937 </Box>
938 )}
939 {!busy && (
940 <Box marginLeft={3}>
941 <CInput key={`cx-msg-${job.id}`} placeholder="Next message to this Codex agent..." submitLabel="send" onSubmit={(v: string) => v.trim() && cx(`msg ${job.id} ${v.trim()}`)} />
942 </Box>
943 )}
944 {peeked && peeked.id === job.id && <Text dimColor>{shown(peeked.text.slice(0, 1500))}</Text>}
945 </Box>
946 )
947 })}
948 </Box>,
949 'cyan',
950 )}
951 {card(
952 'Your Codex threads',
953 <Box flexDirection="column" gap={1}>
954 {threads === null && <Text dimColor>Reading your Codex threads... (the first time takes a few seconds)</Text>}
955 {threads !== null && threads.length === 0 && <Text dimColor>No Codex threads in the last 60 days.</Text>}
956 {byProject(threads ?? []).map(group => {
957 const total = counts[group.project] ?? group.threads.length
958 const expanded = cxo.project === group.project
959 const list = expanded ? group.threads : group.threads.slice(0, 3)
960 return (
961 <Box flexDirection="column">
962 <Text>
963 <Text bold color="magenta">▸ {shown(group.folder)}</Text>
964 <Text dimColor> · {total} thread{total === 1 ? '' : 's'}</Text>
965 </Text>
966 {list.map(th => {
967 const working = th.status === 'working' || jobs.some(j => j.threadId === th.id && j.status === 'running')
968 const open = cxo.thread === th.id
969 return (
970 <Box flexDirection="column" marginLeft={2}>
971 <Box gap={1}>
972 <Button
973 key={`cx-open-${th.id}`}
974 plain
975 label={`${working ? '●' : '○'} ${shown(th.name.slice(0, 44))}`}
976 onPress={() => loadCodexConversation($, th.id, th.name, th.folder)}
977 />
978 <Text dimColor>{ago(Date.now() - th.updatedAt)} ago{th.from === 'Codex CLI' ? ' · CLI' : ''}</Text>
979 </Box>
980 {open && (
981 <Box flexDirection="column" marginLeft={2}>
982 <Text dimColor>{th.lastReply ? shown(th.lastReply) : 'No reply yet.'}</Text>
983 {!working ? (
984 <CInput key={`cx-tmsg-${th.id}`} placeholder="Message this Codex thread..." submitLabel="send" onSubmit={(v: string) => v.trim() && cx(`msg ${th.id} ${v.trim()}`)} />
985 ) : (
986 <Text color="cyan">Working right now. Message it when it's done.</Text>
987 )}
988 </Box>
989 )}
990 </Box>
991 )
992 })}
993 {total > list.length && (
994 <Box marginLeft={2}>
995 <Button
996 key={`cx-more-${group.project}`}
997 plain
998 label={expanded ? 'Show less' : `Show all ${total}`}
999 onPress={async () => {
1000 await update($, cxOpen, v => ({ ...v, project: expanded ? '' : group.project }))
1001 if (!expanded) await scanCodexForPanel($, group.project)
1002 }}
1003 />
1004 </Box>
1005 )}
1006 </Box>
1007 )
1008 })}
1009 <Box gap={2}>
1010 <Button
1011 key="cx-refresh"
1012 label="Refresh"
1013 onPress={async () => {
1014 lastCodexScan = 0
1015 await scanCodexForPanel($, cxo.project)
1016 }}
1017 />
1018 <Text dimColor>Click a thread to open the full conversation. Last 60 days, grouped by project like the Codex app.</Text>
1019 </Box>
1020 </Box>,
1021 )}
1022 </Box>
1023 )
1024 }
1025
1026 if (view === 'skills') {
1027 const { Input: SInput } = $.ui.resolve(e) as any
1028 const scan = await read($, skillScan)
1029 const sv = await read($, skillView)
1030 const use = ((await $.store.get('skillUse')) ?? {}) as SkillUse
1031 const since = (await $.store.get('skillUseSince')) as number | undefined
1032 const items = scan?.items ?? []
1033 const usesOf = (it: SkillItem) => use[it.name]?.count ?? 0
1034 const q = sv.q.trim().toLowerCase()
1035 const filtered = items
1036 .filter(it => !q || it.name.toLowerCase().includes(q) || it.description.toLowerCase().includes(q))
1037 .sort((a, b) =>
1038 sv.sort === 'used'
1039 ? usesOf(b) - usesOf(a) || a.name.localeCompare(b.name)
1040 : sv.sort === 'unused'
1041 ? usesOf(a) - usesOf(b) || b.descChars - a.descChars
1042 : b.descChars - a.descChars,
1043 )
1044 const tokens = Math.round(items.reduce((sum, it) => sum + it.descChars, 0) / 4)
1045 const neverUsed = items.filter(it => usesOf(it) === 0).length
1046 const dupes = new Set(items.filter((it, i) => items.findIndex(x => x.name === it.name) !== i).map(it => it.name))
1047 const setView = (patch: Partial<typeof sv>) => update($, skillView, v => ({ ...v, ...patch }))
1048 const act = async (args: string) => {
1049 try {
1050 await $.command.run({ command: 'buddy-skills', args })
1051 } catch {
1052 $.ui.toast(`Type /buddy-skills ${args}`)
1053 }
1054 await scanAllSkills($)
1055 }
1056 const folderOf = (it: SkillItem) => it.path.slice(it.path.lastIndexOf('/') + 1)
1057 const sortBtn = (id: 'used' | 'unused' | 'big', label: string) => (
1058 <Button key={`ssort-${id}`} variant={sv.sort === id ? 'primary' : 'secondary'} label={label} onPress={() => setView({ sort: id, shown: 15 })} />
1059 )
1060 const lastUsed = (it: SkillItem) => (use[it.name] ? `used ${use[it.name].count}x · last ${ago(Date.now() - use[it.name].last)} ago` : 'never used')
1061 return (
1062 <Box flexDirection="column">
1063 {header}
1064 <Text dimColor>Every skill you have, how often Claude really uses it, and what it costs. Copy, move or delete with one click.</Text>
1065 <Text> </Text>
1066 {card(
1067 'Your skills',
1068 <Box flexDirection="column" gap={1}>
1069 {!scan && <Text dimColor>Scanning...</Text>}
1070 {scan && (
1071 <Box flexDirection="column">
1072 {rec ? (
1073 <Text dimColor>Skill counts and names are hidden while recording.</Text>
1074 ) : (
1075 <Text>
1076 <Text bold>{items.filter(i => i.scope === 'project').length}</Text> in this project · <Text bold>{items.filter(i => i.scope === 'global').length}</Text> global ·{' '}
1077 <Text bold color={neverUsed > 0 ? 'yellow' : 'green'}>{neverUsed}</Text> never used
1078 </Text>
1079 )}
1080 <Text color="yellow">About {tokens.toLocaleString()} tokens of skill names and descriptions ride along in every chat (estimate)</Text>
1081 <Text dimColor>{since ? `Counting use since ${new Date(since).toLocaleDateString()}. ` : 'Counting starts now: each skill Claude loads is counted. '}Counts cover every chat and project.</Text>
1082 {dupes.size > 0 && <Text color="yellow">Same name in two places: {rec ? `${dupes.size} skills` : [...dupes].slice(0, 6).join(', ')}</Text>}
1083 {rec && <Text color="red">● Recording: skill names and descriptions are hidden.</Text>}
1084 {scan.codexLink && <Text dimColor>This project shares its skills with Codex (.agents/skills). Moving a skill out of the project removes it for Codex too.</Text>}
1085 </Box>
1086 )}
1087 <Box gap={2} flexWrap="wrap">
1088 {sortBtn('used', 'Most used')}
1089 {sortBtn('unused', 'Never used')}
1090 {sortBtn('big', 'Biggest')}
1091 <Button key="sscan" label="Rescan" onPress={() => scanAllSkills($)} />
1092 </Box>
1093 <SInput key="squery" placeholder="Search skills..." submitLabel="search" onSubmit={(v: string) => setView({ q: v, shown: 15 })} />
1094 {sv.q && <Text dimColor>Showing matches for "{sv.q}" · <Text color="cyan">clear by searching for nothing</Text></Text>}
1095 </Box>,
1096 'magenta',
1097 )}
1098 {filtered.slice(0, sv.shown).map(it => {
1099 const key = `${it.scope}:${folderOf(it)}`
1100 const opened = sv.open === key
1101 return (
1102 <Box flexDirection="column" marginBottom={1}>
1103 <Box gap={2}>
1104 <Button key={`sopen-${key}`} label={opened ? 'Close' : 'Manage'} onPress={() => setView({ open: opened ? '' : key })} />
1105 <Text>
1106 <Text bold>{rec ? '█'.repeat(Math.min(12, Math.max(4, it.name.length))) : it.name}</Text>
1107 <Text color={it.scope === 'project' ? 'cyan' : 'magenta'}> {it.scope === 'project' ? 'this project' : 'global'}</Text>
1108 {it.isLink && <Text dimColor> · linked</Text>}
1109 <Text color={usesOf(it) > 0 ? 'green' : 'yellow'}> · {lastUsed(it)}</Text>
1110 <Text dimColor> · ~{Math.round(it.descChars / 4)} tokens</Text>
1111 </Text>
1112 </Box>
1113 {opened && (
1114 <Box flexDirection="column" marginLeft={4} gap={1}>
1115 <Text dimColor>{rec ? 'Hidden while recording.' : it.description || '(no description)'}</Text>
1116 {it.isLink ? (
1117 <Text dimColor>This one is a linked folder, managed somewhere else. Buddy won't copy, move or delete it.</Text>
1118 ) : (
1119 <Box flexDirection="column" gap={1}>
1120 <Box gap={2} flexWrap="wrap">
1121 {it.scope === 'project' && <Button key={`sg-${key}`} label="Make global (copy)" onPress={() => act(`global ${folderOf(it)}`)} />}
1122 {it.scope === 'project' && <Button key={`sm-${key}`} label="Move to global" onPress={() => act(`moveglobal ${folderOf(it)}`)} />}
1123 {it.scope === 'global' && <Button key={`sh-${key}`} label="Add to this project" onPress={() => act(`here ${folderOf(it)}`)} />}
1124 <Button key={`sd-${key}`} label="Delete" onPress={() => act(`delete ${key}`)} />
1125 </Box>
1126 <SInput
1127 key={`sc-${key}`}
1128 placeholder="Copy to another project: paste its folder path"
1129 submitLabel="copy"
1130 onSubmit={(v: string) => v.trim() && act(`copy ${key} ${v.trim()}`)}
1131 />
1132 <Text dimColor>Copies keep the original. Move and Delete ask first and keep a backup in ~/.claude/buddy/skill-backups.</Text>
1133 </Box>
1134 )}
1135 </Box>
1136 )}
1137 </Box>
1138 )
1139 })}
1140 {filtered.length > sv.shown && <Button key="smore" label={rec ? 'Show more' : `Show more (${filtered.length - sv.shown} left)`} onPress={() => setView({ shown: sv.shown + 25 })} />}
1141 </Box>
1142 )
1143 }
1144
1145 if (view === 'threads') {
1146 const { Input: TInput } = $.ui.resolve(e) as any
1147 const model = await read($, threadModel)
1148 const kind = await read($, threadKind)
1149 const live = await read($, agentLive)
1150 const threads = await read($, chatThreads)
1151 const peeked = await read($, peek)
1152 const metaAll = ((await $.store.get('agentMeta')) ?? {}) as Record<string, { by: string; model: string }>
1153 let helpers: { id: string; description: string; type: string; status: string; parentId?: string; spawnedBy?: string }[] = []
1154 try {
1155 helpers = (await $.agent.list()) as any
1156 } catch {
1157 helpers = []
1158 }
1159 const rowsById = Object.fromEntries((await read($, agents)).map(r => [r.id, r]))
1160 const startThread = async (task: string) => {
1161 const text = task.trim()
1162 if (!text) return
1163 if (kind === 'chat') {
1164 try {
1165 await $.command.run({ command: 'thread', args: text })
1166 } catch {
1167 $.ui.toast('Type /thread followed by the task')
1168 }
1169 return
1170 }
1171 try {
1172 const started = await $.agent.spawn({ prompt: text, description: text.slice(0, 40), model })
1173 if (started.agentId) {
1174 const meta = ((await $.store.get('agentMeta')) ?? {}) as Record<string, unknown>
1175 await $.store.set('agentMeta', { ...meta, [started.agentId]: { by: 'you', model } })
1176 $.ui.toast(`Buddy started a ${model} helper`)
1177 } else $.ui.toast(`Not started: ${started.deny ?? 'refused'}`)
1178 } catch (err) {
1179 $.ui.toast(`Couldn't start it: ${String((err as Error)?.message ?? err).slice(0, 80)}`)
1180 }
1181 await update($, tick, n => n + 1)
1182 }
1183 const peekAgent = async (id: string) => {
1184 try {
1185 const rows = (await $.session.messages({ agentId: id })) as any
1186 const list = Array.isArray(rows) ? rows : []
1187 const text = list
1188 .slice(-4)
1189 .map((r: any) => `${r.role === 'assistant' ? 'Helper' : 'Task'}: ${String(r.text ?? '').replace(/\s+/g, ' ').slice(0, 220)}`)
1190 .join('\n')
1191 await update($, peek, () => ({ id, text: text || 'Nothing to show yet.' }))
1192 } catch {
1193 await update($, peek, () => ({ id, text: "Couldn't read that helper's messages." }))
1194 }
1195 }
1196 const messageAgent = async (id: string, text: string) => {
1197 if (!text.trim()) return
1198 try {
1199 const sent = await $.session.send({ to: { agentId: id }, text: text.trim() })
1200 $.ui.toast(sent.isDelivered ? 'Buddy passed your message on' : `Not delivered: ${sent.reason}`)hooks/jobs/extras.tsx 202 lines1import { atom, read, update } from 'claude-code'
2
3import type { Limit } from '../../types'
4
5// Buddy's shared state (same keys in every file, so every job sees the same values).
6const limits = atom({ plugin: 'buddy', key: 'limits' } as const, [] as Limit[])
7const forecast = atom({ plugin: 'buddy', key: 'forecast' } as const, { limits: {}, repliesLeft: null } as { limits: Record<string, { fullAt?: number; resetsAt?: string }>; repliesLeft: number | null })
8const cost = atom({ plugin: 'buddy', key: 'cost' } as const, 0)
9const editing = atom({ plugin: 'buddy', key: 'editing' } as const, [] as string[])
10const codexLog = atom({ plugin: 'buddy', key: 'codexLog' } as const, [] as string[])
11const codexStatus = atom({ plugin: 'buddy', key: 'codexStatus' } as const, '')
12
13type Options = {
14 lockedFiles?: string
15 houseRules?: string
16 codexEnabled?: boolean
17 codexModel?: string
18}
19
20const list = (text: string | undefined, sep: RegExp) =>
21 (text ?? '')
22 .split(sep)
23 .map(s => s.trim())
24 .filter(Boolean)
25
26const norm = (p: string) => p.replace(/\\/g, '/').toLowerCase()
27
28// A locked entry matches a file name, a path ending, or a folder ("contracts/").
29const isLocked = (path: string, locked: string[]) => {
30 const p = norm(path)
31 return locked.some(raw => {
32 const l = norm(raw)
33 if (l.endsWith('/')) return p.includes('/' + l) || p.startsWith(l)
34 return p === l || p.endsWith('/' + l)
35 })
36}
37
38const short = (text: string, max: number) => (text.length > max ? text.slice(0, max - 1) + '…' : text)
39
40// Runs Codex read-only on one task and streams its progress into Buddy's pane.
41// Returns Codex's final answer, or why there is none.
42async function runCodex($: any, task: string, model: string, cwd: string): Promise<string> {
43 await update($, codexStatus, () => 'running')
44 await update($, codexLog, () => [`▶ ${short(task, 70)}`])
45 let answer = ''
46 let buffer = ''
47 const run = $.process.spawn({
48 argv: ['codex', 'exec', '-m', model, '-s', 'read-only', '--skip-git-repo-check', '--ephemeral', '--json', '-C', cwd, task],
49 input: '',
50 })
51 for await (const chunk of run) {
52 if (chunk.stream !== 'stdout') continue
53 buffer += chunk.text
54 const lines = buffer.split('\n')
55 buffer = lines.pop() ?? ''
56 for (const line of lines) {
57 let ev: any
58 try {
59 ev = JSON.parse(line)
60 } catch {
61 continue
62 }
63 const item = ev.item
64 if (ev.type === 'item.completed' && item?.type === 'agent_message') {
65 answer = String(item.text ?? '')
66 await update($, codexLog, l => [...l, `💬 ${short(answer.replace(/\s+/g, ' '), 70)}`].slice(-8))
67 } else if (ev.type === 'item.started' && item?.type === 'command_execution') {
68 await update($, codexLog, l => [...l, `$ ${short(String(item.command ?? ''), 70)}`].slice(-8))
69 } else if (ev.type === 'turn.completed') {
70 const used = ev.usage?.input_tokens ?? 0
71 await update($, codexLog, l => [...l, `✓ done (${Math.round(used / 1000)}k tokens in)`].slice(-8))
72 }
73 }
74 }
75 await update($, codexStatus, () => (answer ? 'done' : 'no answer'))
76 return answer || 'Codex finished without an answer. Check that `codex` is installed and logged in.'
77}
78
79// Settings saved in Buddy's panel win over the config file.
80async function readSettings($: any, options: Options): Promise<Options> {
81 return { ...options, ...(((await $.store.get('settings')) ?? {}) as Options) }
82}
83
84export function registerExtras(on: any, options: Options) {
85
86 // Locked files and the work receipt both watch file edits.
87 on('tool.call', { tool: ['Edit', 'Write', 'NotebookEdit'] }, async ($: any, e: any, next: any) => {
88 const path = String(e.file_path ?? e.notebook_path ?? '')
89 const live = ((await $.store.get('jobs')) ?? {}) as Record<string, boolean>
90 const locked = list((await readSettings($, options)).lockedFiles, /,/)
91 if (live.lockedFiles !== false && path && isLocked(path, locked)) {
92 $.ui.toast(`Buddy kept Claude out of a locked file: ${short(path, 60)}`)
93 const log = ((await $.store.get('log')) ?? []) as any[]
94 await $.store.set('log', [{ at: Date.now(), kind: 'locked', what: `edit ${short(path, 80)}`, choice: 'blocked (locked file)' }, ...log].slice(0, 20))
95 return { deny: `${path} is locked in Buddy's settings. Don't edit it; tell the user what you wanted to change.` }
96 }
97 const ran = await next(e)
98 if (path && ran?.deny === undefined && ran?.isError !== true) {
99 await update($, editing, files => (files.includes(path) ? files : [...files, path]))
100 }
101 return ran
102 })
103
104 // Limits and cost, pushed after every turn and when a limit moves a point.
105 on('session.measure', async ($: any, e: any, next: any) => {
106 const before = await read($, limits)
107 const now: Limit[] = (e.rateLimits ?? []).map((r: any) => ({ kind: r.kind, percentUsed: r.percentUsed, resetsAt: r.resetsAt }))
108 await update($, limits, () => now)
109 await update($, cost, () => Number(e.cost?.usd ?? 0))
110 // Forecasts: from the last hour of readings, when each limit runs out at this pace,
111 // and how many more replies this chat has before it's nearly full.
112 try {
113 const t = Date.now()
114 const hist = (((await $.store.get('limitHistory')) ?? {}) as Record<string, { t: number; p: number }[]>)
115 const out: Record<string, { fullAt?: number; resetsAt?: string }> = {}
116 for (const r of now) {
117 let h = (hist[r.kind] ?? []).filter(s => t - s.t < 3600000)
118 if (h.length && r.percentUsed < h[h.length - 1].p) h = [] // the window reset
119 h = [...h, { t, p: r.percentUsed }].slice(-60)
120 hist[r.kind] = h
121 const first = h[0]
122 const rate = h.length > 1 && t - first.t > 300000 ? (r.percentUsed - first.p) / (t - first.t) : 0
123 out[r.kind] = { resetsAt: r.resetsAt, fullAt: rate > 0 ? t + (100 - r.percentUsed) / rate : undefined }
124 }
125 await $.store.set('limitHistory', hist)
126 const usage = await $.session.usage()
127 const pct = Number(usage?.context?.percent ?? 0)
128 const mem = (((await $.store.get(`memHistory`)) ?? {}) as Record<string, number[]>)
129 const sid = await $.session.id()
130 const series = [...(mem[sid] ?? []), pct].slice(-8)
131 mem[sid] = series
132 const keys = Object.keys(mem)
133 if (keys.length > 30) delete mem[keys[0]]
134 await $.store.set('memHistory', mem)
135 const steps = series.slice(1).map((v, i) => v - series[i]).filter(d => d > 0)
136 const avg = steps.length >= 2 ? steps.reduce((a, b) => a + b, 0) / steps.length : 0
137 const repliesLeft = avg > 0 && pct < 90 ? Math.max(0, Math.floor((90 - pct) / avg)) : null
138 await update($, forecast, () => ({ limits: out, repliesLeft }))
139 } catch {
140 // forecasts are a nice-to-have
141 }
142 for (const r of now) {
143 const was = before.find(b => b.kind === r.kind)?.percentUsed ?? 0
144 if (r.percentUsed >= 80 && was < 80) $.ui.toast(`Buddy: you've used ${Math.round(r.percentUsed)}% of your ${r.kind} limit`)
145 }
146 return next(e)
147 })
148
149 // House rules ride along with every new chat, unseen.
150 {
151 on('prompt.context', async ($: any, e: any, next: any) => {
152 const got = await next(e)
153 const live = ((await $.store.get('jobs')) ?? {}) as Record<string, boolean>
154 const rules = list((await readSettings($, options)).houseRules, /[\n;]/)
155 const blocks = [...got.blocks]
156 if (live.todoInbox !== false) {
157 blocks.push({
158 name: 'buddy-todo-inbox',
159 text:
160 'The user runs Buddy, which keeps a short to-do list of things blocking your work. Call mcp__buddy__todo_for_you only when you are stuck and cannot finish the task until the user does something only they can do, such as add an API key, log in, or install an app. Do not add questions or decisions (ask those in your reply), reminders, optional follow-ups, or things they can do any time. At most one per reply. Keep it to one short sentence starting with a verb.',
161 })
162 }
163 if (live.houseRules === false || rules.length === 0) return { ...got, blocks }
164 const text = "The user's house rules (from Buddy). Follow them in every reply:\n" + rules.map(r => `- ${r}`).join('\n')
165 return { ...got, blocks: [...blocks, { name: 'buddy-house-rules', text }] }
166 })
167 }
168
169 // Handoff note: a summary of this chat, saved to a file, ready for a fresh chat.
170 on('command.run', { command: 'handoff' }, async ($: any, e: any) => {
171 const reply = await $.model.fork({
172 prompt:
173 'Write a handoff note for continuing this work in a fresh chat. Sections: Goal, What is done, Decisions made, Files involved, Next steps, Open questions. Be specific and short. Markdown only.',
174 })
175 if (!reply.isAnswered) return { text: `Buddy couldn't write a handoff yet (${reply.reason}).` }
176 const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
177 const file = `handoff-${stamp}.md`
178 await $.fs.write(file, reply.text)
179 return { text: `Handoff saved to ${file}. Start a new chat and say: "Read ${file} and continue."` }
180 })
181
182 // Codex sidekick: opt-in, read-only.
183 {
184 on('tool.call', { tool: 'mcp__buddy__codex' }, async ($: any, e: any) => {
185 const s = await readSettings($, options)
186 if (s.codexEnabled !== true) return { result: 'The Codex sidekick is switched off in Buddy settings.' }
187 const answer = await runCodex($, String(e.task ?? ''), (s.codexModel ?? 'gpt-5.5').trim() || 'gpt-5.5', String(e.cwd ?? '.'))
188 return { result: answer }
189 })
190
191 on('command.run', { command: 'codex' }, async ($: any, e: any) => {
192 const task = String(e.args ?? '').trim()
193 if (!task) return { text: 'Usage: /codex <task>' }
194 const s = await readSettings($, options)
195 if (s.codexEnabled !== true) return { text: 'Turn on the Codex sidekick in Buddy > Settings first.' }
196 await $.ui.open({ id: 'buddy', title: 'Buddy' })
197 const answer = await runCodex($, task, (s.codexModel ?? 'gpt-5.5').trim() || 'gpt-5.5', '.')
198 return { text: `Codex says:\n\n${answer}` }
199 })
200 }
201}
202hooks/jobs/guards.tsx 129 lines1import { atom, update } from 'claude-code'
2
3import { classify, describeArgs, setExtraPaidHosts, toMeOnly } from '../lib/patterns.ts'
4import type { Hit } from '../lib/patterns.ts'
5import type { AgentRow, Caught, Mood } from '../../types'
6
7// Buddy's shared state (same keys in every file, so every job sees the same values).
8const caught = atom({ plugin: 'buddy', key: 'caught' } as const, { send: 0, spend: 0, danger: 0 } as Caught)
9const lastHeld = atom({ plugin: 'buddy', key: 'lastHeld' } as const, '')
10const mood = atom({ plugin: 'buddy', key: 'mood' } as const, 'sleepy' as Mood)
11const agentLive = atom({ plugin: 'buddy', key: 'agentLive' } as const, {} as Record<string, { tool?: string; steps: number; lastAt: number }>)
12
13// The send gate, spend gate and danger guard share one tool.call hook.
14// Each held call is answered through Buddy's own question, so it still asks when
15// Claude Code runs with permissions bypassed. Anything that breaks denies (fail closed).
16
17type Options = { myEmail?: string; sendGate?: boolean; spendGate?: boolean; dangerGuard?: boolean; paidApis?: string }
18
19const today = () => new Date().toISOString().slice(0, 10)
20
21const JOB_FOR: Record<Hit['kind'], 'sendGate' | 'spendGate' | 'dangerGuard'> = { send: 'sendGate', spend: 'spendGate', danger: 'dangerGuard' }
22
23// A job is on unless the settings or the Jobs tab switched it off.
24const enabled = (hit: Hit, o: Options, live: Record<string, boolean> | undefined) => {
25 const job = JOB_FOR[hit.kind]
26 if (live && live[job] !== undefined) return live[job]
27 return (o as any)[job] === true
28}
29
30const TITLES: Record<Hit['kind'], string> = {
31 send: 'Buddy is holding something that would leave your machine.',
32 spend: 'Buddy is holding a paid API call.',
33 danger: 'Buddy is holding a command that can delete or overwrite work.',
34}
35
36type LogEntry = { at: number; kind: string; what: string; choice: string }
37type Approvals = { date: string; targets: string[] }
38
39// Buddy's activity log: the last 20 things he held and what you chose.
40async function logEvent($: any, entry: LogEntry) {
41 const log = ((await $.store.get('log')) ?? []) as LogEntry[]
42 await $.store.set('log', [entry, ...log].slice(0, 20))
43}
44
45// "Approve all today" list, visible and undoable from the panel.
46async function approvedToday($: any, target: string) {
47 const a = ((await $.store.get('approvals')) ?? { date: '', targets: [] }) as Approvals
48 return a.date === today() && a.targets.includes(target)
49}
50
51async function approveToday($: any, target: string) {
52 const a = ((await $.store.get('approvals')) ?? { date: '', targets: [] }) as Approvals
53 const targets = a.date === today() ? a.targets : []
54 await $.store.set('approvals', { date: today(), targets: targets.includes(target) ? targets : [...targets, target] })
55}
56
57export function registerGuards(on: any, options: Options) {
58 setExtraPaidHosts(options.paidApis)
59 on('tool.call', async ($: any, e: any, next: any) => {
60 // Threads tab: what each helper agent is doing right now.
61 if (e.agentId) {
62 const id = e.agentId as string
63 try {
64 await update($, agentLive, (all: Record<string, { tool?: string; steps: number; lastAt: number }>) => ({ ...all, [id]: { steps: all[id]?.steps ?? 0, tool: String(e.tool), lastAt: Date.now() } }))
65 } catch {
66 // display only
67 }
68 }
69 // Settings saved in Buddy's panel win over the config file.
70 const s = { ...options, ...(((await $.store.get('settings')) ?? {}) as Options) }
71 setExtraPaidHosts(s.paidApis)
72 const hit = classify(String(e.tool), e as Record<string, unknown>)
73 if (!hit) return next(e)
74 const live = (await $.store.get('jobs')) as Record<string, boolean> | undefined
75 if (!enabled(hit, s, live)) return next(e)
76
77 if (hit.kind !== 'danger' && (await approvedToday($, hit.target))) {
78 await logEvent($, { at: Date.now(), kind: hit.kind, what: hit.what, choice: 'approved earlier today' })
79 return next(e)
80 }
81
82 const detail = describeArgs(e as Record<string, unknown>)
83 const summary = detail ? `${hit.what}. ${detail}` : hit.what
84 await update($, lastHeld, () => `${hit.kind}: ${summary}`)
85 await update($, mood, () => 'holding')
86
87 const myEmail = (s.myEmail ?? '').trim()
88 const choices =
89 hit.kind === 'danger'
90 ? ['Proceed', 'Cancel']
91 : hit.kind === 'send' && hit.canSendToMe && myEmail
92 ? ['Send', 'Send to me first', 'Approve all today', 'Cancel']
93 : [hit.kind === 'send' ? 'Send' : 'Approve', 'Approve all today', 'Cancel']
94
95 let answer = 'Cancel'
96 try {
97 answer = await $.ui.ask(`${TITLES[hit.kind]} ${summary}. Let it go?`, choices)
98 } catch {
99 answer = 'Cancel' // dismissed, nobody to ask, or anything broke: nothing goes out
100 }
101 await update($, mood, () => 'working')
102 await logEvent($, { at: Date.now(), kind: hit.kind, what: summary.slice(0, 140), choice: answer.slice(0, 80) })
103
104 if (answer === 'Send' || answer === 'Approve' || answer === 'Proceed') return next(e)
105 if (answer === 'Approve all today') {
106 await approveToday($, hit.target)
107 return next(e)
108 }
109 if (answer === 'Send to me first') {
110 const rewritten = toMeOnly(e as Record<string, unknown>, myEmail)
111 if (!rewritten) return { deny: 'Buddy could not find a recipient to rewrite, so nothing was sent.' }
112 await update($, lastHeld, () => `send: test copy to ${myEmail} only (${hit.what})`)
113 await update($, caught, c => ({ ...c, send: c.send + 1 }))
114 return next(rewritten)
115 }
116
117 await update($, caught, c => ({ ...c, [hit.kind]: c[hit.kind] + 1 }))
118 if (answer !== 'Cancel') {
119 return { deny: `Not sent. The user answered Buddy with: "${answer}". Do what they said, then ask again.` }
120 }
121 return { deny: `Cancelled by the user in Buddy's ${hit.kind} guard. Nothing happened.` }
122 }).catch(($: any, e: any, next: any) => {
123 // Fail closed for anything Buddy guards; every other tool carries on as normal.
124 // When unsure whether a guard is on, treat it as on.
125 const hit = classify(String(e.tool), e as Record<string, unknown>)
126 return hit && enabled(hit, options, undefined) ? { deny: "Buddy's guard hit an error, so nothing was run or sent." } : next(e)
127 })
128}
129hooks/jobs/power.tsx 86 lines1import { atom, read, update } from 'claude-code'
2
3import { maskDeep, maskText, nameList } from '../lib/mask.ts'
4
5// Buddy's shared state (same keys in every file, so every job sees the same values).
6const recOn = atom({ plugin: 'buddy', key: 'recOn' } as const, false)
7const tick = atom({ plugin: 'buddy', key: 'tick' } as const, 0)
8
9type Options = { hideNames?: string }
10
11export type Todo = { id: string; task: string; doneWhen?: string; sessionId: string; chat: string; at: number; done?: boolean }
12
13// Names to hide on screen: the settings panel wins over the install options.
14async function hiddenNames($: any, options: Options): Promise<string[]> {
15 const panel = ((await $.store.get('settings')) ?? {}) as Options
16 return nameList(panel.hideNames ?? options.hideNames)
17}
18
19export function registerPower(on: any, options: Options) {
20 // ---------- Recording mode: mask the transcript while you film or share your screen ----------
21 // Each hook reads `recOn`, so flipping it redraws every row at once.
22 on('ui.render', { component: 'UserMessage' }, async ($: any, e: any, next: any) => {
23 if (!(await read($, recOn))) return next(e)
24 const names = await hiddenNames($, options)
25 return next({ ...e, props: { ...e.props, text: maskText(String(e.props.text ?? ''), names) } })
26 })
27 on('ui.render', { component: 'AssistantMessage' }, async ($: any, e: any, next: any) => {
28 if (!(await read($, recOn))) return next(e)
29 const names = await hiddenNames($, options)
30 return next({ ...e, props: { ...e.props, text: maskText(String(e.props.text ?? ''), names) } })
31 })
32 on('ui.render', { component: 'CommandOutput' }, async ($: any, e: any, next: any) => {
33 if (!(await read($, recOn))) return next(e)
34 const names = await hiddenNames($, options)
35 return next({ ...e, props: { ...e.props, text: maskText(String(e.props.text ?? ''), names) } })
36 })
37 on('ui.render', { component: 'ToolUse' }, async ($: any, e: any, next: any) => {
38 if (!(await read($, recOn))) return next(e)
39 const names = await hiddenNames($, options)
40 const props = { ...e.props, input: maskDeep(e.props.input, names) }
41 if (e.props.output !== undefined) props.output = maskDeep(e.props.output, names)
42 return next({ ...e, props })
43 })
44 on('ui.render', { component: 'ToolResult' }, async ($: any, e: any, next: any) => {
45 if (!(await read($, recOn))) return next(e)
46 const names = await hiddenNames($, options)
47 return next({ ...e, props: { ...e.props, output: maskDeep(e.props.output, names) } })
48 })
49
50 // ---------- To-do inbox: things only you can do, handed to Buddy instead of buried in a reply ----------
51 on('tool.call', { tool: 'mcp__buddy__todo_for_you' }, async ($: any, e: any) => {
52 const live = ((await $.store.get('jobs')) ?? {}) as Record<string, boolean>
53 if (live.todoInbox === false) return { result: 'The to-do inbox is off in Buddy. Tell the user in your reply instead.' }
54 const task = String(e.task ?? '').trim().slice(0, 140)
55 if (!task) return { result: 'Give the task in one short sentence.' }
56 const sessionId = await $.session.id()
57 let chat = ''
58 try {
59 const home = ((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.') as string
60 const row = JSON.parse(await $.fs.read(`${home.replace(/\\/g, '/')}/.claude/buddy/chats/${sessionId}.json`))
61 chat = row.folder || row.title || ''
62 } catch {
63 chat = ''
64 }
65 const todo: Todo = {
66 id: `${Date.now().toString(36)}${Math.floor(Math.random() * 1e4)}`,
67 task,
68 doneWhen: e.doneWhen ? String(e.doneWhen).slice(0, 140) : undefined,
69 sessionId,
70 chat,
71 at: Date.now(),
72 }
73 const list = ((await $.store.get('todos')) ?? []) as Todo[]
74 const panel = ((await $.store.get('settings')) ?? {}) as Record<string, unknown>
75 const keepMs = Math.max(0.1, Number(panel.todoDays ?? 1) || 1) * 86400000
76 await $.store.set('todos', [...list.filter(t => !t.done && Date.now() - t.at < keepMs), todo].slice(-10))
77 await $.ui.open({ id: 'buddy', title: 'Buddy' })
78 $.ui.toast(`Buddy: new to-do for you: ${task}`)
79 await update($, tick, (n: number) => n + 1)
80 return {
81 result:
82 'Added to the user\'s Buddy to-do list. They press Done when finished and you will get a message saying so. Carry on with anything that does not depend on it; otherwise stop and wait.',
83 }
84 })
85}
86hooks/jobs/threads.tsx 187 lines1import { atom, read, update } from 'claude-code'
2
3// Threads: one chat runs a team. Helper agents inside this chat, separate background
4// Claude chats, and messages to any other open chat, all managed from Buddy's Threads tab.
5
6export type AgentLive = { tool?: string; steps: number; lastAt: number }
7export type AgentMeta = { by: string; model: string; task: string }
8export type ChatThread = {
9 id: string
10 sessionId?: string
11 task: string
12 model: string
13 by: string
14 status: 'starting' | 'running' | 'done' | 'failed'
15 startedAt: number
16 endedAt?: number
17 lastTool?: string
18 answer?: string
19 turns: number
20}
21
22const agentLive = atom({ plugin: 'buddy', key: 'agentLive' } as const, {} as Record<string, AgentLive>)
23const chatThreads = atom({ plugin: 'buddy', key: 'chatThreads' } as const, [] as ChatThread[])
24const threadModel = atom({ plugin: 'buddy', key: 'threadModel' } as const, 'sonnet')
25
26type Options = { threadPermission?: string }
27
28const short = (text: string, max: number) => (text.length > max ? text.slice(0, max - 1) + '…' : text)
29
30async function boardDir($: any): Promise<string> {
31 const home = ((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.') as string
32 return `${home.replace(/\\/g, '/')}/.claude/buddy/chats`
33}
34
35// Every open chat from the board files (the same files the Chats tab reads).
36async function listBoard($: any): Promise<{ id: string; title: string; folder: string; status: string }[]> {
37 const dir = await boardDir($)
38 if (!(await $.fs.exists(dir))) return []
39 const self = await $.session.id()
40 const rows: { id: string; title: string; folder: string; status: string }[] = []
41 for (const ent of await $.fs.list(dir)) {
42 if (ent.kind !== 'file' || !ent.name.endsWith('.json')) continue
43 try {
44 const row = JSON.parse(await $.fs.read(`${dir}/${ent.name}`))
45 if (row.status !== 'closed' && Date.now() - row.updatedAt < 180000 && row.id !== self) rows.push({ id: row.id, title: row.title ?? '', folder: row.folder ?? '', status: row.status })
46 } catch {
47 // skip unreadable files
48 }
49 }
50 return rows
51}
52
53// Runs one turn of a separate background Claude chat (a fresh one, or the next message to one
54// that already exists via --resume) and keeps its row in the Threads tab up to date.
55async function runChatThread($: any, id: string, prompt: string, options: Options, tellLead: boolean) {
56 const rows = await read($, chatThreads)
57 const row = rows.find(r => r.id === id)
58 if (!row) return
59 const panel = ((await $.store.get('settings')) ?? {}) as Options
60 const mode = String(panel.threadPermission ?? options.threadPermission ?? 'acceptEdits').trim() || 'acceptEdits'
61 const argv = ['claude', '-p', '--output-format', 'stream-json', '--verbose', '--model', row.model, '--permission-mode', mode]
62 if (row.sessionId) argv.push('--resume', row.sessionId)
63 argv.push(prompt)
64 const set = (patch: Partial<ChatThread>) => update($, chatThreads, (list: ChatThread[]) => list.map(r => (r.id === id ? { ...r, ...patch } : r)))
65 await set({ status: 'running', endedAt: undefined })
66 let answer = ''
67 let failed = ''
68 try {
69 const child = $.process.spawn({ argv, cwd: await $.session.cwd(), env: { BUDDY_CHILD: '1' }, input: '' })
70 let buffer = ''
71 for await (const piece of child) {
72 if (piece.stream !== 'stdout' || typeof piece.text !== 'string') continue
73 buffer += piece.text
74 const lines = buffer.split('\n')
75 buffer = lines.pop() ?? ''
76 for (const line of lines) {
77 let ev: any
78 try {
79 ev = JSON.parse(line)
80 } catch {
81 continue
82 }
83 if (ev.type === 'system' && ev.session_id) await set({ sessionId: ev.session_id })
84 if (ev.type === 'assistant') {
85 const tools = (ev.message?.content ?? []).filter((c: any) => c.type === 'tool_use').map((c: any) => c.name)
86 if (tools.length > 0) await set({ lastTool: tools[tools.length - 1] })
87 }
88 if (ev.type === 'result') {
89 answer = String(ev.result ?? '')
90 if (ev.is_error) failed = answer || 'the chat ended with an error'
91 if (ev.session_id) await set({ sessionId: ev.session_id })
92 }
93 }
94 }
95 } catch (err) {
96 failed = String((err as Error)?.message ?? err).slice(0, 200)
97 }
98 const cur = (await read($, chatThreads)).find(r => r.id === id)
99 await set({ status: failed ? 'failed' : 'done', endedAt: Date.now(), answer: short(failed || answer, 4000), turns: (cur?.turns ?? 0) + 1 })
100 $.ui.toast(failed ? `Buddy: "${short(row.task, 40)}" failed` : `Buddy: separate chat "${short(row.task, 40)}" finished`)
101 if (tellLead) {
102 const text = failed
103 ? `[Buddy] Separate chat ${id} ("${short(row.task, 60)}") failed: ${short(failed, 400)}`
104 : `[Buddy] Separate chat ${id} ("${short(row.task, 60)}") finished. Its answer:\n\n${short(answer, 6000)}`
105 try {
106 await $.prompt.submit({ text })
107 } catch {
108 // the answer stays in the Threads tab
109 }
110 }
111}
112
113export function registerThreads(on: any, options: Options) {
114 // Live steps for each helper agent: one step per model request in its loop.
115 on('turn.step', async function* ($: any, e: any, next: any) {
116 if (e.agentId) {
117 const id = e.agentId as string
118 try {
119 await update($, agentLive, (all: Record<string, AgentLive>) => ({ ...all, [id]: { ...(all[id] ?? { steps: 0 }), steps: (all[id]?.steps ?? 0) + 1, lastAt: Date.now() } }))
120 } catch {
121 // display only
122 }
123 }
124 return yield* next(e)
125 })
126
127 // The lead chat's tools: see the other chats, message them, and start separate ones.
128 on('tool.call', { tool: 'mcp__buddy__list_chats' }, async ($: any) => {
129 const rows = await listBoard($)
130 const threads = await read($, chatThreads)
131 return {
132 result: JSON.stringify({
133 openChats: rows,
134 separateChatsStartedHere: threads.map(t => ({ id: t.id, task: t.task, model: t.model, status: t.status, answer: t.answer ? short(t.answer, 500) : undefined })),
135 }),
136 }
137 })
138
139 on('tool.call', { tool: 'mcp__buddy__message_chat' }, async ($: any, e: any) => {
140 const target = String(e.chatId ?? '').trim()
141 const text = String(e.text ?? '').trim()
142 if (!target || !text) return { result: 'Give chatId and text.' }
143 const threads = await read($, chatThreads)
144 const mine = threads.find(t => t.id === target || t.sessionId === target)
145 if (mine) {
146 if (mine.status === 'running' || mine.status === 'starting') return { result: `Separate chat ${mine.id} is still working. Wait for its answer, then message it.` }
147 void runChatThread($, mine.id, text, options, true)
148 return { result: `Sent to separate chat ${mine.id}. Its reply will arrive as a new message from Buddy.` }
149 }
150 const sent = await $.session.send({ to: { sessionId: target }, text: `[from another chat, via Buddy] ${text}` })
151 $.ui.toast(sent.isDelivered ? 'Buddy delivered your message' : `Buddy couldn't deliver it: ${sent.reason}`)
152 return { result: sent.isDelivered ? 'Delivered to that chat.' : `Not delivered: ${sent.reason}` }
153 })
154
155 // /thread <task> starts a separate chat from the panel; /thread msg <id> <text> sends it the next message.
156 on('command.run', { command: 'thread' }, async ($: any, e: any) => {
157 const args = String(e.args ?? '').trim()
158 const m = args.match(/^msg\s+(\S+)\s+([\s\S]+)$/)
159 if (m) {
160 const row = (await read($, chatThreads)).find(r => r.id === m[1])
161 if (!row) return { text: `No separate chat called ${m[1]}.` }
162 if (row.status === 'running' || row.status === 'starting') return { text: 'That chat is still working. Message it when it finishes.' }
163 void runChatThread($, row.id, m[2], options, false)
164 return { text: `Sent to ${row.id}.` }
165 }
166 if (!args) return { text: 'Usage: /thread <task> · /thread msg <id> <text>' }
167 const model = await read($, threadModel)
168 const id = `t${Date.now().toString(36).slice(-5)}`
169 await update($, chatThreads, (list: ChatThread[]) => [...list, { id, task: short(args, 300), model, by: 'you', status: 'starting' as const, startedAt: Date.now(), turns: 0 }].slice(-12))
170 void runChatThread($, id, args, options, false)
171 return { text: `Started separate chat ${id} on ${model}. Watch it in Buddy's Threads tab.` }
172 })
173
174 on('tool.call', { tool: 'mcp__buddy__start_chat' }, async ($: any, e: any) => {
175 const task = String(e.task ?? '').trim()
176 if (!task) return { result: 'Give the task.' }
177 const model = String(e.model ?? 'sonnet').trim() || 'sonnet'
178 const id = `t${Date.now().toString(36).slice(-5)}`
179 await update($, chatThreads, (list: ChatThread[]) => [...list, { id, task: short(task, 300), model, by: 'Claude', status: 'starting' as const, startedAt: Date.now(), turns: 0 }].slice(-12))
180 await $.ui.open({ id: 'buddy', title: 'Buddy' })
181 void runChatThread($, id, task, options, true)
182 return {
183 result: `Started separate chat ${id} on ${model}. It runs in the background; its answer will arrive as a new message from Buddy. Message it later with mcp__buddy__message_chat using chatId "${id}". Carry on meanwhile.`,
184 }
185 })
186}
187hooks/jobs/skills.tsx 211 lines1import { atom, read, update } from 'claude-code'
2
3// Skills manager: every skill you have (global and this project), how often Claude actually
4// uses each one, what their descriptions cost every chat, and copy / move / delete between
5// projects. Copies and deletes back up first, never touch linked folders, and ask before deleting.
6
7export type SkillItem = {
8 name: string
9 scope: 'global' | 'project'
10 path: string
11 isLink: boolean
12 descChars: number
13 description: string
14}
15export type SkillScan = { at: number; cwd: string; items: SkillItem[]; codexLink: boolean }
16export type SkillUse = Record<string, { count: number; last: number }>
17
18const skillScan = atom({ plugin: 'buddy', key: 'skillScan' } as const, null as SkillScan | null)
19const tick = atom({ plugin: 'buddy', key: 'tick' } as const, 0)
20
21export const norm = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '')
22const quotePs = (p: string) => `'${p.replace(/'/g, "''")}'`
23
24// Reads the name and description from a SKILL.md's frontmatter (single line, quoted, or a | / > block).
25export function frontmatter(text: string): { name?: string; description: string } {
26 const m = text.match(/^---\s*\n([\s\S]*?)\n---/)
27 if (!m) return { description: '' }
28 const lines = m[1].split('\n')
29 let name: string | undefined
30 let description = ''
31 for (let i = 0; i < lines.length; i++) {
32 const line = lines[i]
33 const nm = line.match(/^name:\s*(.+)$/)
34 if (nm) name = nm[1].trim().replace(/^["']|["']$/g, '')
35 const dm = line.match(/^description:\s*(.*)$/)
36 if (dm) {
37 const first = dm[1].trim()
38 if (first === '|' || first === '>' || first === '|-' || first === '>-' || first === '') {
39 const block: string[] = []
40 for (let j = i + 1; j < lines.length && /^\s+\S/.test(lines[j]); j++) block.push(lines[j].trim())
41 description = block.join(' ')
42 } else description = first.replace(/^["']|["']$/g, '')
43 }
44 }
45 return { name, description }
46}
47
48async function homeDir($: any): Promise<string> {
49 return norm(((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.') as string)
50}
51
52async function scanDir($: any, dir: string, scope: 'global' | 'project'): Promise<SkillItem[]> {
53 if (!(await $.fs.exists(dir))) return []
54 const out: SkillItem[] = []
55 for (const ent of await $.fs.list(dir)) {
56 if (ent.name.startsWith('.')) continue
57 const path = `${dir}/${ent.name}`
58 if (ent.kind !== 'dir' && !ent.isLink) continue
59 let text = ''
60 try {
61 text = await $.fs.read(`${path}/SKILL.md`)
62 } catch {
63 continue
64 }
65 const fm = frontmatter(text)
66 out.push({
67 name: fm.name || ent.name,
68 scope,
69 path,
70 isLink: Boolean(ent.isLink),
71 descChars: fm.description.length + (fm.name || ent.name).length,
72 description: fm.description.slice(0, 220),
73 })
74 }
75 return out
76}
77
78async function runScan($: any): Promise<SkillScan> {
79 const home = await homeDir($)
80 const cwd = norm(await $.session.cwd())
81 const global = await scanDir($, `${home}/.claude/skills`, 'global')
82 const project = cwd === home ? [] : await scanDir($, `${cwd}/.claude/skills`, 'project')
83 const codexLink = await $.fs.exists(`${cwd}/.agents/skills`)
84 const scan: SkillScan = { at: Date.now(), cwd, items: [...project, ...global], codexLink }
85 await update($, skillScan, () => scan)
86 return scan
87}
88
89// True when the folder, or anything inside it, is a link: Buddy never moves or deletes through one.
90async function hasLink($: any, dir: string, depth = 0): Promise<boolean> {
91 if (depth > 6) return true
92 const st = await $.fs.stat(dir)
93 if (st.isLink) return true
94 for (const ent of await $.fs.list(dir)) {
95 if (ent.isLink || ent.kind === 'other') return true
96 if (ent.kind === 'dir' && (await hasLink($, `${dir}/${ent.name}`, depth + 1))) return true
97 }
98 return false
99}
100
101async function copyDir($: any, src: string, dst: string): Promise<string> {
102 const windows = (await $.env.get('OS')) === 'Windows_NT'
103 const parent = dst.slice(0, dst.lastIndexOf('/'))
104 const r = windows
105 ? await $.process.run([
106 'powershell',
107 '-NoProfile',
108 '-NonInteractive',
109 '-Command',
110 `New-Item -ItemType Directory -Force -Path ${quotePs(parent)} | Out-Null; Copy-Item -LiteralPath ${quotePs(src)} -Destination ${quotePs(dst)} -Recurse -Force`,
111 ])
112 : await $.process.run(['sh', '-c', 'mkdir -p "$1" && cp -R "$2" "$3"', 'sh', parent, src, dst])
113 return r.exitCode === 0 ? '' : (r.stderr || r.stdout || 'copy failed').slice(0, 200)
114}
115
116async function removeDir($: any, path: string): Promise<string> {
117 const windows = (await $.env.get('OS')) === 'Windows_NT'
118 const r = windows
119 ? await $.process.run(['powershell', '-NoProfile', '-NonInteractive', '-Command', `Remove-Item -LiteralPath ${quotePs(path)} -Recurse -Force`])
120 : await $.process.run(['rm', '-rf', path])
121 return r.exitCode === 0 ? '' : (r.stderr || r.stdout || 'delete failed').slice(0, 200)
122}
123
124// Copies a skill to a destination skills folder; with `move`, backs up and removes the original after asking.
125async function placeSkill($: any, item: SkillItem, destSkillsDir: string, move: boolean, label: string): Promise<string> {
126 const folder = item.path.slice(item.path.lastIndexOf('/') + 1)
127 const dst = `${norm(destSkillsDir)}/${folder}`
128 if (norm(dst) === norm(item.path)) return 'It is already there.'
129 if (await $.fs.exists(dst)) return `${label} already has a skill folder called ${folder}. Nothing changed.`
130 if (await hasLink($, item.path)) return `${item.name} is (or contains) a linked folder. Buddy only copies and moves real folders, so nothing changed.`
131 const err = await copyDir($, item.path, dst)
132 if (err) return `Copy failed: ${err}`
133 if (!move) return `Copied ${item.name} to ${label}.`
134 let answer = ''
135 try {
136 answer = await $.ui.ask(`Buddy copied ${item.name} to ${label}. Remove the original from ${item.scope === 'project' ? 'this project' : 'your global skills'}? A backup is kept in ~/.claude/buddy/skill-backups.`, ['Remove the original', 'Keep both'])
137 } catch {
138 answer = ''
139 }
140 if (answer !== 'Remove the original') return `Copied ${item.name} to ${label} and kept the original.`
141 const backup = `${await homeDir($)}/.claude/buddy/skill-backups/${folder}-${new Date().toISOString().replace(/[:.]/g, '-')}`
142 const berr = await copyDir($, item.path, backup)
143 if (berr) return `Copied, but the backup failed (${berr}), so the original was kept.`
144 const rerr = await removeDir($, item.path)
145 return rerr ? `Copied and backed up, but removing the original failed: ${rerr}` : `Moved ${item.name} to ${label}. Backup kept.`
146}
147
148async function deleteSkill($: any, item: SkillItem): Promise<string> {
149 if (await hasLink($, item.path)) return `${item.name} is (or contains) a linked folder. Buddy won't delete it.`
150 let answer = ''
151 try {
152 answer = await $.ui.ask(`Delete the skill ${item.name} from ${item.scope === 'project' ? 'this project' : 'your global skills'}? Buddy keeps a backup in ~/.claude/buddy/skill-backups.`, ['Delete it', 'Cancel'])
153 } catch {
154 answer = ''
155 }
156 if (answer !== 'Delete it') return 'Nothing deleted.'
157 const folder = item.path.slice(item.path.lastIndexOf('/') + 1)
158 const backup = `${await homeDir($)}/.claude/buddy/skill-backups/${folder}-${new Date().toISOString().replace(/[:.]/g, '-')}`
159 const berr = await copyDir($, item.path, backup)
160 if (berr) return `Backup failed (${berr}), so nothing was deleted.`
161 const rerr = await removeDir($, item.path)
162 return rerr ? `Backed up, but the delete failed: ${rerr}` : `Deleted ${item.name}. Backup kept.`
163}
164
165export function registerSkills(on: any) {
166 // Usage: every time Claude loads a skill, count it (kept across chats and projects).
167 on('tool.call', { tool: 'Skill' }, async ($: any, e: any, next: any) => {
168 try {
169 const name = String(e.skill ?? '').replace(/^\//, '')
170 if (name) {
171 const use = ((await $.store.get('skillUse')) ?? {}) as SkillUse
172 const since = (await $.store.get('skillUseSince')) as number | undefined
173 if (!since) await $.store.set('skillUseSince', Date.now())
174 await $.store.set('skillUse', { ...use, [name]: { count: (use[name]?.count ?? 0) + 1, last: Date.now() } })
175 }
176 } catch {
177 // counting only
178 }
179 return next(e)
180 })
181
182 // /buddy-skills scan | copy <scope>:<folder> <project path> | here <folder> | global <folder> | moveglobal <folder> | delete <scope>:<folder>
183 on('command.run', { command: 'buddy-skills' }, async ($: any, e: any) => {
184 const args = String(e.args ?? '').trim()
185 const [verb, ref, ...rest] = args.split(/\s+/)
186 const scan = verb === 'scan' || !verb ? await runScan($) : ((await read($, skillScan)) ?? (await runScan($)))
187 if (verb === 'scan' || !verb) {
188 await update($, tick, (n: number) => n + 1)
189 return { text: `Buddy found ${scan.items.length} skills.` }
190 }
191 const [scope, folder] = (ref ?? '').includes(':') ? (ref ?? '').split(':') : ['', ref ?? '']
192 const item = scan.items.find(i => i.path.endsWith(`/${folder}`) && (!scope || i.scope === scope))
193 if (!item) return { text: `No skill folder called ${folder}.` }
194 const home = await homeDir($)
195 let msg = ''
196 if (verb === 'copy') {
197 const target = norm(rest.join(' ').replace(/^["']|["']$/g, ''))
198 if (!target || !(await $.fs.exists(target))) msg = `That project folder doesn't exist: ${target || '(empty)'}`
199 else msg = await placeSkill($, item, `${target}/.claude/skills`, false, target.split('/').pop() ?? target)
200 } else if (verb === 'here') msg = await placeSkill($, item, `${scan.cwd}/.claude/skills`, false, 'this project')
201 else if (verb === 'global') msg = await placeSkill($, item, `${home}/.claude/skills`, false, 'your global skills')
202 else if (verb === 'moveglobal') msg = await placeSkill($, item, `${home}/.claude/skills`, true, 'your global skills')
203 else if (verb === 'delete') msg = await deleteSkill($, item)
204 else return { text: 'Usage: /buddy-skills scan | here <folder> | global <folder> | moveglobal <folder> | copy <scope>:<folder> <project path> | delete <scope>:<folder>' }
205 await runScan($)
206 await update($, tick, (n: number) => n + 1)
207 $.ui.toast(`Buddy: ${msg}`)
208 return { text: msg }
209 })
210}
211hooks/jobs/codexteam.tsx 240 lines1import { atom, read, update } from 'claude-code'
2
3import { dayDirs, dumpArgv, idFromFile, parseDump, parseIndex } from '../lib/codexthreads.ts'
4import type { CodexThread } from '../lib/codexthreads.ts'
5
6// Codex team: Claude (and you) start Codex agents, message any Codex thread, and watch them work.
7// Codex runs through its own CLI. Buddy always passes the sandbox explicitly: read-only unless you
8// approve file edits for that one run, because a user's Codex config may default to full access.
9
10export type CodexJob = {
11 id: string
12 threadId?: string
13 task: string
14 model: string
15 canEdit: boolean
16 by: string
17 status: 'running' | 'done' | 'failed'
18 startedAt: number
19 endedAt?: number
20 lastAction?: string
21 answer?: string
22 tokens?: number
23 turns: number
24 lastPrompt?: string
25}
26
27const codexJobs = atom({ plugin: 'buddy', key: 'codexJobs' } as const, [] as CodexJob[])
28const cxConv = atom({ plugin: 'buddy', key: 'cxConv' } as const, { id: '', name: '', folder: '', loading: false, entries: [] as { role: 'you' | 'codex' | 'step'; text: string }[], cutOff: false, loadedAt: 0, shown: 60 })
29
30const short = (text: string, max: number) => (text.length > max ? text.slice(0, max - 1) + '…' : text)
31
32type Options = { codexEnabled?: boolean; codexModel?: string }
33
34async function codexOn($: any, options: Options): Promise<boolean> {
35 const panel = ((await $.store.get('settings')) ?? {}) as Options
36 return (panel.codexEnabled ?? options.codexEnabled) === true
37}
38
39async function defaultModel($: any, options: Options): Promise<string> {
40 const panel = ((await $.store.get('settings')) ?? {}) as Options
41 return String(panel.codexModel ?? options.codexModel ?? 'gpt-5.5').trim() || 'gpt-5.5'
42}
43
44
45// Your recent Codex threads (app and CLI), newest first: name, folder, working or idle, last reply.
46async function scanCodexThreads($: any, limit = 15): Promise<CodexThread[]> {
47 const home = (((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.') as string).replace(/\\/g, '/')
48 const windows = (await $.env.get('OS')) === 'Windows_NT'
49 const files: { path: string; id: string; mtime: number }[] = []
50 for (const dir of dayDirs(home, 14)) {
51 if (!(await $.fs.exists(dir))) continue
52 for (const ent of await $.fs.list(dir)) {
53 const id = idFromFile(ent.name)
54 if (ent.kind === 'file' && id) files.push({ path: `${dir}/${ent.name}`, id, mtime: ent.mtimeMs })
55 }
56 }
57 const recent = files.sort((a, b) => b.mtime - a.mtime).slice(0, limit)
58 if (recent.length === 0) return []
59 let names: Record<string, string> = {}
60 try {
61 names = parseIndex(await $.fs.read(`${home}/.codex/session_index.jsonl`))
62 } catch {
63 names = {}
64 }
65 const r = await $.process.run(dumpArgv(windows, recent.map(f => f.path)), { timeoutMs: 60000 })
66 const threads = parseDump(String(r.stdout ?? ''), names, Object.fromEntries(recent.map(f => [f.id, f.mtime])))
67 await $.store.set('codexThreads', threads)
68 return threads
69}
70
71// One Codex turn: a new agent, or the next message to an existing thread (codex exec resume).
72async function runCodexJob($: any, jobId: string, prompt: string, tellLead: boolean): Promise<CodexJob | undefined> {
73 const job = (await read($, codexJobs)).find(j => j.id === jobId)
74 if (!job) return undefined
75 const sandbox = job.canEdit ? 'workspace-write' : 'read-only'
76 const argv = job.threadId
77 ? ['codex', 'exec', 'resume', '-m', job.model, '-c', `sandbox_mode="${sandbox}"`, '--skip-git-repo-check', '--json', job.threadId, prompt]
78 : ['codex', 'exec', '-m', job.model, '-s', sandbox, '--skip-git-repo-check', '--json', '-C', await $.session.cwd(), prompt]
79 const set = (patch: Partial<CodexJob>) => update($, codexJobs, (list: CodexJob[]) => list.map(j => (j.id === jobId ? { ...j, ...patch } : j)))
80 await set({ status: 'running', endedAt: undefined, lastAction: 'starting Codex', lastPrompt: prompt.slice(0, 4000), answer: undefined })
81 let answer = ''
82 let failed = ''
83 let tokens = 0
84 try {
85 const child = $.process.spawn({ argv, input: '' })
86 let buffer = ''
87 for await (const piece of child) {
88 if (piece.stream !== 'stdout' || typeof piece.text !== 'string') continue
89 buffer += piece.text
90 const lines = buffer.split('\n')
91 buffer = lines.pop() ?? ''
92 for (const line of lines) {
93 let ev: any
94 try {
95 ev = JSON.parse(line)
96 } catch {
97 continue
98 }
99 const item = ev.item ?? {}
100 if (ev.type === 'thread.started' && ev.thread_id) await set({ threadId: ev.thread_id, lastAction: 'thinking' })
101 else if (ev.type === 'item.started' && item.type === 'command_execution') await set({ lastAction: `running: ${short(String(item.command ?? ''), 60)}` })
102 else if (ev.type === 'item.completed' && item.type === 'file_change') await set({ lastAction: 'edited files' })
103 else if (ev.type === 'item.completed' && item.type === 'web_search') await set({ lastAction: 'reading the web' })
104 else if (ev.type === 'item.completed' && item.type === 'agent_message') {
105 answer = String(item.text ?? '')
106 await set({ lastAction: 'writing its answer' })
107 } else if (ev.type === 'turn.completed') tokens = Number(ev.usage?.input_tokens ?? 0) + Number(ev.usage?.output_tokens ?? 0)
108 else if (ev.type === 'turn.failed' || ev.type === 'error') failed = String(ev.error?.message ?? ev.message ?? 'Codex reported an error')
109 }
110 }
111 } catch (err) {
112 failed = String((err as Error)?.message ?? err).slice(0, 200)
113 }
114 if (!answer && !failed) failed = 'Codex ended without an answer'
115 const cur = (await read($, codexJobs)).find(j => j.id === jobId)
116 await set({ status: failed ? 'failed' : 'done', endedAt: Date.now(), answer: short(failed || answer, 6000), tokens: (cur?.tokens ?? 0) + tokens, turns: (cur?.turns ?? 0) + 1, lastAction: failed ? 'failed' : 'done' })
117 $.ui.toast(failed ? `Buddy: Codex "${short(job.task, 40)}" failed` : `Buddy: Codex finished "${short(job.task, 40)}"`)
118 // If you're reading this thread in the panel, jump to the new reply.
119 try {
120 const open = await read($, cxConv)
121 const tid = (await read($, codexJobs)).find(j => j.id === jobId)?.threadId
122 if (open.id && (open.id === jobId || open.id === tid)) {
123 await $.clock.sleep(250)
124 await $.ui.scroll({ in: 'buddy', to: 'end' })
125 }
126 } catch {
127 // scrolling is a nicety
128 }
129 if (tellLead) {
130 const tid = (await read($, codexJobs)).find(j => j.id === jobId)?.threadId ?? ''
131 const text = failed
132 ? `[Buddy] Codex agent ${jobId} (thread ${tid}) failed: ${short(failed, 400)}`
133 : `[Buddy] Codex agent ${jobId} (thread ${tid}) finished "${short(job.task, 80)}". Its answer:\n\n${short(answer, 6000)}`
134 try {
135 await $.prompt.submit({ text })
136 } catch {
137 // the answer stays in the Codex tab
138 }
139 }
140 return (await read($, codexJobs)).find(j => j.id === jobId)
141}
142
143async function newJob($: any, task: string, model: string, canEdit: boolean, by: string, threadId?: string): Promise<string> {
144 const id = `c${Date.now().toString(36).slice(-5)}`
145 await update($, codexJobs, (list: CodexJob[]) =>
146 [...list, { id, threadId, task: short(task, 300), model, canEdit, by, status: 'running' as const, startedAt: Date.now(), turns: 0 }].slice(-15),
147 )
148 return id
149}
150
151// Asking before Codex may edit files. Anything other than a clear yes keeps it read-only.
152async function approveEdits($: any, what: string): Promise<boolean> {
153 try {
154 const answer = await $.ui.ask(`Let Codex edit files in this project for "${short(what, 80)}"? It can change and create files here. No keeps it read-only.`, ['Yes, let it edit', 'No, read-only'])
155 return answer === 'Yes, let it edit'
156 } catch {
157 return false
158 }
159}
160
161export function registerCodexTeam(on: any, options: Options) {
162 const off = 'Codex is switched off in Buddy (Settings > Codex). Ask the user to turn it on.'
163
164 on('tool.call', { tool: 'mcp__buddy__codex_start' }, async ($: any, e: any) => {
165 if (!(await codexOn($, options))) return { result: off }
166 const task = String(e.task ?? '').trim()
167 if (!task) return { result: 'Give the task.' }
168 const model = String(e.model ?? '').trim() || (await defaultModel($, options))
169 const canEdit = e.canEdit === true ? await approveEdits($, task) : false
170 const id = await newJob($, task, model, canEdit, 'Claude')
171 await $.ui.open({ id: 'buddy', title: 'Buddy' })
172 if (e.wait === true) {
173 const job = await runCodexJob($, id, task, false)
174 return { result: `Codex agent ${id} (thread ${job?.threadId ?? '?'}) ${job?.status}:\n\n${job?.answer ?? ''}` }
175 }
176 void runCodexJob($, id, task, true)
177 return { result: `Started Codex agent ${id} on ${model}${canEdit ? ' (may edit files)' : ' (read-only)'}. Its answer arrives later as a message from Buddy. Message it with mcp__buddy__codex_message.` }
178 })
179
180 on('tool.call', { tool: 'mcp__buddy__codex_message' }, async ($: any, e: any) => {
181 if (!(await codexOn($, options))) return { result: off }
182 const target = String(e.threadId ?? '').trim()
183 const text = String(e.text ?? '').trim()
184 if (!target || !text) return { result: 'Give threadId (a Codex thread id or a Buddy agent id) and text.' }
185 const jobs = await read($, codexJobs)
186 const known = jobs.find(j => j.id === target || j.threadId === target)
187 if (known?.status === 'running') return { result: `Codex agent ${known.id} is still working. Wait for its answer first.` }
188 const id = known?.id ?? (await newJob($, text, await defaultModel($, options), false, 'Claude', target))
189 if (e.wait === true) {
190 const job = await runCodexJob($, id, text, false)
191 return { result: `Codex ${job?.status}:\n\n${job?.answer ?? ''}` }
192 }
193 void runCodexJob($, id, text, true)
194 return { result: `Sent to Codex (${known ? `agent ${id}` : `thread ${target}`}). Its reply arrives as a message from Buddy.` }
195 })
196
197 on('tool.call', { tool: 'mcp__buddy__codex_threads' }, async ($: any) => {
198 let scan: CodexThread[] = []
199 try {
200 scan = await scanCodexThreads($)
201 } catch {
202 scan = ((await $.store.get('codexThreads')) ?? []) as CodexThread[]
203 }
204 const jobs = await read($, codexJobs)
205 return {
206 result: JSON.stringify({
207 startedFromHere: jobs.map(j => ({ id: j.id, threadId: j.threadId, task: j.task, status: j.status, lastAction: j.lastAction, answer: j.answer ? short(j.answer, 400) : undefined })),
208 recentCodexThreads: scan,
209 }),
210 }
211 })
212
213 // The panel's buttons: /buddy-codex start <model> <edit|read> <task> · msg <threadId> <text>
214 on('command.run', { command: 'buddy-codex' }, async ($: any, e: any) => {
215 if (!(await codexOn($, options))) return { text: 'Turn Codex on in Buddy > Settings first.' }
216 const args = String(e.args ?? '').trim()
217 if (args === 'scan') {
218 const threads = await scanCodexThreads($)
219 return { text: `Buddy found ${threads.length} recent Codex threads.` }
220 }
221 const start = args.match(/^start\s+(\S+)\s+(edit|read)\s+([\s\S]+)$/)
222 if (start) {
223 const canEdit = start[2] === 'edit' ? await approveEdits($, start[3]) : false
224 const id = await newJob($, start[3], start[1], canEdit, 'you')
225 void runCodexJob($, id, start[3], false)
226 return { text: `Started Codex agent ${id} on ${start[1]}${canEdit ? ' (may edit files)' : ' (read-only)'}.` }
227 }
228 const msg = args.match(/^msg\s+(\S+)\s+([\s\S]+)$/)
229 if (msg) {
230 const jobs = await read($, codexJobs)
231 const known = jobs.find(j => j.id === msg[1] || j.threadId === msg[1])
232 if (known?.status === 'running') return { text: 'That Codex agent is still working.' }
233 const id = known?.id ?? (await newJob($, msg[2], await defaultModel($, options), false, 'you', msg[1]))
234 void runCodexJob($, id, msg[2], false)
235 return { text: `Sent to Codex.` }
236 }
237 return { text: 'Usage: /buddy-codex start <model> <edit|read> <task> · /buddy-codex msg <threadId> <text>' }
238 })
239}
240hooks/lib/codexthreads.ts 285 lines1// Reading Codex's own session logs (~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl). Pure helpers, no `$`.
2// Logs can be gigabytes, so the caller dumps only a small slice of each file: the start (which
3// holds the project folder) and the end (which holds the status and the last reply).
4
5export type CodexThread = {
6 id: string
7 name: string
8 project: string
9 folder: string
10 from: string
11 updatedAt: number
12 status: 'working' | 'idle'
13 lastReply: string
14 file: string
15}
16
17const HEAD_BYTES = 8192
18const TAIL_BYTES = 16384
19
20const short = (text: string, max: number) => (text.length > max ? text.slice(0, max - 1) + '…' : text)
21
22// The day folders to look in: today back `days` days.
23export function dayDirs(home: string, days: number, now = Date.now()): string[] {
24 const out: string[] = []
25 for (let i = 0; i < days; i++) {
26 const d = new Date(now - i * 86400000)
27 out.push(`${home}/.codex/sessions/${d.getFullYear()}/${String(d.getMonth() + 1).padStart(2, '0')}/${String(d.getDate()).padStart(2, '0')}`)
28 }
29 return out
30}
31
32export const idFromFile = (name: string) => (name.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/) ?? [])[1] ?? ''
33
34// The commands that print, per file, a marker, its first bytes and its last bytes.
35export function dumpArgv(windows: boolean, files: string[]): string[] {
36 if (windows) {
37 const list = files.map(f => `'${f.replace(/'/g, "''")}'`).join(',')
38 return [
39 'powershell',
40 '-NoProfile',
41 '-NonInteractive',
42 '-Command',
43 // Byte reads, not Get-Content: a log can be gigabytes and -Tail crawls on those.
44 `[Console]::OutputEncoding=[Text.Encoding]::UTF8; foreach ($f in @(${list})) { '@@FILE ' + $f; $s=[IO.File]::Open($f,'Open','Read','ReadWrite'); try { $n=[Math]::Min($s.Length,${HEAD_BYTES}); $b=New-Object byte[] $n; [void]$s.Read($b,0,$n); [Text.Encoding]::UTF8.GetString($b); '@@TAIL'; $m=[Math]::Min($s.Length,${TAIL_BYTES}); [void]$s.Seek(-$m,'End'); $b=New-Object byte[] $m; [void]$s.Read($b,0,$m); [Text.Encoding]::UTF8.GetString($b) } finally { $s.Close() } }`,
45 ]
46 }
47 return ['sh', '-c', `for f; do echo "@@FILE $f"; head -c ${HEAD_BYTES} "$f"; echo; echo "@@TAIL"; tail -c ${TAIL_BYTES} "$f"; echo; done`, 'sh', ...files]
48}
49
50// A JSON string field from a slice that may be cut off: "key":"value", unescaped.
51function field(text: string, key: string): string {
52 const m = text.match(new RegExp(`"${key}":"((?:[^"\\\\]|\\\\.)*)"`))
53 if (!m) return ''
54 try {
55 return JSON.parse(`"${m[1]}"`)
56 } catch {
57 return m[1]
58 }
59}
60
61// Turns the dump into threads. `names` maps thread id to the name the Codex app gave it.
62export function parseDump(stdout: string, names: Record<string, string>, mtimes: Record<string, number>): CodexThread[] {
63 const out: CodexThread[] = []
64 for (const block of stdout.split('@@FILE ').slice(1)) {
65 const nl = block.indexOf('\n')
66 const file = block.slice(0, nl).trim()
67 const rest = block.slice(nl + 1)
68 const [head, tail = ''] = rest.split('@@TAIL')
69 const id = idFromFile(file.replace(/\\/g, '/'))
70 if (!id) continue
71 const project = field(head, 'cwd').replace(/\\/g, '/')
72 const folder = project.split('/').filter(Boolean).pop() ?? ''
73 const originator = field(head, 'originator')
74 const source = field(head, 'source')
75 const from = originator.includes('Desktop') ? 'Codex app' : source === 'exec' ? 'Codex CLI' : 'Codex'
76 let lastReply = ''
77 let open = false
78 for (const line of tail.split('\n')) {
79 let d: any
80 try {
81 d = JSON.parse(line)
82 } catch {
83 continue
84 }
85 const p = d.payload ?? {}
86 if (d.type === 'event_msg' && p.type === 'task_started') open = true
87 if (d.type === 'event_msg' && p.type === 'task_complete') {
88 open = false
89 if (p.last_agent_message) lastReply = String(p.last_agent_message)
90 }
91 if (d.type === 'event_msg' && p.type === 'agent_message' && p.message) lastReply = String(p.message)
92 }
93 // Codex's own background safety checks, not threads the user started.
94 if (names[id] === 'Guardian review' || lastReply.startsWith('{"risk_level"')) continue
95 const updatedAt = mtimes[id] ?? 0
96 out.push({
97 id,
98 name: names[id] || (folder ? `${folder} thread` : 'Codex thread'),
99 project,
100 folder,
101 from,
102 updatedAt,
103 status: open && Date.now() - updatedAt < 15 * 60000 ? 'working' : 'idle',
104 lastReply: short(lastReply.replace(/\s+/g, ' ').trim(), 600),
105 file: file.replace(/\\/g, '/'),
106 })
107 }
108 return out.sort((a, b) => b.updatedAt - a.updatedAt)
109}
110
111export function parseIndex(text: string): Record<string, string> {
112 const names: Record<string, string> = {}
113 for (const line of text.split('\n')) {
114 try {
115 const r = JSON.parse(line)
116 if (r.id && r.thread_name) names[r.id] = String(r.thread_name)
117 } catch {
118 // skip
119 }
120 }
121 return names
122}
123
124// Threads grouped by project, projects ordered by their newest thread.
125export function byProject(threads: CodexThread[]): { project: string; folder: string; threads: CodexThread[] }[] {
126 const groups = new Map<string, { project: string; folder: string; threads: CodexThread[] }>()
127 for (const t of threads) {
128 const key = t.project || '(no project)'
129 if (!groups.has(key)) groups.set(key, { project: key, folder: t.folder || 'No project', threads: [] })
130 groups.get(key)!.threads.push(t)
131 }
132 return [...groups.values()].sort((a, b) => (b.threads[0]?.updatedAt ?? 0) - (a.threads[0]?.updatedAt ?? 0))
133}
134
135// Ids the Codex app named "Guardian review": its own safety checks, skipped before scanning.
136export function guardianIds(index: Record<string, string>): Set<string> {
137 return new Set(Object.entries(index).filter(([, n]) => n === 'Guardian review').map(([id]) => id))
138}
139
140// Pass 1: just each file's project folder, for every log in the given day folders. The folders are
141// passed (not the files) so the command line stays short however many logs there are.
142export function projectsArgv(windows: boolean, dirs: string[]): string[] {
143 if (windows) {
144 const list = dirs.map(d => `'${d.replace(/'/g, "''")}'`).join(',')
145 return [
146 'powershell',
147 '-NoProfile',
148 '-NonInteractive',
149 '-Command',
150 `[Console]::OutputEncoding=[Text.Encoding]::UTF8; foreach ($d in @(${list})) { if (Test-Path -LiteralPath $d) { foreach ($e in Get-ChildItem -LiteralPath $d -Filter 'rollout-*.jsonl') { $s=[IO.File]::Open($e.FullName,'Open','Read','ReadWrite'); try { $n=[Math]::Min($s.Length,${HEAD_BYTES}); $b=New-Object byte[] $n; [void]$s.Read($b,0,$n); $h=[Text.Encoding]::UTF8.GetString($b); $m=[regex]::Match($h,'"cwd":"([^"]*)"'); '@@P ' + $e.Name + [char]9 + $m.Groups[1].Value } finally { $s.Close() } } } }`,
151 ]
152 }
153 return [
154 'sh',
155 '-c',
156 `for d; do for f in "$d"/rollout-*.jsonl; do [ -f "$f" ] || continue; c=$(head -c ${HEAD_BYTES} "$f" | grep -o '"cwd":"[^"]*"' | head -n 1 | cut -d'"' -f4); printf '@@P %s\\t%s\\n' "$(basename "$f")" "$c"; done; done`,
157 'sh',
158 ...dirs,
159 ]
160}
161
162// Pass 1 output to thread id -> project path (forward slashes).
163export function parseProjects(stdout: string): Record<string, string> {
164 const out: Record<string, string> = {}
165 for (const line of stdout.split('\n')) {
166 if (!line.startsWith('@@P ')) continue
167 const [file, cwd = ''] = line.slice(4).split('\t')
168 const id = idFromFile(file.trim().replace(/\\/g, '/'))
169 if (id) out[id] = cwd.trim().replace(/\\\\/g, '/').replace(/\\/g, '/')
170 }
171 return out
172}
173
174// Pass 2 picks: the newest `perProject` threads of every project (all of `focus`), newest first, capped.
175export function pickPerProject<T extends { id: string; mtime: number }>(files: T[], projectOf: Record<string, string>, perProject: number, focus = '', cap = 140): T[] {
176 const seen: Record<string, number> = {}
177 const picked: T[] = []
178 for (const f of [...files].sort((a, b) => b.mtime - a.mtime)) {
179 const p = projectOf[f.id] ?? ''
180 const limit = p === focus && focus ? 60 : perProject
181 seen[p] = (seen[p] ?? 0) + 1
182 if (seen[p] <= limit) picked.push(f)
183 if (picked.length >= cap) break
184 }
185 return picked
186}
187
188// How many threads each project has in total (for "Show all (N)").
189export function projectCounts(projectOf: Record<string, string>): Record<string, number> {
190 const out: Record<string, number> = {}
191 for (const p of Object.values(projectOf)) out[p || '(no project)'] = (out[p || '(no project)'] ?? 0) + 1
192 return out
193}
194
195// Pass 1 for a few files only (the new ones since last time), so the command line stays short.
196export function projectsArgvFiles(windows: boolean, files: string[]): string[] {
197 if (windows) {
198 const list = files.map(f => `'${f.replace(/'/g, "''")}'`).join(',')
199 return [
200 'powershell',
201 '-NoProfile',
202 '-NonInteractive',
203 '-Command',
204 `[Console]::OutputEncoding=[Text.Encoding]::UTF8; foreach ($f in @(${list})) { $s=[IO.File]::Open($f,'Open','Read','ReadWrite'); try { $n=[Math]::Min($s.Length,${HEAD_BYTES}); $b=New-Object byte[] $n; [void]$s.Read($b,0,$n); $h=[Text.Encoding]::UTF8.GetString($b); $m=[regex]::Match($h,'"cwd":"([^"]*)"'); '@@P ' + [IO.Path]::GetFileName($f) + [char]9 + $m.Groups[1].Value } finally { $s.Close() } }`,
205 ]
206 }
207 return [
208 'sh',
209 '-c',
210 `for f; do c=$(head -c ${HEAD_BYTES} "$f" | grep -o '"cwd":"[^"]*"' | head -n 1 | cut -d'"' -f4); printf '@@P %s\\t%s\\n' "$(basename "$f")" "$c"; done`,
211 'sh',
212 ...files,
213 ]
214}
215
216// ---------- One thread's full conversation ----------
217
218export type ConvEntry = { role: 'you' | 'codex' | 'step'; text: string }
219
220const CONV_TAIL = 48 * 1024 * 1024 // read at most the last 48 MB of a log
221const CONV_OUT = 3_500_000 // and print at most 3.5 MB of matching lines
222const LINE_CAP = 40_000
223
224// Prints only the log lines that are conversation items (messages, commands, tool calls, searches).
225export function convArgv(windows: boolean, file: string, tailBytes = CONV_TAIL): string[] {
226 if (windows) {
227 const f = `'${file.replace(/'/g, "''")}'`
228 return [
229 'powershell',
230 '-NoProfile',
231 '-NonInteractive',
232 '-Command',
233 `[Console]::OutputEncoding=[Text.Encoding]::UTF8; $s=[IO.File]::Open(${f},'Open','Read','ReadWrite'); try { $m=[Math]::Min($s.Length,${tailBytes}); [void]$s.Seek(-$m,'End'); $b=New-Object byte[] $m; $r=0; while ($r -lt $m) { $k=$s.Read($b,$r,$m-$r); if ($k -le 0) { break }; $r+=$k }; $txt=[Text.Encoding]::UTF8.GetString($b,0,$r) } finally { $s.Close() }; $out=New-Object Text.StringBuilder; foreach ($l in $txt.Split([char]10)) { if ($l.Contains('"item_completed"') -and ($l.Contains('"UserMessage"') -or $l.Contains('"AgentMessage"') -or $l.Contains('"CommandExecution"') -or $l.Contains('"McpToolCall"') -or $l.Contains('"Extension"'))) { if ($l.Length -gt ${LINE_CAP}) { $l=$l.Substring(0,${LINE_CAP}) }; [void]$out.AppendLine($l) } }; $o=$out.ToString(); if ($o.Length -gt ${CONV_OUT}) { $o=$o.Substring($o.Length-${CONV_OUT}) }; $o`,
234 ]
235 }
236 return [
237 'sh',
238 '-c',
239 `tail -c ${tailBytes} "$1" | grep '"item_completed"' | grep -E '"(UserMessage|AgentMessage|CommandExecution|McpToolCall|Extension)"' | cut -c1-${LINE_CAP} | tail -c ${CONV_OUT}`,
240 'sh',
241 file,
242 ]
243}
244
245const textOf = (content: unknown): string =>
246 Array.isArray(content) ? content.map((c: any) => String(c?.text ?? '')).filter(Boolean).join('\n') : ''
247
248// Turns those lines into a back-and-forth. Context Codex injects (instructions, environment) is skipped.
249export function parseConversation(stdout: string): { entries: ConvEntry[]; cutOff: boolean } {
250 const entries: ConvEntry[] = []
251 let cutOff = false
252 for (const line of stdout.split('\n')) {
253 if (!line.trim()) continue
254 let item: any
255 try {
256 item = JSON.parse(line).payload?.item
257 } catch {
258 // a line cut at the cap: keep what the fields say
259 const type = (line.match(/"item":\{"type":"(\w+)"/) ?? [])[1]
260 const text = field(line, 'text')
261 if (type === 'UserMessage' || type === 'AgentMessage') {
262 entries.push({ role: type === 'UserMessage' ? 'you' : 'codex', text: text + ' …' })
263 cutOff = true
264 }
265 continue
266 }
267 if (!item) continue
268 if (item.type === 'UserMessage') {
269 const text = textOf(item.content).trim()
270 if (text && !text.startsWith('<') && !text.startsWith('# AGENTS.md')) entries.push({ role: 'you', text })
271 } else if (item.type === 'AgentMessage') {
272 const text = textOf(item.content).trim()
273 if (text) entries.push({ role: 'codex', text })
274 } else if (item.type === 'CommandExecution') {
275 const cmd = Array.isArray(item.command) ? item.command[item.command.length - 1] : String(item.command ?? '')
276 entries.push({ role: 'step', text: `ran: ${short(String(cmd).replace(/\s+/g, ' '), 140)}` })
277 } else if (item.type === 'McpToolCall') {
278 entries.push({ role: 'step', text: `${short(String(item.arguments?.title ?? item.title ?? `used ${item.server ?? 'a tool'}`), 140)}` })
279 } else if (item.type === 'Extension') {
280 entries.push({ role: 'step', text: `${item.kind ?? 'searched'}: ${short(String(item.query ?? ''), 120)}` })
281 }
282 }
283 return { entries, cutOff }
284}
285hooks/lib/mask.ts 78 lines1// Recording mode: hide secrets, emails, phone numbers, money and named clients on screen.
2// Display only: Claude still reads the real text. Pure functions, no `$`.
3
4const BAR = (n: number) => '█'.repeat(Math.max(4, Math.min(n, 12)))
5
6// Known key shapes first, then "NAME=value" for anything called a key, token, secret or password.
7const SECRETS: RegExp[] = [
8 /\bsk-(?:ant-|proj-|live-|test-)?[A-Za-z0-9_-]{16,}/g,
9 /\bAIza[0-9A-Za-z_-]{30,}/g,
10 /\bgh[pousr]_[A-Za-z0-9]{30,}/g,
11 /\bgithub_pat_[A-Za-z0-9_]{30,}/g,
12 /\bxox[abprs]-[A-Za-z0-9-]{10,}/g,
13 /\bAKIA[0-9A-Z]{16}\b/g,
14 /\b(?:rk|pk)_(?:live|test)_[A-Za-z0-9]{16,}/g,
15 /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,
16 /\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/g,
17]
18const NAMED_SECRET = /\b([A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD)[A-Za-z0-9_]*["']?\s*[=:]\s*)(["']?)([^\s"',;]{6,})/gi
19const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g
20const PHONE = /(?:\+\d{1,3}[\s.-]?)?\(?\b\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}\b/g
21const MONEY = /(?:[$€£]\s?\d[\d,]*(?:\.\d+)?(?:\s?(?:k|K|m|M|bn|million|billion|thousand))?)|(?:\b\d[\d,]*(?:\.\d+)?\s?(?:USD|CAD|EUR|GBP|dollars)\b)/g
22
23const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
24
25export function maskText(text: string, names: string[] = []): string {
26 if (!text) return text
27 let out = text
28 for (const re of SECRETS) out = out.replace(re, m => BAR(m.length))
29 out = out.replace(NAMED_SECRET, (_m, name: string, quote: string, value: string) => `${name}${quote}${BAR(value.length)}`)
30 out = out.replace(EMAIL, '███@███')
31 out = out.replace(PHONE, '███-███-████')
32 out = out.replace(MONEY, m => (/^[$€£]/.test(m) ? `${m[0]}███` : '███'))
33 for (const name of names) {
34 if (name.length < 2) continue
35 out = out.replace(new RegExp(`\\b${escapeRe(name)}\\b`, 'gi'), m => BAR(m.length))
36 }
37 return out
38}
39
40// Masks every string inside a value and keeps its shape, so tool rows still draw.
41export function maskDeep<T>(value: T, names: string[] = [], depth = 0): T {
42 if (depth > 8) return value
43 if (typeof value === 'string') return maskText(value, names) as unknown as T
44 if (Array.isArray(value)) return value.map(v => maskDeep(v, names, depth + 1)) as unknown as T
45 if (value && typeof value === 'object') {
46 const out: Record<string, unknown> = {}
47 for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = maskDeep(v, names, depth + 1)
48 return out as T
49 }
50 return value
51}
52
53export const nameList = (raw: unknown) =>
54 String(raw ?? '')
55 .split(',')
56 .map(s => s.trim())
57 .filter(Boolean)
58
59// What a cold cache costs: the whole chat re-written to cache at 1.25x (5 min) or 2x (1 hour) the input price.
60// Per-million input prices, US dollars, from Anthropic's published pricing (2026-10).
61export function inputPrice(model: string): number {
62 const m = model.toLowerCase()
63 if (/fable|mythos/.test(m)) return 10
64 if (/opus-5-5|opus-5\.5/.test(m)) return 4
65 if (/opus/.test(m)) return 5
66 if (/sonnet/.test(m)) return 2
67 if (/haiku/.test(m)) return 1
68 return 4
69}
70
71export function coldCost(tokens: number, model: string, cacheMinutes: number) {
72 const price = inputPrice(model)
73 const writeRate = cacheMinutes >= 60 ? 2 : 1.25
74 const cold = (tokens / 1e6) * price * writeRate
75 const warm = (tokens / 1e6) * price * (/fable|mythos/i.test(model) ? 0.025 : /opus-5-5|opus-5\.5/i.test(model) ? 0.05 : 0.1)
76 return { cold, warm }
77}
78hooks/jobs/watch.tsx 174 lines1import { atom, read, update } from 'claude-code'
2
3import { coldCost } from '../lib/mask.ts'
4import type { AgentRow, Caught, Mood, Receipt } from '../../types'
5
6// Buddy's shared state (same keys in every file, so every job sees the same values).
7const agents = atom({ plugin: 'buddy', key: 'agents' } as const, [] as AgentRow[])
8const caught = atom({ plugin: 'buddy', key: 'caught' } as const, { send: 0, spend: 0, danger: 0 } as Caught)
9const memory = atom({ plugin: 'buddy', key: 'memory' } as const, 0)
10const mood = atom({ plugin: 'buddy', key: 'mood' } as const, 'sleepy' as Mood)
11const editing = atom({ plugin: 'buddy', key: 'editing' } as const, [] as string[])
12const receipt = atom({ plugin: 'buddy', key: 'receipt' } as const, null as Receipt | null)
13const lastTurnAt = atom({ plugin: 'buddy', key: 'lastTurnAt' } as const, 0)
14
15
16// The all-chats board: each chat's Buddy keeps one small status file in ~/.claude/buddy/chats,
17// and every Buddy reads them all. One file per chat, so chats never overwrite each other.
18type ChatStatus = 'working' | 'waiting' | 'done' | 'idle' | 'closed'
19type ChatRow = { id: string; title: string; folder: string; status: ChatStatus; since: number; updatedAt: number }
20
21async function chatDir($: any): Promise<string> {
22 const home = ((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.') as string
23 return `${home.replace(/\\/g, '/')}/.claude/buddy/chats`
24}
25
26async function writeChat($: any, patch: Partial<ChatRow>) {
27 const id = await $.session.id()
28 const file = `${await chatDir($)}/${id}.json`
29 let cur: Partial<ChatRow> = {}
30 try {
31 cur = JSON.parse(await $.fs.read(file))
32 } catch {
33 cur = {}
34 }
35 const now = Date.now()
36 const next = { ...cur, ...patch, id, updatedAt: now } as ChatRow
37 if (patch.status && patch.status !== cur.status) next.since = now
38 if (!next.since) next.since = now
39 await $.fs.write(file, JSON.stringify(next))
40}
41
42type Options = { agentWatcher?: boolean; donePingSeconds?: number; bannedPhrases?: string; cacheMinutes?: number; cacheAskAbove?: number; cacheCheck?: boolean }
43
44const short = (text: string, max: number) => (text.length > max ? text.slice(0, max - 1) + '…' : text)
45
46// Reads how full the chat is and keeps Buddy's face in step with it.
47export async function readMemory($: any) {
48 const usage = await $.session.usage()
49 const context = usage?.context
50 if (!context || !context.window) return
51 const tokens = context.tokens ?? 0
52 const percent = Math.round(context.percent ?? (tokens / context.window) * 100)
53 await update($, memory, () => percent)
54}
55
56export function registerWatch(on: any, options: Options) {
57 on('prompt.submit', async ($: any, e: any, next: any) => {
58 // Cache price check: after a break, the next message re-reads the whole chat at full price.
59 // Buddy says what that costs and offers to compact first. Never blocks if anything fails.
60 try {
61 const live = ((await $.store.get('jobs')) ?? {}) as Record<string, boolean>
62 const s = { ...options, ...(((await $.store.get('settings')) ?? {}) as Options) }
63 const last = await read($, lastTurnAt)
64 const ttl = Math.max(1, Number(s.cacheMinutes ?? 60)) * 60000
65 const text = String(e.text ?? '').trim()
66 if ((live.cacheCheck ?? options.cacheCheck) === true && e.origin?.kind === 'composer' && last > 0 && Date.now() - last > ttl && !text.startsWith('/')) {
67 const usage = await $.session.usage()
68 const tokens = Number(usage?.context?.tokens ?? 0)
69 const model = String(await $.session.model())
70 const { cold, warm } = coldCost(tokens, model, Number(s.cacheMinutes ?? 60))
71 const askAbove = Number(s.cacheAskAbove ?? 0.5)
72 if (tokens > 0 && cold >= askAbove) {
73 const away = Math.round((Date.now() - last) / 60000)
74 await update($, mood, () => 'holding')
75 const choice = String(
76 await $.ui.ask(
77 `Buddy: your cache went cold ${away} min ago. This message re-reads your whole chat (${Math.round(tokens / 1000)}K tokens): about $${cold.toFixed(2)} at API rates, vs $${warm.toFixed(2)} warm. On a subscription it comes out of your limit instead. Compact first to shrink it? (Stop asking turns this check off; switch it back on in the Health card or Jobs.)`,
78 ['Send anyway', 'Compact first, then send', 'Cancel', 'Stop asking'],
79 ),
80 )
81 await update($, mood, () => 'working')
82 const log = ((await $.store.get('log')) ?? []) as unknown[]
83 await $.store.set('log', [{ at: Date.now(), kind: 'cache', what: `cold cache, ~$${cold.toFixed(2)}`, choice: choice.startsWith('Compact') ? 'Compacted first' : choice === 'Cancel' ? 'Cancelled' : choice === 'Stop asking' ? 'Turned the check off' : 'Sent anyway' }, ...log].slice(0, 20))
84 if (choice === 'Stop asking') {
85 await $.store.set('jobs', { ...live, cacheCheck: false })
86 $.ui.toast('Buddy: cache price check OFF. Your message is going out. Switch it back on in the Health card.')
87 }
88 if (choice === 'Cancel') {
89 await $.prompt.fill({ text })
90 return { drop: 'Buddy kept your message in the box. Nothing was sent.' }
91 }
92 if (choice.startsWith('Compact')) {
93 $.ui.toast('Buddy: compacting first...')
94 await $.session.compact({})
95 }
96 }
97 }
98 } catch {
99 // the price check is advice; a failure never blocks your message
100 }
101 await update($, mood, () => 'working')
102 try {
103 const text = String(e.text ?? '').replace(/\s+/g, ' ').trim()
104 const file = `${await chatDir($)}/${await $.session.id()}.json`
105 let title = ''
106 try {
107 title = JSON.parse(await $.fs.read(file)).title ?? ''
108 } catch {
109 title = ''
110 }
111 await writeChat($, { status: 'working', ...(title || !text || text.startsWith('/') ? {} : { title: short(text, 48) }) })
112 } catch {
113 // the board is a nice-to-have; never block a prompt over it
114 }
115 return next(e)
116 })
117
118 on('turn.complete', async ($: any, e: any, next: any) => {
119 const done = await next(e)
120 if (e.agentId !== undefined) {
121 const now = await $.clock.now()
122 await update($, agents, (list: AgentRow[]) =>
123 list.map(row => (row.id === e.agentId && row.endedAt === undefined ? { ...row, endedAt: now } : row)),
124 )
125 return done
126 }
127 await readMemory($)
128 await update($, mood, () => 'happy')
129 try {
130 await writeChat($, { status: 'done' })
131 } catch {
132 // board only
133 }
134 await update($, lastTurnAt, () => Date.now())
135 const live = ((await $.store.get('jobs')) ?? {}) as Record<string, boolean>
136 // Work receipt: the files this task changed.
137 const files = await read($, editing)
138 const seconds = Math.round(Number(e.durationMs ?? 0) / 1000)
139 if (files.length > 0) {
140 const at = await $.clock.now()
141 await update($, receipt, () => ({ files, seconds, at }))
142 await update($, editing, () => [])
143 }
144 // Done ping for long tasks, so you can walk away.
145 const s = { ...options, ...(((await $.store.get('settings')) ?? {}) as Options) }
146 const pingAfter = Number(s.donePingSeconds ?? 60)
147 if (live.donePing !== false && !e.isAborted && pingAfter > 0 && seconds >= pingAfter) {
148 const took = seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`
149 $.ui.toast(`( ^.^ )/ Buddy: done in ${took}${files.length ? `, ${files.length} file${files.length === 1 ? '' : 's'} changed` : ''}`)
150 }
151 // House rules check: flag banned words in the reply.
152 const banned = (s.bannedPhrases ?? '').split(',').map(s => s.trim()).filter(Boolean)
153 const answer = String(e.answer ?? '')
154 const hits = banned.filter(b => answer.toLowerCase().includes(b.toLowerCase()))
155 if (live.houseRules !== false && hits.length > 0) $.ui.toast(`Buddy: that reply used ${hits.map(h => `"${h}"`).join(', ')}, which your house rules ban`)
156 // Keep the lifetime caught counter between sessions.
157 await $.store.set('caught', await read($, caught))
158 return done
159 })
160
161 if (options.agentWatcher !== false) {
162 on('agent.spawn', async ($: any, e: any, next: any) => {
163 const started = await next(e)
164 const live = ((await $.store.get('jobs')) ?? {}) as Record<string, boolean>
165 if (live.agentWatcher !== false && started?.agentId !== undefined) {
166 const now = await $.clock.now()
167 const row: AgentRow = { id: started.agentId, task: short(String(e.description ?? e.prompt ?? 'agent'), 44), startedAt: now }
168 await update($, agents, (list: AgentRow[]) => [...list, row].slice(-10))
169 }
170 return started
171 })
172 }
173}
174hooks/pet.tsx 157 lines1// Buddy's animated pet: a Client surface module with its own frame clock.
2// Props come from the hooks module (species, mood, stage, name); clicks post back.
3
4type Species = 'bunny' | 'cat' | 'dog' | 'bear' | 'frog' | 'owl' | 'ghost' | 'dragon'
5type Mood = 'sleepy' | 'working' | 'happy' | 'holding' | 'tired'
6type Props = { species?: Species; mood?: Mood; stage?: 'egg' | 'pet'; name?: string; label?: string }
7type State = { frame: number; hearts: number; cracking: number }
8
9// Two poses per species; {e} = eye, {m} = mouth. Three lines each, kept narrow.
10const ART: Record<Species, [string[], string[]]> = {
11 bunny: [
12 [' (\\_/) ', ' ({e}{m}{e}) ', ' (")(") '],
13 [' (\\ /) ', ' ({e}{m}{e}) ', 'o(")(") '],
14 ],
15 cat: [
16 [' /\\_/\\ ', '( {e}{m}{e} )', ' > ^ < '],
17 [' /\\_/\\ ', '( {e}{m}{e} )', ' (") (")~'],
18 ],
19 dog: [
20 [' __ ', '({e}{m}{e})_', ' U U ~'],
21 [' __ ', '({e}{m}{e})_', ' U U ~'],
22 ],
23 bear: [
24 [' ʕ•ᴥ•ʔ '.replace('•ᴥ•', '{e}{m}{e}'), ' / \\ ', ' U U '],
25 [' ʕ•ᴥ•ʔ '.replace('•ᴥ•', '{e}{m}{e}'), ' \\ / ', ' U U '],
26 ],
27 frog: [
28 [' @..@ '.replace('..', '{e}{e}'), '({m}{m}{m}{m})', ' ^ ^ '],
29 [' @..@ '.replace('..', '{e}{e}'), '({m}{m}{m}{m})', '^ ^'],
30 ],
31 owl: [
32 [' {o,o} '.replace('o,o', '{e},{e}'), ' /)_) ', ' " " '],
33 [' {o,o} '.replace('o,o', '{e},{e}'), ' (_(\\ ', ' " " '],
34 ],
35 ghost: [
36 [' .-. ', ' ({e} {e}) ', ' | {m} | ', ' \'~~~\' '].slice(0, 3),
37 [' .-. ', ' ({e} {e}) ', ' |{m} | '],
38 ],
39 dragon: [
40 [' /\\_/\\_ ', ' ({e} {e} >', ' ^^ ~~ '],
41 [' /\\_/\\_ ', ' ({e} {e} >~', ' ^^ ~~'],
42 ],
43}
44
45const FACE: Record<Mood, { e: string; m: string }> = {
46 sleepy: { e: '-', m: '.' },
47 working: { e: 'o', m: '_' },
48 happy: { e: '^', m: 'w' },
49 holding: { e: 'O', m: 'o' },
50 tired: { e: 'x', m: '~' },
51}
52
53const EGG = [
54 [' .--. ', ' / \\ ', ' \\____/ '],
55 [' .--. ', ' / . \\ ', ' \\____/ '],
56 [' .--. ', ' / /\\ \\ ', ' \\_\\/_/ '],
57 [' * . * ', ' \\/ \\/ ', ' \\____/ '],
58]
59
60const NOTES = ['♪', '♫', '♪ ♫', '♫ ♪']
61const fill = (line: string, f: { e: string; m: string }) => line.split('{e}').join(f.e).split('{m}').join(f.m)
62const pad = (n: number) => ' '.repeat(Math.max(0, n))
63
64export default function Pet(props: Props, surface: any) {
65 const { Box, Text } = surface.elements
66 const s: State = surface.state ?? { frame: 0, hearts: 0, cracking: 0 }
67
68 if (surface.state === undefined) {
69 surface.setState({ frame: 0, hearts: 0, cracking: 0 })
70 surface.every(220, () => {
71 const cur: State = surface.state ?? { frame: 0, hearts: 0, cracking: 0 }
72 surface.setState({
73 frame: cur.frame + 1,
74 hearts: Math.max(0, cur.hearts - 1),
75 cracking: cur.cracking > 0 ? cur.cracking + 1 : 0,
76 })
77 if (cur.cracking >= 12) surface.post({ hatched: true })
78 })
79 surface.onPointer((ev: any) => {
80 if (ev.type !== 'down') return
81 const cur: State = surface.state ?? { frame: 0, hearts: 0, cracking: 0 }
82 if ((props.stage ?? 'pet') === 'egg') {
83 if (cur.cracking === 0) surface.setState({ ...cur, cracking: 1 })
84 } else {
85 surface.setState({ ...cur, hearts: 8 })
86 surface.post({ petted: true })
87 }
88 })
89 }
90
91 const width = Math.max(14, surface.columns || 24)
92 const f = s.frame
93
94 if ((props.stage ?? 'pet') === 'egg') {
95 const crack = s.cracking > 0 ? Math.min(3, Math.floor(s.cracking / 3)) : 0
96 const wobble = s.cracking > 0 ? (f % 2 ? 1 : 0) : f % 6 === 0 ? 1 : 0
97 const art = EGG[crack]
98 return (
99 <Box flexDirection="column">
100 <Text color="yellow">{pad(4)}{s.cracking > 0 ? ' crack!' : ''}</Text>
101 {art.map(line => (
102 <Text color="yellow">{pad(4 + wobble)}{line}</Text>
103 ))}
104 <Text dimColor>{s.cracking > 0 ? 'hatching...' : 'Click the egg to hatch your Buddy'}</Text>
105 </Box>
106 )
107 }
108
109 const species: Species = props.species ?? 'bunny'
110 const mood: Mood = props.mood ?? 'sleepy'
111 const poses = ART[species] ?? ART.bunny
112 const face = FACE[mood]
113 const pose = poses[f % 2]
114 const artWidth = Math.max(...pose.map(l => l.length))
115 const room = Math.max(0, width - artWidth - 4)
116
117 // Movement per mood.
118 let x = 2
119 let lift = 0
120 let top = ' '
121 let color = 'yellow'
122 if (mood === 'working') {
123 const span = Math.max(1, room)
124 const step = f % (span * 2)
125 x = 1 + (step < span ? step : span * 2 - step) // walk back and forth
126 } else if (mood === 'happy') {
127 lift = f % 2 // bounce
128 x = 2 + (f % 4 < 2 ? 0 : 2) // sway
129 top = pad(x + 1) + NOTES[f % NOTES.length]
130 color = 'green'
131 } else if (mood === 'holding') {
132 x = 2 + (f % 2) // shake
133 top = pad(x + 3) + '!'
134 color = 'red'
135 } else if (mood === 'tired') {
136 top = pad(x + artWidth) + (f % 3 === 0 ? 'z' : f % 3 === 1 ? 'zZ' : 'zZz')
137 color = 'gray'
138 } else {
139 top = pad(x + artWidth) + (f % 4 < 2 ? 'z' : ' z')
140 }
141 if (s.hearts > 0) top = pad(x + 1) + (s.hearts % 2 ? '♥ ♥' : ' ♥ ♥ ')
142
143 const lines = pose.map(l => fill(l, face))
144 return (
145 <Box flexDirection="column">
146 <Text color={s.hearts > 0 ? 'magenta' : 'yellow'}>{lift ? ' ' : top}</Text>
147 {lift ? <Text color="yellow">{top}</Text> : null}
148 {lines.map(l => (
149 <Text color={color}>{pad(x)}{l}</Text>
150 ))}
151 {lift ? null : <Text> </Text>}
152 <Text bold>{props.name ?? 'Buddy'}</Text>
153 <Text dimColor>{props.label ?? ''}</Text>
154 </Box>
155 )
156}
157hooks/lib/patterns.ts 181 lines1// What counts as a send, a spend or a danger. Plain logic, no mods API, so it can be unit-tested.
2// Pattern-based by design: it catches the known tools and commands, not every possible script.
3
4export type Kind = 'danger' | 'spend' | 'send'
5
6export type Hit = {
7 kind: Kind
8 // A short stable key for "approve all today", e.g. "gmail:send_message" or "host:api.apify.com".
9 target: string
10 // One line for the dialog.
11 what: string
12 // True when the call has a recipient field Buddy can rewrite to "me first".
13 canSendToMe: boolean
14}
15
16const SHELL_TOOLS = new Set(['Bash', 'PowerShell', 'Monitor'])
17
18// Connector (MCP) actions, matched on the part after the last "__".
19const MCP_SEND = /^(send_message|send|reply|forward|post|publish|share_file|schedule_message|slack_send_message|slack_schedule_message|create_event|respond_to_event|upload)/i
20const MCP_DANGER = /^(trash_|delete_|remove_|purge|destroy)/i
21// Paid services, matched on the connector (server) name, plus the action that runs work.
22const PAID_SERVER = /(apify|wavespeed|kie|elevenlabs|heygen|fal|replicate|openai|runway|luma|suno)/i
23const PAID_ACTION = /(call-actor|call_actor|run|generate|create|text_to|speech|image|video|rag-web-browser|web-fetch)/i
24
25// Hosts of paid APIs Josh and his audience call from scripts.
26const PAID_HOSTS = [
27 'api.apify.com',
28 'api.wavespeed.ai',
29 'api.kie.ai',
30 'api.elevenlabs.io',
31 'api.heygen.com',
32 'fal.run',
33 'queue.fal.run',
34 'api.replicate.com',
35 'api.openai.com',
36 'api.runwayml.com',
37 'api.anthropic.com',
38 'generativelanguage.googleapis.com',
39 'api.stability.ai',
40 'api.mistral.ai',
41 'api.together.xyz',
42 'api.deepgram.com',
43 'api.assemblyai.com',
44 'api.lumalabs.ai',
45 'api.suno.ai',
46]
47
48const DANGER_SHELL: [RegExp, string][] = [
49 // Deleting one named file is routine; folders and wildcards are where work gets lost.
50 [/\brm\s+([^\n;&|]*\s)?(-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)\b/, 'delete a folder and everything in it (rm -r)'],
51 [/\brm\s+[^\n;&|]*[*?]/, 'delete every file matching a wildcard (rm *)'],
52 [/\bRemove-Item\b[^\n|;]*-Recurse\b/i, 'delete a folder and everything in it (Remove-Item -Recurse)'],
53 [/\bRemove-Item\b[^\n|;]*[*?]/i, 'delete every file matching a wildcard (Remove-Item *)'],
54 [/\b(rmdir|rd)\s+\/s\b/i, 'delete a folder (rmdir /s)'],
55 [/\bdel\s+([^\n;&|]*\s)?\/s\b/i, 'delete files in every subfolder (del /s)'],
56 [/\bdel\s+[^\n;&|]*\*/i, 'delete every file matching a wildcard (del *)'],
57 [/\bgit\s+reset\s+--hard\b/i, 'wipe uncommitted changes (git reset --hard)'],
58 [/\bgit\s+clean\s+-[a-z]*f/i, 'delete untracked files (git clean -f)'],
59 [/\bgit\s+(checkout|restore)\s+(--\s+)?\.(\s|$)/i, 'discard all changes (git checkout/restore .)'],
60 [/\bgit\s+push\b[^\n;|]*(--force\b|--force-with-lease\b|\s-f\b|\s\+\S)/i, 'force push (rewrites remote history)'],
61 [/\bdrop\s+(table|database|schema)\b/i, 'drop a database table'],
62 [/\b(prisma\s+migrate\s+reset|db:reset|supabase\s+db\s+reset)\b/i, 'reset a database'],
63]
64
65const SEND_SHELL: [RegExp, string, string][] = [
66 [/\bgit\s+push\b/i, 'git:push', 'push code to the remote (git push)'],
67 [/\bgh\s+(pr\s+(create|merge)|release\s+create|issue\s+create)\b/i, 'gh:publish', 'publish on GitHub (gh)'],
68 [/\bvercel\b[^\n;|]*(--prod\b|\bdeploy\b)/i, 'vercel:deploy', 'deploy to Vercel'],
69 [/\b(fly|flyctl)\s+deploy\b/i, 'fly:deploy', 'deploy to Fly.io'],
70 [/\bnpm\s+publish\b/i, 'npm:publish', 'publish a package to npm'],
71]
72
73const WRITE_METHOD = /(-X\s*(POST|PUT|PATCH|DELETE)\b|--request\s+(POST|PUT|PATCH|DELETE)\b|\s(-d|--data\S*|-F|--form)\s|-Method\s+(Post|Put|Patch|Delete)\b|-Body\b)/i
74const HTTP_CLIENT = /\b(curl|wget|Invoke-RestMethod|Invoke-WebRequest|irm|iwr|httpie|http)\b/i
75const URL_HOST = /https?:\/\/([a-z0-9.-]+)/gi
76const LOCAL_HOST = /^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|[a-z0-9-]+\.localhost|[a-z0-9.-]+\.test)$/i
77
78const short = (text: string, max: number) => (text.length > max ? text.slice(0, max - 1) + '…' : text)
79
80export function hostsIn(command: string): string[] {
81 const out: string[] = []
82 for (const m of command.matchAll(URL_HOST)) out.push(m[1].toLowerCase())
83 return out
84}
85
86// Text fed to a program through a heredoc (<<EOF ... EOF) is data, not a command:
87// a script that merely mentions "rm -rf" or "git push" should not trip a guard.
88export function stripHeredocs(command: string): string {
89 return command.replace(/<<-?\s*(['"]?)([A-Za-z_]\w*)\1[^\n]*\n[\s\S]*?\n[ \t]*\2[ \t]*(?=\n|$)/g, '<<HEREDOC')
90}
91
92// Extra paid hosts from Buddy's settings (e.g. "api.stripe.com, api.twilio.com").
93let extraPaidHosts: string[] = []
94export function setExtraPaidHosts(list: string | undefined) {
95 extraPaidHosts = (list ?? '')
96 .split(',')
97 .map(s => s.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, ''))
98 .filter(Boolean)
99}
100
101export function classifyShell(command: string): Hit | undefined {
102 const cmd = stripHeredocs(command).trim()
103 for (const [re, what] of DANGER_SHELL) {
104 if (re.test(cmd)) return { kind: 'danger', target: 'shell:' + what, what: `${what}: ${short(cmd, 120)}`, canSendToMe: false }
105 }
106 const hosts = hostsIn(cmd)
107 const paid = hosts.find(h => [...PAID_HOSTS, ...extraPaidHosts].some(p => h === p || h.endsWith('.' + p)))
108 if (paid && HTTP_CLIENT.test(cmd)) {
109 return { kind: 'spend', target: 'host:' + paid, what: `paid API call to ${paid}: ${short(cmd, 120)}`, canSendToMe: false }
110 }
111 if (/\bapify\s+(call|run|actors\s+call)\b/i.test(cmd)) {
112 return { kind: 'spend', target: 'cli:apify', what: `paid Apify run: ${short(cmd, 120)}`, canSendToMe: false }
113 }
114 for (const [re, target, what] of SEND_SHELL) {
115 if (re.test(cmd)) return { kind: 'send', target, what: `${what}: ${short(cmd, 120)}`, canSendToMe: false }
116 }
117 const external = hosts.find(h => !LOCAL_HOST.test(h))
118 if (external && HTTP_CLIENT.test(cmd) && WRITE_METHOD.test(cmd)) {
119 return { kind: 'send', target: 'host:' + external, what: `send data to ${external}: ${short(cmd, 120)}`, canSendToMe: false }
120 }
121 return undefined
122}
123
124export function classifyMcp(tool: string, args: Record<string, unknown>): Hit | undefined {
125 if (!tool.startsWith('mcp__')) return undefined
126 const parts = tool.split('__')
127 const server = parts[1] ?? ''
128 const action = parts[parts.length - 1] ?? ''
129 const label = `${server.replace(/^claude_ai_/, '')}:${action}`
130 // Drafts never leave your account, so creating, updating or deleting one is not held.
131 if (/draft/i.test(action)) return undefined
132 if (MCP_DANGER.test(action)) {
133 return { kind: 'danger', target: 'mcp:' + label, what: `${label}`, canSendToMe: false }
134 }
135 const readOnly = /^(get|list|search|abort|fetch-|read|describe|status)/i.test(action)
136 if (PAID_SERVER.test(server) && !readOnly && PAID_ACTION.test(action)) {
137 return { kind: 'spend', target: 'mcp:' + label, what: `${label}`, canSendToMe: false }
138 }
139 if (MCP_SEND.test(action) || /send|post|publish/i.test(action)) {
140 const hasRecipient = 'to' in args || 'recipient' in args
141 return { kind: 'send', target: 'mcp:' + label, what: `${label}`, canSendToMe: hasRecipient }
142 }
143 return undefined
144}
145
146export function classify(tool: string, input: Record<string, unknown>): Hit | undefined {
147 if (SHELL_TOOLS.has(tool)) {
148 const command = typeof input.command === 'string' ? input.command : ''
149 return command ? classifyShell(command) : undefined
150 }
151 return classifyMcp(tool, input)
152}
153
154// What the call is about, for the dialog: recipient, subject and body when the tool has them.
155export function describeArgs(args: Record<string, unknown>): string {
156 const pick = (...keys: string[]) => {
157 for (const k of keys) if (args[k] !== undefined && args[k] !== '') return args[k]
158 return undefined
159 }
160 const fmt = (v: unknown, max: number) => short(typeof v === 'string' ? v : JSON.stringify(v), max)
161 const to = pick('to', 'recipient', 'recipients', 'channel', 'channel_id', 'attendees')
162 const subject = pick('subject', 'title', 'summary', 'name')
163 const body = pick('body', 'text', 'message', 'content', 'description', 'input')
164 const parts: string[] = []
165 if (to !== undefined) parts.push(`To: ${fmt(to, 80)}`)
166 if (subject !== undefined) parts.push(`Subject: ${fmt(subject, 80)}`)
167 if (body !== undefined) parts.push(`"${fmt(body, 160)}"`)
168 return parts.join(' | ')
169}
170
171// Rewrite a send so it reaches only me: recipient replaced, cc and bcc removed.
172export function toMeOnly(args: Record<string, unknown>, myEmail: string): Record<string, unknown> | undefined {
173 if (!myEmail) return undefined
174 const out: Record<string, unknown> = { ...args }
175 if ('to' in args) out.to = Array.isArray(args.to) ? [myEmail] : myEmail
176 else if ('recipient' in args) out.recipient = myEmail
177 else return undefined
178 for (const k of ['cc', 'bcc', 'Cc', 'Bcc', 'ccRecipients', 'bccRecipients']) delete out[k]
179 return out
180}
181