A virtual office side panel: Clawd runs the floor, every subagent is an employee at a desk

<img src="docs/avatars/banner.svg" alt="Clawd, the chief of staff, hands a document to a builder, who works on it and sends back a done tick" width="400">
Brief Clawd once. He picks specialists from your installed helpers, runs independent work in the background, and brings back one report. Keep talking while the specialists work.
free to talk · uses your installed helpers · right-sized models · live office panel
What it does · How it runs · The office · Setup · Privacy
<!-- SCREENSHOT: the Office tab mid-job, or a short GIF of /office-demo. -->
claude plugin marketplace add vedant-shah/clawd-hq
claude plugin install clawd-hq@clawd-hq
Start a session. The office opens on its own. Type /office-demo for a one-minute tour.
Needs Claude Code v2.1.287 or later.
Clawd HQ isn't a new agent runtime. It packages Claude Code's native agents into an opinionated project workflow: delegation by default for larger jobs, model and effort sizing, quiet progress, and a live office panel.
Free to talk is the aim, not a promise. Short direct jobs (a single command, a line or two) Clawd does himself, and then you wait.
Every check can be turned off in Settings. Nothing is ever sent for you. Buttons fill your prompt box; the one exception is "Add to CLAUDE.md", which writes the line you see.
Claude Code already runs subagents in the background, with a model and effort per agent (docs). Clawd HQ sets that up for you and adds the workflow around it.
| Plain Claude Code | With Clawd HQ | |
|---|---|---|
| Delegation | Claude decides case by case | Larger jobs go to specialists by default |
| Choosing models | You or each agent file set them | Clawd sizes model and effort per job |
| Questions | Come as they arise | Up to four in one box, at a pause |
| Progress | Raw tool rows in the chat | Plain-words steps in a live office panel |
How a request flows
The ways Clawd can staff a job
/council <question>: four fresh voices answer once, without seeing each other, and Clawd sums up without being one of them. You decide. The office shows it as one Council card.Type /office to open it. The Office tab looks like this:
╭──────────────────────────────────────────────────╮
│ [Clawd] Clawd Chief of Staff ● Free │
│ Opus 5.5 · High │
│ ╭─────────────────────────────────────╮ │
│ │ Desks are busy. I'm all ears. │ │
│ ╰─────────────────────────────────────╯ │
╰──────────────────────────────────────────────────╯
YOU SHOULD KNOW
╭──────────────────────────────────────────────────╮
│ HEADS UP · Builder │
│ The report says all tests pass, but one test │
│ file was skipped. │
│ [Learn more] Ask Clawd Dismiss │
╰──────────────────────────────────────────────────╯
AT WORK · 3
╭──────────────────────────────────────────────────╮
│ [pic] Builder Add the export button │
│ Writing the test for the empty case. │
│ Sonnet 5.5 · medium · 4m · 38K tokens │
│ ▓▓▓░░ Step 3 of 5 │
╰──────────────────────────────────────────────────╯
╭──────────────────────────────────────────────────╮
│ [pic][pic] Planner & Reviewer Plan the move │
│ Working · 6m · 52K tokens │
╰──────────────────────────────────────────────────╯
[Usage ▾] 42% · 18% · 9%
The other tabs:
Every helper gets its own pixel Clawd, drawn for what it does:
<img src="docs/avatars/preview.png" alt="A sheet of pixel-art Clawd avatars, one per helper, each with its own outfit, hat and tool" width="520">
<!-- SCREENSHOT: a cropped strip of the avatars, if the full sheet is too tall. -->
Setup runs on its own the first time. No questions. A card shows what it picked.
Type /office-setup to run it again. Turn off "Automatic setup" in Settings if you'd rather start it yourself.
All on by default. Flip them in the Settings tab.
| Switch | When it's off |
|---|---|
| Clawd runs the chat | Claude behaves as usual. You keep the panel. |
| Quiet chat | The chat shows every row. |
| Automatic setup | Setup runs only when you type /office-setup. |
| Recap on Clawd's card | No recap is made. |
| You should know | Finished work isn't checked. Claude Code's own note works as usual. |
| Left undone check | The model check is skipped. Code markers are still read. |
| Your own voice file | A path to a text file that changes Clawd's tone. Empty by default. |
Clawd's rules also reach scripted runs (claude -p and the Agent SDK). Turn off "Clawd runs the chat" if you don't want that.
Most of it runs on your machine. Model calls use your plan.
| When | Model | What it sees |
|---|---|---|
| Setup picks a team | Sonnet, read-only | Files in this project it opens (no content search, no secret-named files, nothing outside the folder), plus your helpers' names and use counts. About $0.15 per project on API billing ($0.13 to $0.18 across 11 real projects). |
| Setup fallback | Opus, once | A project summary, the README, your instruction files, helper names and counts |
| Setup writes your workflow | Haiku | Your instruction files |
| Recap | The session's model | One short question on the cached chat |
| You should know | Haiku | The brief, each step, and the report. Long outputs are trimmed. |
| Left undone check | Haiku | Your request and Clawd's final report |
| Coffee break | The session's model | One short question on the cached chat |
Apart from these calls, the plugin opens no network connections and starts no processes.
~/.clawd-hq/, made only when you edit them.Specialists use your plan like any Claude work. Clawd picks the smallest model for each job, so routine work often runs on Haiku. Each extra check is one small call, and each can be turned off.
No. Failures, stopped jobs, errors, questions and permission requests always show. Press ctrl+o for the full view.
Yes. Turn off "Clawd runs the chat". You keep the panel.
The panel is a mod, and mods don't run in Cowork or Chat.
claude plugin marketplace update clawd-hq
Then run /reload-plugins or restart Claude Code. You can turn on auto-update in /plugin.
Early and still changing. Please open an issue when you hit a rough edge.
From plugins/clawd-hq:
claude plugin validate .
claude plugin test .
npx -y -p typescript tsc --noEmit -p .
Unofficial. Not made by, endorsed by, or affiliated with Anthropic. Clawd is Anthropic's mascot. MIT license, see LICENSE.
hooks/register.tsx 793 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { Artifact, Badge, Boss, ContractorOffer, Employee, Fx, KnowState, LeftItem, Payroll, RuleOffer } from '../types'
5import { FILE_TOOLS, leftActions, leftAnswer, leftAsked, leftOwnTurn, leftStart, leftToolUsed, leftTurnStart, leftWatch, type LeftIo } from './left-io'
6import { BRIEF_NOTE, HANDOVER_NOTE, STAFFING_NOTE, fit, parseChoices, parseEffort } from './desk'
7import type { Effort } from './desk'
8import { resumedEffort } from './resume-effort'
9import { parsePairUp } from './pair-up'
10import { cleanArtifacts, hideArtifact, keepArtifact, sweepArtifacts } from './artifacts'
11import type { ArtifactAnswer, ArtifactIo } from './artifacts'
12import { READING_BRIEF, THINKING, narrationOf, sentenceOf } from './activity'
13import { BLURB_CHARS, DEMO_TOOL, FRAME_MS, STEP_TOOL } from './constants'
14import { ownToolAnswer } from './own-tools'
15import type { OwnToolIo } from './own-tools'
16import { blank, smallRow } from './quiet-rows'
17import type { Resolve } from './quiet-rows'
18import { createScoutBox } from './scout-box'
19import { SCOUT_CRASH_DENY, runScout, scoutRoute, spawnTypeOf } from './scout-run'
20import type { RouteIo, ScoutHost } from './scout-run'
21import { SCOUT_SPEC, SCOUT_TIMEOUT_MS, SCOUT_TYPE, TEAM_PICK_SPEC } from './scout-spec'
22import { freshHire, isLively, isSettling, settle, turnEndBoss, withBlurb, withJobs } from './office-state'
23import { holdBack, resetPayroll, reviewPayroll, savePayroll, setLaidOff } from './payroll'
24import { checkOnboard, chooseOnboard, isSetupBusy, restartOnboard, savedOf, startOnboard } from './onboard'
25import { ancestorPaths, answerText, breakdownOf, commandsOf, listEntries } from './onboard-adapt'
26import { rehire } from './hire'
27import { PROFILE_BLOCK, profileBlock } from './profile'
28import { PROFILE_KEY, teamKey } from './onboard-types'
29import type { OnboardCard, OnboardIo, Profile, Team } from './onboard-types'
30import type { PayrollIo } from './payroll'
31import { ROWS_KEY, setToggle } from './configs'
32import type { ConfigField, ConfigIo } from './configs'
33import { BRAND, labelOf } from './office'
34import { renderPanel } from './panel'
35import { limitsOf } from './meters'
36import { contextOf, noteRequest, noteThreshold, startGauge } from './usage'
37import { isBreakTime, isPersonCompact, takeCoffeeBreak, whileCompacting, type CoffeeIo } from './coffee-break'
38import { isNotification, isPersonMessage, withHandBack, withNewWork, withNotice, withPersonSpoke, withToolUsed, withTurnEnd } from './checkpoint'
39import { keepCoffeeRecord } from './coffee-debug'
40import type { CoffeeDebugIo } from './coffee-debug'
41import type { GaugeIo } from './usage'
42import { DEMO, isActive } from './panel-model'
43import { startDemo } from './demo'
44import type { DemoIo } from './demo'
45import { SECTION_ID, SEED_KEYS, isBriefed, optionsOf, readBriefing } from './instructions'
46import type { Briefing, BriefingIo, BriefingOptions } from './instructions'
47import { BYPASS_KEY, REACH0, fallbackText, isFallbackDue, judged, withCompose, withNewConversation, withRequest, withSent } from './rules-reach'
48import { SHIPPED_DENY, clawdActions, editNote, editPartOf, guardOnCrash, isShippedWrite, readFailed, readFailedLine, refreshClawd } from './clawd-edit'
49import type { ClawdIo } from './clawd-edit'
50import { maybeRecap, noteRecapTurn, resetRecap, setRecapOn } from './recap'
51import { liveOptions, loadSaved, useSaved } from './toggle-store'
52import type { RecapIo } from './recap'
53import { isBackgroundHint, isHandback, isNoUpdate, rowLook } from './quiet'
54import { checkHandback, checkOwnTurn, forgetKnow, isWatching, keepBrief, knowActions, knowPrompt, knowToolUsed, knowTurnStart, startKnow } from './know-check'
55import type { KnowIo } from './know-check'
56import { KNOW0, QUIET_FORK, isBuiltinKnow } from './know'
57import { PANES, askAgain, askOnAttach, openAtStart, openPanes, pinHeight, raise } from './panes'
58import type { PaneIo } from './panes'
59import type { PanelTools } from './panel-kit'
60import type { PanelActions, PanelData } from './panel-types'
61import { reportStep } from './steps'
62import type { StepIo } from './steps'
63import { isCountedTool } from './usage-count'
64import { recordUse } from './use-tally'
65import { scrolled } from './scroll-window'
66import { DEMO_SPEC, FIND_HELPERS_SPEC, HIRE_CONTRACTOR_SPEC, OFFER_RULE_SPEC, STEP_SPEC } from './tool-specs'
67import { findHelpers } from './find-helpers'
68import { contractorActions, hireContractor } from './contractor'
69import type { ContractorIo } from './contractor'
70import { checkOld, oldActions } from './old-decisions'
71import type { OldIo } from './old-decisions'
72import { offerRule, ruleActions } from './rule-io'
73import type { RuleIo } from './rule-io'
74import { hire, withReport, withSaid, withStep, withTool } from './staff-model'
75import { fillCouncil, runCouncil, withVoiceNotes, type CouncilIo } from './council'
76import { clockOut, hireListed, newHire, reconcile, signOfLife, specialistOf } from './run-io'
77import type { RunIo } from './run-io'
78import { BOSS0, BRIEF0, FX0, GAUGE0, PAYROLL0, edit, inLine, reasonOf, runEach, startNote } from './state'
79
80const staff = atom({ plugin: 'clawd-hq', key: 'staff' } as const, [] as Employee[])
81const boss = atom({ plugin: 'clawd-hq', key: 'boss' } as const, BOSS0)
82const fx = atom({ plugin: 'clawd-hq', key: 'fx' } as const, FX0)
83const tick = atom({ plugin: 'clawd-hq', key: 'tick' } as const, 0)
84const blurbs = atom({ plugin: 'clawd-hq', key: 'blurbs' } as const, {} as Record<string, string>)
85const roster = atom({ plugin: 'clawd-hq', key: 'roster' } as const, {} as Record<string, Badge>)
86const payroll = atom({ plugin: 'clawd-hq', key: 'payroll' } as const, PAYROLL0)
87const gauge = atom({ plugin: 'clawd-hq', key: 'gauge' } as const, GAUGE0)
88const artifacts = atom({ plugin: 'clawd-hq', key: 'artifacts' } as const, [] as Artifact[])
89const leftUndone = atom({ plugin: 'clawd-hq', key: 'leftUndone' } as const, [] as LeftItem[])
90const ruleOffers = atom({ plugin: 'clawd-hq', key: 'ruleOffers' } as const, [] as RuleOffer[])
91const contractorOffers = atom({ plugin: 'clawd-hq', key: 'contractorOffers' } as const, [] as ContractorOffer[])
92const know = atom({ plugin: 'clawd-hq', key: 'know' } as const, KNOW0)
93const clawdBrief = atom({ plugin: 'clawd-hq', key: 'brief' } as const, BRIEF0)
94const onboard = atom({ plugin: 'clawd-hq', key: 'onboard' } as const, null as OnboardCard | null)
95
96// Values written by an older version of the mod lack the newer fields: fill them in.
97async function getBoss($: EngineInterface): Promise<Boss> { return { ...BOSS0, ...(await read($, boss)) } }
98async function getFx($: EngineInterface): Promise<Fx> { return { ...FX0, ...(await read($, fx)) } }
99async function getPayroll($: EngineInterface): Promise<Payroll> { return { ...PAYROLL0, ...(await read($, payroll)) } }
100async function setBoss($: EngineInterface, fn: (b: Boss) => Boss) { await update($, boss, b => fn({ ...BOSS0, ...b })) }
101async function setFx($: EngineInterface, fn: (f: Fx) => Fx) { await update($, fx, f => fn({ ...FX0, ...f })) }
102
103// The project the session runs in: payroll is kept per project.
104let cwd = ''
105/** The setup scout (hooks/scout-run.ts): the files it opens and the picks it sends. It is no hire, so it stays off the books. */
106const scoutBox = createScoutBox()
107const scoutHost = ($: EngineInterface): ScoutHost => ({ spawn: a => $.agent.spawn(a), list: () => $.agent.list(), stop: id => $.tool.call({ tool: 'TaskStop', task_id: id }), after: (ms, fn) => $.clock.after(ms, fn) })
108const scoutRouteIo = ($: EngineInterface): RouteIo => ({
109 real: async path => (await $.fs.stat(path, { resolve: true })).realPath, isHired: async id => (await read($, staff)).some(one => one.id === id), typeOf: async id => (await $.agent.list()).find(a => a.id === id)?.type })
110// Each agent's effort, set the moment it is hired so its first request already carries it; staff keeps it across reloads.
111const efforts = new Map<string, Effort>()
112
113/**
114 * Puts a type on the books, with how often it was hired, kept across sessions in the store. Queued, so it never
115 * overlaps another write to the books.
116 */
117const enroll = ($: EngineInterface, type: string, jobs: number, tokens = 0) => inLine(() => enrollNow($, type, jobs, tokens))
118
119/** The write itself, for a caller already inside `inLine`: queueing it again there would wait on itself for ever. */
120async function enrollNow($: EngineInterface, type: string, jobs: number, tokens = 0) {
121 const mine = await read($, roster)
122 const saved = Object.keys(mine).length === 0 ? ((await $.store.get('roster')) as Record<string, Badge> | undefined) : undefined
123 const cur = { ...(saved ?? {}), ...mine }
124 if (cur[type] && jobs === 0 && tokens === 0) {
125 if (saved) await update($, roster, () => cur)
126 return
127 }
128 const next = withJobs(cur, type, jobs, tokens)
129 await update($, roster, () => next)
130 await $.store.set('roster', next)
131}
132
133/** The books of specialists (hooks/run-io.ts): who is at work, hired, heard from or gone. */
134const runIo = ($: EngineInterface): RunIo => ({
135 now: () => $.clock.now(), tick: () => read($, tick), staff: () => read($, staff), changeStaff: fn => update($, staff, fn),
136 blurbs: () => read($, blurbs), enroll: (type, jobs, tokens) => enroll($, type, jobs, tokens), setBoss: fn => setBoss($, fn),
137 toast: text => void $.ui.toast(text), agents: () => $.agent.list(),
138})
139
140/** A resumed specialist is at work again, on a new run; one the books lost (from before a reload) joins them, not counted as a hire. */
141async function rejoin<R extends { agentId?: string }>($: EngineInterface, r: R, e: { subagentType: string; description: string; name?: string; resume?: { agentId: string } }, said?: Effort) {
142 if (!r.agentId) return r
143 const [now, t] = [await $.clock.now(), await read($, tick)]
144 if (!(await read($, staff)).some(one => one.id === r.agentId)) await update($, staff, l => hire(l, freshHire({ ...e, id: r.agentId!, type: e.subagentType }, now, t)))
145 // The level it was hired with (or the follow-up's new one) goes on; the books are the copy that outlives a reload.
146 const level = resumedEffort(said, [r.agentId, e.resume?.agentId], await read($, staff), efforts)
147 if (level) { efforts.set(r.agentId, level); await update($, staff, l => edit(l, r.agentId!, one => ({ ...one, effort: level }))) }
148 await signOfLife(runIo($), r.agentId)
149 await showStatus($)
150 return r
151}
152
153async function showStatus($: EngineInterface) {
154 const n = (await read($, staff)).filter(isActive).length
155 $.ui.status(n > 0 ? `HQ · 🦀 ${n} at desk${n === 1 ? '' : 's'}` : undefined)
156}
157
158// ---- Clawd's instructions: the person's own copies live in the home folder (hooks/instructions.ts) ----
159
160/** File calls do not expand `~`: the home folder by name, '' when the process has none. */
161const homeOf = async ($: EngineInterface) => ((await $.env.get("HOME").catch(() => undefined)) || (await $.env.get("USERPROFILE").catch(() => undefined)) || '').replace(/[\\/]+$/, '')
162
163const briefIo = ($: EngineInterface, home: string, warn: (text: string) => void): BriefingIo => ({
164 root: $.plugin.root, home, warn, read: path => $.fs.read(path), exists: path => $.fs.exists(path),
165 seed: async part => { const v = await $.store.get(SEED_KEYS[part]); return typeof v === 'string' ? v : undefined },
166})
167
168/** What this session's chat was given: read at its first request, again after a session start or /clear. */
169let briefing: Promise<Briefing> | undefined
170/** Which road the rules took this session (hooks/rules-reach.ts), and what an earlier session learnt of this machine. */
171let reach = REACH0
172let wasBypassed: boolean | undefined
173
174/** This session's briefing. Set before anything is awaited, so requests made at the same moment share one read (and one warning). */
175const briefingOf = ($: EngineInterface, opts: BriefingOptions) =>
176 (briefing ??= homeOf($).then(home => readBriefing(briefIo($, home, text => void $.ui.toast(text)), opts)))
177
178/** The rules (and the profile from setup) for a prompt, where the system prompt hook has not run: once per conversation. */
179async function rulesRide($: EngineInterface, opts: BriefingOptions, e: { text: string; command?: unknown }): Promise<string[]> {
180 if (!opts.isOn || e.command !== undefined || e.text.trimStart().startsWith('/') || !isFallbackDue(reach, wasBypassed)) return []
181 const { text } = await briefingOf($, opts)
182 if (text === undefined) return []
183 reach = withSent(reach)
184 return [fallbackText(text, profileBlock((await $.store.get(PROFILE_KEY).catch(() => undefined)) as Profile | undefined))]
185}
186
187/** After a main chat request: what this machine does with the system prompt is kept, and Clawd's card warns when the rules were missing. */
188async function judgeReach($: EngineInterface) {
189 const { isLost, bypassed } = judged(reach, wasBypassed)
190 if (bypassed !== undefined) { wasBypassed = bypassed; await $.store.set(BYPASS_KEY, bypassed) }
191 if ((await getBoss($)).isRulesLost !== isLost) await setBoss($, b => ({ ...b, isRulesLost: isLost }))
192}
193/** The main chat's turn began with an edit request from the Settings tab: the plugin's own instruction files are off limits until it ends. */
194let isEditTurn = false
195
196/** The calls behind the buttons for Clawd's instructions in the Settings tab (hooks/clawd-edit.ts). The prompt box is filled after what is there, never sent. */
197const clawdIo = async ($: EngineInterface, opts: BriefingOptions): Promise<ClawdIo> => ({
198 isOn: opts.isOn, voiceFile: opts.voiceFile, briefing: briefIo($, await homeOf($), () => undefined),
199 loaded: () => (briefing ?? Promise.resolve(undefined)).catch(() => undefined),
200 write: (path, text) => $.fs.write(path, text), setSeed: (part, text) => $.store.set(SEED_KEYS[part], text),
201 promptRead: () => $.prompt.read(), fill: text => $.prompt.fill({ text, mode: 'append' }),
202 get: async () => ({ ...BRIEF0, ...(await read($, clawdBrief)) }), set: fn => update($, clawdBrief, b => fn({ ...BRIEF0, ...b })),
203})
204
205/** The tab follows the files. A read that fails is an amber line in the tab with why (a toast if even that fails); it never stops the hook that asked. */
206const refreshTab = ($: EngineInterface, opts: BriefingOptions, isFresh: boolean) => clawdIo($, opts).then(io => refreshClawd(io, isFresh))
207 .catch((err: unknown) => update($, clawdBrief, b => readFailed({ ...BRIEF0, ...b }, err))).catch((err: unknown) => $.ui.toast(readFailedLine(reasonOf(err))))
208
209// ---- The panes: one per view, so the host's own tab strip switches between them (hooks/panes.ts) ----
210
211const paneIo = ($: EngineInterface): PaneIo => ({
212 open: args => $.ui.open(args),
213 list: () => $.ui.panes(),
214 close: id => $.ui.close({ id }),
215})
216
217/** Set once a write of the artifact list failed this session, so the person is told once. */
218let isArtifactsWarned = false
219
220/** The name an agent's work is filed under; 'agent' when it is not on the books. */
221const byOf = async ($: EngineInterface, id: string) => {
222 const one = (await read($, staff)).find(e => e.id === id)
223 return one ? labelOf(one, (await read($, blurbs))[one.type] ?? '') : 'agent'
224}
225
226// ---- Payroll: which agent types Clawd is offered (hooks/payroll.ts) ----
227
228const payrollIo = ($: EngineInterface): PayrollIo => ({
229 cwd, get: () => getPayroll($), set: async p => { await update($, payroll, () => p) }, keep: (key, p) => $.store.set(key, p),
230 types: async () => [...new Set([...Object.keys(await read($, blurbs)), ...Object.keys(await read($, roster))])],
231 picks: async () => ((await $.store.get(teamKey(cwd))) as Team | undefined)?.picks?.filter(p => p.kind === 'agent').map(p => p.name),
232 list: path => $.fs.list(path), fx: () => getFx($), setFx: fn => setFx($, fn),
233 invalidate: () => { $.ui.invalidate('tool.describe'); $.ui.invalidate('prompt.attachment') },
234})
235
236// ---- The Artifact Desk: the pages Claude published or opened here, kept per project folder ----
237
238const artifactIo = ($: EngineInterface): ArtifactIo => ({
239 folder: () => cwd, now: () => $.clock.now(),
240 change: fn => update($, artifacts, fn),
241 save: (folder, list) => $.store.set(`artifacts:${folder}`, list),
242 warnOnce: text => { if (!isArtifactsWarned) $.ui.toast(text); isArtifactsWarned = true },
243 check: i => $.tool.check(i as never), list: i => $.tool.call({ tool: 'Artifact', ...i }) as never,
244})
245
246/** Left undone (hooks/left-io.ts): work put off, kept per project folder. The Do it now button reuses the heads-up card's prompt fill. */
247const leftIo = ($: EngineInterface): LeftIo => ({
248 folder: () => cwd, now: () => $.clock.now(), change: fn => update($, leftUndone, fn), save: (folder, list) => $.store.set(`leftUndone:${folder}`, list),
249 read: path => $.fs.read(path), complete: ask => $.model.complete(ask), fillPrompt: text => knowIo($).fillPrompt(text), byOf: id => byOf($, id),
250})
251
252/**
253 * The "Add to CLAUDE.md" card (hooks/rule-io.ts). The press writes the exact line shown into the project's CLAUDE.md with no model in
254 * between: the one place the plugin writes that file, and a deliberate exception to "buttons only fill the prompt box".
255 */
256const ruleIo = ($: EngineInterface): RuleIo => ({
257 path: () => (cwd === '' ? '' : `${cwd.replace(/[\\/]+$/, '')}/CLAUDE.md`),
258 exists: path => $.fs.exists(path), read: path => $.fs.read(path), write: (path, text) => $.fs.write(path, text),
259 now: () => $.clock.now(), change: fn => update($, ruleOffers, fn),
260 setDone: fn => setFx($, f => ({ ...f, ruleDone: fn(f.ruleDone) })), after: (ms, fn) => $.clock.after(ms, fn),
261})
262
263/** The one-time card about an old decisions file (hooks/old-decisions.ts): the plugin only checks that the file is there; it never reads or changes it. */
264const oldIo = ($: EngineInterface): OldIo => ({
265 folder: () => cwd, exists: path => $.fs.exists(path), get: key => $.store.get(key), set: (key, value) => $.store.set(key, value),
266 fill: async text => (await $.prompt.fill({ text, mode: 'append' })).isFilled,
267 show: isShown => setFx($, f => ({ ...f, oldDecisions: isShown ? true : undefined })), toast: text => void $.ui.toast(text),
268})
269
270/** The office's own tools (hooks/own-tools.ts): the tour, the offer of a lasting rule, the step report, and the search of everything installed. */
271const ownToolIo = ($: EngineInterface, opts: BriefingOptions): OwnToolIo => ({
272 tour: async () => { await openPanes(paneIo($), false); await startDemo(demoIo($)) },
273 offerRule: (id, input) => offerRule(ruleIo($), id, input), step: (id, input) => reportStep(stepIo($), id, input),
274 find: async (id, input) => findHelpers(await onboardIo($, opts), id, input), contractor: async (id, input) => hireContractor(await contractorIo($, opts), id, input),
275})
276
277/** Contractors (hooks/contractor.ts): setup's calls, plus the offers on the Office tab. */
278const contractorIo = async ($: EngineInterface, opts: BriefingOptions): Promise<ContractorIo> =>
279 ({ ...(await onboardIo($, opts)), change: fn => update($, contractorOffers, fn), toast: text => void $.ui.toast(text) })
280
281/** The step tool (hooks/steps.ts): only a specialist at work here reports. */
282const stepIo = ($: EngineInterface): StepIo => ({
283 isAtWork: async id => { const one = await specialistOf(runIo($), id); return one !== undefined && isActive(one) },
284 record: async (id, report) => { const now = await $.clock.now(); await update($, staff, l => edit(l, id, one => withReport(one, report, now))) },
285})
286
287// ---- The recap (hooks/recap.ts): one line on where things stand, after a few quiet minutes ----
288
289const recapIo = ($: EngineInterface): RecapIo => ({
290 now: () => $.clock.now(), boss: () => getBoss($), setBoss: fn => setBoss($, fn),
291 isTouring: async () => (await getFx($)).demo !== undefined,
292 isShown: async () => ((await $.session.surfaces().catch(() => [])).length > 0),
293 ask: prompt => $.model.fork({ prompt }),
294})
295
296// ---- The check on finished work (hooks/know-check.ts): what it may do, each a `$` call spelled here ----
297
298const knowIo = ($: EngineInterface): KnowIo => ({
299 now: () => $.clock.now(),
300 get: key => $.store.get(key),
301 set: (key, value) => $.store.set(key, value as never),
302 surfaces: () => $.session.surfaces(),
303 panes: () => $.ui.panes(),
304 messages: agentId => (agentId === undefined ? $.session.messages() : $.session.messages({ agentId })),
305 complete: ask => $.model.complete(ask),
306 card: async (): Promise<KnowState> => ({ ...KNOW0, ...(await read($, know)) }),
307 setCard: fn => update($, know, s => fn({ ...KNOW0, ...s })),
308 fillPrompt: text => $.prompt.fill({ text, mode: 'append' }),
309})
310
311// ---- Setup (hooks/onboard.ts): built per use, so the clock, home folder, agent lists and payroll are read as they are now ----
312
313/** The setup card held this session; only setup's own code writes it, so the loose stored shape is an OnboardCard. */
314const setupCard = async ($: EngineInterface) => ((await read($, onboard)) ?? undefined) as OnboardCard | undefined
315
316const onboardIo = async ($: EngineInterface, opts: BriefingOptions): Promise<OnboardIo> => {
317 const [now, home, config, known, p] = [await $.clock.now(), await homeOf($), await $.env.get('CLAUDE_CONFIG_DIR').catch(() => undefined), await read($, blurbs), await getPayroll($)]
318 const types = [...new Set([...Object.keys(known), ...Object.keys(await read($, roster))])]
319 return {
320 now: () => now, cwd, home: () => home, configDir: () => config || undefined, blurbs: () => known, allAgentTypes: () => types, parked: () => p.laidOff,
321 get: async key => (await $.store.get(key)) as never, set: (key, value) => $.store.set(key, value),
322 isShown: async () => (await $.session.surfaces().catch(() => [])).length > 0, isAutoOn: () => opts.isAutoOn,
323 list: dir => listEntries(dir, d => $.fs.list(d), path => $.fs.stat(path)), read: path => $.fs.read(path).catch(() => undefined), exists: path => $.fs.exists(path),
324 ancestors: async name => ancestorPaths(await $.fs.ancestors({ names: [name] })),
325 breakdown: async () => breakdownOf(await $.session.usage({ breakdown: 'summary' })), commands: async () => commandsOf(await $.command.list()),
326 complete: async req => answerText(await $.model.complete(req)),
327 spawnScout: (brief, check) => runScout(scoutBox, scoutHost($), brief, check, SCOUT_TIMEOUT_MS),
328 registerHire: ({ name, description, prompt, skills }) => $.agent.register({ name, description, prompt, skills }).then(() => true, () => false),
329 savePayroll: laidOff => savePayroll(payrollIo($), { ...p, laidOff: [...laidOff], isReviewed: true }), // its stacks kept
330 card: () => setupCard($), setCard: async card => { await update($, onboard, () => card ?? null) },
331 }
332}
333
334// ---- The frame clock ----
335
336async function onFrame($: EngineInterface, frames: number, opts: BriefingOptions) {
337 const [list, f, b, t0] = [await read($, staff), await getFx($), await getBoss($), await read($, tick)]
338 if (frames % 8 === 0) {
339 await reconcile(runIo($))
340 const isDrawn = (await $.session.surfaces().catch(() => [])).length > 0 // the desktop attaches after session start
341 if (isDrawn && !(await read($, onboard))) void onboardIo($, opts).then(checkOnboard).catch(() => undefined) // slow steps never hold a frame
342 }
343 if (frames % 25 === 0) {
344 if (!isSetupBusy(await savedOf({ cwd, get: async key => (await $.store.get(key)) as never }), opts.isAutoOn)) await reviewPayroll(payrollIo($))
345 // The model takes its time: the frames go on meanwhile, and a recap that fails is simply not shown.
346 void maybeRecap(recapIo($)).catch(() => undefined)
347 }
348 // A quiet office only needs a frame now and then, for blinking and snoring; nothing is written in between.
349 if (!isLively(list, f, b, t0) && frames % 3 !== 0) return
350 const t = await update($, tick, n => n + 1)
351 if (list.some(one => isSettling(one, t))) await update($, staff, l => settle(l, t))
352 await showStatus($)
353}
354
355// ---- The side panel: a snapshot to draw, and what it may ask for ----
356
357async function panelData($: EngineInterface, options: BriefingOptions): Promise<PanelData> {
358 return {
359 staff: await read($, staff), boss: await getBoss($), fx: await getFx($), tick: await read($, tick), blurbs: await read($, blurbs),
360 roster: await read($, roster), payroll: await getPayroll($),
361 artifacts: await read($, artifacts), leftUndone: await read($, leftUndone), ruleOffers: await read($, ruleOffers), contractorOffers: await read($, contractorOffers), gauge: await read($, gauge), now: await $.clock.now(), know: await knowIo($).card(),
362 brief: { ...BRIEF0, ...(await read($, clawdBrief)) }, options, onboard: await setupCard($),
363 }
364}
365
366/** Settings shows the list of finished work (true) or its configs (false); the choice is a display flag, shared by every drawing. */
367const showLog = ($: EngineInterface, isOpen: boolean) => setFx($, f => ({ ...f, isLogOpen: isOpen }))
368
369/** The settings rows for `setToggle` (hooks/configs.ts): the Settings switch's, and the one to hand any other caller (onboarding). */
370const configIo = ($: EngineInterface): ConfigIo => ({
371 plugin: $.plugin.name, list: () => $.config.list(), set: args => $.config.set(args), keepKeys: record => $.store.set(ROWS_KEY, record),
372 save: (key, value) => $.store.set(key, value), refresh: async () => $.ui.invalidate('tool.describe'), // the Agent tool's text follows Clawd's switch
373})
374
375/** A config's toggle pressed: its settings row is changed as in /config, and the plugin reloads with it. A refusal, or a call that fails, is shown plainly. */
376async function setConfig($: EngineInterface, field: ConfigField, value: boolean) {
377 // A toggle drawn before Clawd's turn began: the reload would lose what the turn holds, so nothing changes (the tab says why).
378 if ((await getBoss($)).isBusy) return
379 const note = await setToggle(configIo($), field, value)
380 await setFx($, f => ({ ...f, configNote: note }))
381}
382
383
384function panelActions($: EngineInterface, opts: BriefingOptions): PanelActions {
385 return {
386 editClawd: async (target, isTerminal) => clawdActions(await clawdIo($, opts)).editClawd(target, isTerminal),
387 resetClawd: async part => clawdActions(await clawdIo($, opts)).resetClawd(part),
388 setFind: (tab, text) => setFx($, f => ({ ...f, finds: { ...f.finds, [tab]: text } })),
389 hideArtifact: url => hideArtifact(artifactIo($), cwd, url),
390 layOff: type => setLaidOff(payrollIo($), type, true),
391 hire: type => setLaidOff(payrollIo($), type, false),
392 toggleUsage: () => setFx($, f => ({ ...f, isUsageOpen: !f.isUsageOpen })),
393 holdCouncil: () => fillCouncil(councilIo($)),
394 coffeeBreak: isTerminal => takeCoffeeBreak(coffeeIo($), isTerminal).catch((err: unknown) => $.ui.toast(`Couldn't compact the chat: ${reasonOf(err)}.`)),
395 showLog: isOpen => showLog($, isOpen),
396 setConfig: (field, value) => setConfig($, field, value),
397 scrollClawd: async (part, dir) => { const text = (await read($, clawdBrief))[part]?.text ?? ''; await setFx($, f => ({ ...f, scroll: scrolled(f.scroll, part, text, dir) })) },
398 choose: async button => { void chooseOnboard(await onboardIo($, opts), button) }, // a step can wait on the question box or a model: the press does not
399 ...knowActions(knowIo($)),
400 ...leftActions(leftIo($)),
401 ...ruleActions(ruleIo($)),
402 ...contractorActions(() => contractorIo($, opts)),
403 ...oldActions(oldIo($)),
404 }
405}
406
407// ---- The header meters: context and rate limits, kept as the engine reports them ----
408
409const gaugeIo = ($: EngineInterface): GaugeIo => ({
410 now: () => $.clock.now(), usage: () => $.session.usage(), model: () => $.session.model(),
411 threshold: () => $.session.usage({ breakdown: 'summary' }).then(u => u.context.breakdown?.autoCompactThreshold),
412 get: () => read($, gauge), set: fn => update($, gauge, fn),
413})
414
415/** The coffee break button (hooks/coffee-break.ts). Where the engine has no compact call (the desktop app can bundle 2.1.295), calling it fails and the command is put in the prompt box instead. */
416const coffeeIo = ($: EngineInterface): CoffeeIo => ({
417 now: () => $.clock.now(),
418 isBreak: async () => isBreakTime(await getBoss($), await read($, staff), await getFx($)),
419 ask: prompt => $.model.fork({ prompt }), // the note's one short question, on the cached chat
420 compact: args => $.session.compact(args),
421 promptRead: () => $.prompt.read(), fill: text => $.prompt.fill({ text, mode: 'append' }),
422 setNote: async note => { const { turns } = await getBoss($); await setFx($, f => ({ ...f, coffee: note && { ...note, turns } })) },
423 clearReading: async () => { await setBoss($, withNewWork); await update($, gauge, g => ({ ...g, contextPercent: undefined, contextTokens: undefined })) }, // a compaction ends the checkpoint too
424})
425
426/** The Hold a council button and /council (hooks/council.ts): the box is filled after what is there; a typed question is sent as the person's own words. */
427const councilIo = ($: EngineInterface): CouncilIo => ({ fill: text => $.prompt.fill({ text, mode: 'append' }), submit: text => $.prompt.submit({ text, asUser: true }), later: fn => $.clock.after(0, fn), toast: text => void $.ui.toast(text) })
428
429/** The record of why the coffee break button shows or not (hooks/coffee-debug.ts), kept at `debug:coffee` in the store. */
430const coffeeDebugIo = ($: EngineInterface): CoffeeDebugIo => ({
431 now: () => $.clock.now(), save: (key, value) => $.store.set(key, value),
432 data: async () => ({ boss: await getBoss($), staff: await read($, staff), fx: await getFx($), gauge: await read($, gauge) }),
433})
434
435// ---- The demo: a scripted tour with stand-in employees, cleaned up at the end ----
436
437const demoIo = ($: EngineInterface): DemoIo => ({
438 show: view => raise(paneIo($), view), showLog: isOpen => showLog($, isOpen),
439 boss: () => getBoss($), setBoss: fn => setBoss($, fn), tick: () => read($, tick), now: () => $.clock.now(),
440 hire: (id, type, description) => newHire(runIo($), id, type, description), finish: (id, mood) => clockOut(runIo($), id, mood),
441 editStaff: (id, fn) => update($, staff, l => edit(l, id, fn)),
442 dropStandIns: () => update($, staff, l => l.filter(e => !e.id.startsWith(DEMO))),
443 setDemo: demo => setFx($, f => ({ ...f, demo })), showStatus: () => showStatus($),
444 after: (ms, fn) => $.clock.after(ms, fn),
445})
446
447/** The drawing table of a render event, handed to the quiet rows (hooks/quiet-rows.tsx) as a closure. */
448const resolver = ($: EngineInterface): Resolve => e => $.ui.resolve(e)
449
450export const register: Register = (on, options) => {
451 let timer: Timer | undefined
452 let isFraming = false
453 const brief = liveOptions(optionsOf(options)) // each switch read when used: a saved press first (hooks/toggle-store.ts)
454
455 // Clawd's rules and voice join the main chat's instructions: read once a session (and again after /clear), then the same text on every request, so the prompt cache holds.
456 // A plugin seated outermost can send this event past ours (hooks/rules-reach.ts): the rules then ride with a prompt instead.
457 on('prompt.compose', async ($, e, next) => {
458 const base = await next(e)
459 if (!brief.isOn || !isBriefed(e.traits)) return base
460 const { text } = await briefingOf($, brief)
461 reach = withCompose(reach, text !== undefined)
462 return text === undefined ? base : { sections: [...base.sections, { id: SECTION_ID, scope: 'session', text } as const] }
463 })
464
465 on('session.start', async ($, e, next) => {
466 cwd = e.cwd
467 briefing = undefined
468 reach = REACH0
469 isEditTurn = false
470 resetPayroll()
471 isArtifactsWarned = false
472 // The setting only: whether anything is drawn is read at each frame's ask, since the desktop app attaches after this.
473 setRecapOn(() => brief.isRecapOn)
474 // Each step stands on its own: one that fails stops none after it (the Settings tab still fills), and the person is told which.
475 const failed = await runEach([
476 ['saved switches', async () => useSaved(await loadSaved(key => $.store.get(key)))],
477 ['instructions road', async () => { const v = await $.store.get(BYPASS_KEY); wasBypassed = typeof v === 'boolean' ? v : undefined }],
478 ['recap', () => resetRecap(recapIo($))],
479 ['check on finished work', () => startKnow(knowIo($), cwd)],
480 // A review made for an earlier session is not this one's: it is made again within a few seconds if it still stands.
481 ['payroll review', async () => { if ((await getFx($)).layoffs) await setFx($, f => ({ ...f, layoffs: undefined })) }],
482 ['/office', () => $.command.register({ name: 'office', description: `Open ${BRAND}, the virtual office of this session’s agents` })],
483 ['/council', () => $.command.register({ name: 'council', description: 'Ask a few independent voices about a hard choice: /council <question>' })],
484 ['/office-demo', () => $.command.register({ name: 'office-demo', description: `Play a one-minute tour of ${BRAND}’s features` })],
485 ['demo tool', () => $.tool.register(DEMO_SPEC)],
486 ['payroll', async () => { const saved = (await $.store.get(`payroll:${cwd}`)) as Payroll | undefined; if (saved) await update($, payroll, () => ({ ...PAYROLL0, ...saved })) }],
487 // This project's pages only: a list left by another folder is replaced, and what the store holds is checked.
488 ['artifacts', async () => { const pages = cleanArtifacts(await $.store.get(`artifacts:${cwd}`)); await update($, artifacts, () => pages) }],
489 ['left undone', async () => { const items = leftStart(await $.store.get(`leftUndone:${cwd}`)); await update($, leftUndone, () => items) }],
490 ['offer rule tool', () => $.tool.register(OFFER_RULE_SPEC)],
491 ['old decisions card', () => checkOld(oldIo($))],
492 ['step tool', () => $.tool.register(STEP_SPEC)],
493 ['find helpers tool', () => $.tool.register(FIND_HELPERS_SPEC)],
494 ['contractor tool', () => $.tool.register(HIRE_CONTRACTOR_SPEC)],
495 ['team pick tool', () => $.tool.register(TEAM_PICK_SPEC)],
496 ['setup scout', () => $.agent.register(SCOUT_SPEC)],
497 ['setup', async () => startOnboard(await onboardIo($, brief))], // looked for again on the frames
498 ['skill hires', async () => rehire(await onboardIo($, brief))], // the engine forgets registered agents each session
499 ['/office-setup', () => $.command.register({ name: 'office-setup', description: `Set up ${BRAND} for this project: a starting team, with no questions` })],
500 ['roster', () => enroll($, 'general-purpose', 0)],
501 ['meters', () => startGauge(gaugeIo($))],
502 ['instructions', () => refreshTab($, brief, true)],
503 ])
504
505 let frames = 0
506 timer?.cancel()
507 timer = $.clock.every(FRAME_MS, () => {
508 frames += 1
509 // A frame that is still running (a slow agent list) is not stacked on.
510 if (isFraming) return
511 isFraming = true
512 void onFrame($, frames, brief).finally(() => { isFraming = false })
513 })
514
515 const all = [...failed, ...(await runEach([['agent list', () => reconcile(runIo($))]]))]
516 if (all.length > 0) $.ui.toast(startNote(all))
517 // Office is asked to the front on every surface; a refusal is tried once more after the first reply (hooks/panes.ts).
518 void openAtStart(paneIo($))
519 void sweepArtifacts(artifactIo($), cwd).catch(() => undefined) // not waited for: session start never holds on it
520
521 return next(e)
522 })
523
524 // The agent's own stop signal, beside turn.complete: whichever comes first ends the run, the second finds it ended.
525 on('classic.SubagentStop', async ($, e, next) => {
526 await clockOut(runIo($), e.agent_id, 'done')
527 return next(e)
528 })
529
530 // The desktop app starts the session before it draws anything: when it attaches, Office is asked to the front (hooks/panes.ts).
531 on('session.attach', async ($, e, next) => {
532 const result = await next(e)
533 void askOnAttach(paneIo($))
534 return result
535 })
536
537 on('command.run', { command: 'office' }, async $ => {
538 await openPanes(paneIo($), true)
539 return { text: `${BRAND} is open: Office · People · Settings are the tabs at the top.` }
540 })
541
542 // The header's context bar and limit countdowns follow the engine's own readings.
543 on('session.measure', async ($, e, next) => {
544 await update($, gauge, g => ({ ...g, ...contextOf(e.context), limits: limitsOf(e.rateLimits) }))
545 void keepCoffeeRecord(coffeeDebugIo($), 'measure') // the reading of the turn that just ended, which the turn's own record could not have yet
546 return next(e)
547 })
548
549 // The person's own /compact (typed, or the one the coffee break button filled): Clawd drinks while it runs, and a while after it stands.
550 on('session.compact', async ($, e, next) => (isPersonCompact(e) ? whileCompacting(coffeeIo($), () => next(e)) : next(e)))
551
552 // A /clear ends the session without a session.start: from here the list of finished work starts over.
553 on('session.end', async ($, e, next) => {
554 if (e.reason === 'clear') {
555 briefing = undefined
556 const now = await $.clock.now()
557 await update($, gauge, g => ({ ...g, startedAt: now, contextPercent: undefined, contextTokens: undefined }))
558 }
559 // Another conversation takes over this process without a session.start: its recap and its turns are its own.
560 if (e.reason === 'clear' || e.reason === 'resume') { reach = withNewConversation(reach); await resetRecap(recapIo($)) }
561 await forgetKnow(knowIo($))
562 return next(e)
563 })
564
565 on('command.run', { command: 'office-setup' }, async $ => {
566 await openPanes(paneIo($), true)
567 void restartOnboard(await onboardIo($, brief)).catch(() => undefined) // the model calls are not waited for
568 return { text: `${BRAND} setup is running for this project. A small card on the Office tab says what was set up.` }
569 })
570
571 on('command.run', { command: 'council' }, async ($, e) => ({ text: await runCouncil(councilIo($), e.args) }))
572
573 on('command.run', { command: 'office-demo' }, async $ => {
574 await openPanes(paneIo($), false)
575 await startDemo(demoIo($))
576 return { text: `The ${BRAND} tour is playing in the side panel (about a minute).` }
577 })
578
579 // Instruction-aware: remember what each agent type is for, put it on the books, and keep laid-off types off the listing.
580 on('agent.offer', async ($, e, next) => {
581 if (e.agent === SCOUT_TYPE) return { isOffered: false } // the plugin's own: never offered to the chat, never on the books
582 const blurb = fit(e.description, BLURB_CHARS) // cut at a word with no mark: the People row wraps it, and an ellipsis would only hide words
583 // The engine offers every agent type at the same moment when a session starts. Their writes go one at a time:
584 // the state refuses a write that lost the race too often, and the hook was then skipped for that type.
585 await inLine(async () => {
586 if ((await read($, blurbs))[e.agent] !== blurb) {
587 await update($, blurbs, m => withBlurb(m, e.agent, blurb))
588 }
589 if (!(await read($, roster))[e.agent]) await enrollNow($, e.agent, 0)
590 })
591 if (await inLine(() => holdBack(payrollIo($), e.agent))) return { isOffered: false }
592 return next(e)
593 })
594
595 // Clawd learns to pick each hire's model and effort, and, while he runs the chat, that handing work over needs no asking.
596 for (const tool of ['Agent', 'Task']) {
597 on('tool.describe', { tool }, async ($, e, next) => {
598 const r = await next(e)
599 return { ...r, description: r.description + STAFFING_NOTE + (brief.isOn ? HANDOVER_NOTE : '') }
600 })
601 }
602
603 on('agent.spawn', async ($, e, next) => {
604 if (spawnTypeOf(e) === SCOUT_TYPE) { const r = await next(e); if (r.agentId) scoutBox.mark(r.agentId); return r } // marked before anyone else hears of it: no brief notes, no desk
605 // A resumed run keeps its first brief (the engine takes no change to it) and its place on the books: no hire is counted again.
606 // Clawd's [effort: …] line comes off the brief; every agent learns how to report its questions and choices.
607 // A pair-up member's `PAIR-UP: <goal>` line (hooks/pair-up.ts) comes off the same way, right after it.
608 const { effort, prompt: unEffort } = parseEffort(e.prompt)
609 const { goal, isCouncil, prompt } = parsePairUp(unEffort)
610 await setBoss($, withNewWork) // a hire or a resume is new work: the coffee break checkpoint is over
611 if (e.resume) return rejoin($, await next(e), e, effort) // the engine takes no change to a resumed message, so its effort line stays on it
612 // A workflow's agent keeps the script's prompt (2.1.300 applies a rewrite there): its answer is the script's to read.
613 const sent = e.workflow ? e.prompt : prompt + BRIEF_NOTE
614 const r = await next({ ...e, prompt: sent })
615 if (r.agentId) {
616 keepBrief(r.agentId, sent)
617 if (effort) efforts.set(r.agentId, effort)
618 await newHire(runIo($), r.agentId, e.subagentType, e.description, e.name)
619 const pair = goal !== undefined && !e.workflow ? { goal, at: await $.clock.now(), ...(isCouncil ? { isCouncil } : {}) } : undefined // a workflow keeps its script's prompt, so its line was never taken off
620 await update($, staff, l => edit(l, r.agentId!, one => ({ ...one, ...(effort ? { effort } : {}), ...(pair ? { pair } : {}), model: one.model || r.model })))
621 await showStatus($)
622 }
623 return r
624 })
625
626 // Each model request of an agent: what it has spent, and how full its context is.
627 on('turn.step', async function* ($, e, next) {
628 // Not waited for: the store's answer never holds a request back (noteRequest keeps its own errors).
629 if (!e.agentId) void noteRequest(gaugeIo($), e.model, e.effort)
630 const me = e.agentId ? (await read($, staff)).find(one => one.id === e.agentId) : undefined
631 // A request is a sign of life, and a resumed specialist's first can come before any tool call.
632 if (me) await signOfLife(runIo($), me.id, THINKING)
633 const effort = e.agentId ? efforts.get(e.agentId) ?? me?.effort : undefined
634 if (!e.agentId) reach = withRequest(reach, e.messageCount)
635 const result = yield* next(effort ? { ...e, effort } : e)
636 // The request's system prompt was composed on the way: whether the rules reached it is known now.
637 if (!e.agentId && brief.isOn) await judgeReach($).catch(() => undefined) // a store that refuses only means it is learnt again next session
638 const [u, said] = [result.usage, narrationOf(result.answer ?? '')]
639 if (!e.agentId || (!u && !said)) return result
640 const now = await $.clock.now()
641 await update($, staff, l => edit(l, e.agentId!, one => {
642 const stepped = u ? withStep(one, u, u.model || e.model, now) : one
643 // A request that comes back after the run was sent home says nothing: its words would outlive the run.
644 return said && isActive(one) ? withSaid(stepped, said) : stepped
645 }))
646 return result
647 })
648
649 // A page Claude publishes or opens, by Clawd or by a specialist, joins the Artifact Desk on the Office tab.
650 on('tool.call', { tool: 'Artifact' }, async ($, e, next) => {
651 const folder = cwd
652 const ran = await next(e)
653 // The tool's answer matters more than the desk: the save is started, not waited for, and a desk that cannot be kept is skipped, not thrown.
654 void keepArtifact(artifactIo($), folder, e as unknown as Record<string, unknown>, ran as ArtifactAnswer).catch(() => undefined)
655 return ran
656 })
657
658 // Unfinished-work lines Claude or a specialist writes into files (TODO, a skipped test, "not implemented") join Left undone.
659 for (const tool of FILE_TOOLS) on('tool.call', { tool: tool as 'Edit' }, ($, e, next) => leftWatch(leftIo($), e as never, () => next(e))) // MultiEdit is no declared tool name, but the engine runs one if a build has it
660
661 on('tool.call', async ($, e, next) => {
662 const tool = String(e.tool)
663 const input = e as unknown as Record<string, unknown>
664 const id = e.agentId
665 // The running tally of agent and skill use (hooks/use-tally.ts): names and counts only, for what session files are too big to show. Never waited for.
666 if (isCountedTool(tool)) void (async () => recordUse({ get: async key => (await $.store.get(key)) as never, set: (key, value) => $.store.set(key, value) }, cwd, await $.session.id(), tool, input))().catch(() => undefined)
667 if (isEditTurn && isShippedWrite(tool, input)) return { deny: SHIPPED_DENY } as never
668 // The setup scout reads inside the project and sends its picks, guarded from its first call (hooks/scout-run.ts); anyone else is turned away from its tool.
669 const scouted = await scoutRoute(scoutBox, scoutRouteIo($), cwd, id, tool, input)
670 if (scouted) return ('run' in scouted ? next({ ...e, ...scouted.run } as never) : scouted) as never
671 // Every tool Clawd uses himself counts towards a long turn of his own (hooks/know-check.ts), but a step report is no work.
672 if (id === undefined && tool !== STEP_TOOL) { knowToolUsed(); leftToolUsed(tool); await setBoss($, b => withToolUsed(b, tool)) } // editing files himself ends a coffee break checkpoint at the turn's end
673 const own = await ownToolAnswer(ownToolIo($, brief), tool, id, input) // the tour, the offer of a rule, a specialist's step report, and Clawd's search
674 if (own) return own as never
675 // What the person answers in Clawd's question box settles the job at hand only: nothing is saved, and his status line stays as it was.
676 if (tool === 'AskUserQuestion' && id === undefined) return next(e)
677 if (id === undefined) {
678 if (tool !== 'Agent' && tool !== 'Task') await setBoss($, b => ({ ...b, activity: sentenceOf(tool, input) }))
679 return next(e)
680 }
681 // An id no spawn announced and the engine does not list is no one of ours: no hire, no revival.
682 const known = (await read($, staff)).find(one => one.id === id)
683 const listed = known ? undefined : (await $.agent.list()).find(one => one.id === id)
684 if (!known && !listed) return next(e)
685 if (listed) await hireListed(runIo($), listed)
686 else await signOfLife(runIo($), id)
687 await update($, staff, l => edit(l, id, one => withTool(one, sentenceOf(tool, input))))
688 try { return await next(e) } finally { await update($, staff, l => edit(l, id, one => (one.mood === 'working' ? { ...one, mood: 'thinking' } : one))) }
689 }).catch((_$, e, next) => {
690 if (!next.called && e.agentId !== undefined && scoutBox.isScout(e.agentId)) return { deny: SCOUT_CRASH_DENY } as never // fails closed
691 return !next.called && guardOnCrash(isEditTurn, String(e.tool), e as unknown as Record<string, unknown>) === 'deny' ? { deny: SHIPPED_DENY } as never : next(e)
692 })
693
694 // The person's prompts: the latest ride along with the check on finished work, and the second passes a note over.
695 // An edit request from the Settings tab carries a note of its own: the file to edit, and what must not be touched.
696 on('prompt.submit', async ($, e, next) => {
697 leftAsked(e)
698 if (isPersonMessage(e)) await setBoss($, b => withPersonSpoke(b, e.origin?.kind)) // what closed before it is behind us: the coffee break button waits for the next checkpoint
699 else if (isNotification(e)) await setBoss($, b => withNotice(b, e.turnId !== undefined)) // a job's notification starts or joins a turn: which one reports a hand-back
700 if (brief.isKnowOn) await knowPrompt(knowIo($), e as { text: string })
701 const note = await editNote(e.text, brief.voiceFile, $.plugin.root, () => homeOf($))
702 const added = [...(note === undefined ? [] : [note]), ...(await rulesRide($, brief, e))]
703 return next(added.length === 0 ? e : { ...e, context: [...(e.context ?? []), ...added] })
704 })
705 // While ours is on and an office tab is open, Claude Code's own "You should know" stays quiet; every other side question passes.
706 on('model.fork', async ($, e, next) => (brief.isKnowOn && isBuiltinKnow(next.origin) && (await isWatching(knowIo($))) ? { value: QUIET_FORK } : next(e)))
707
708 // Who the person is, from setup, rides at the top of every conversation.
709 on('prompt.context', async ($, e, next) => {
710 const r = await next(e)
711 const profile = profileBlock((await $.store.get(PROFILE_KEY).catch(() => undefined)) as Profile | undefined)
712 return profile ? { ...r, blocks: [...r.blocks, { name: PROFILE_BLOCK, text: profile }] } : r
713 })
714
715 on('turn.start', async ($, e, next) => {
716 // Since 2.1.299 specialists' turns start here too: all of this is about Clawd's own, in the main chat.
717 if (e.agentId !== undefined) return next(e)
718 // Work goes on, so a recap of the pause before it is out of date.
719 noteRecapTurn()
720 knowTurnStart(e.text ?? '')
721 leftTurnStart()
722 isEditTurn = editPartOf(e.text ?? '') !== undefined
723 await setBoss($, b => ({ ...b, isBusy: true, turns: b.turns + 1, recap: undefined, activity: e.text ? READING_BRIEF : 'Back at it' }))
724 return next(e)
725 })
726
727 on('turn.complete', async ($, e, next) => {
728 if (e.agentId !== undefined) {
729 scoutBox.finish(e.agentId) // a scout that ends with no picks sent ends the wait; anyone else is no scout, and nothing happens
730 const asker = (await read($, staff)).find(one => one.id === e.agentId)
731 // Key choices the agent made itself go on its own record, for this session. Its questions stay in its report, for Clawd.
732 if (asker && !asker.id.startsWith(DEMO)) {
733 if (e.reason === 'answer') await setBoss($, withHandBack) // work handed back: a checkpoint once Clawd has reported it
734 const by = labelOf(asker, (await read($, blurbs))[asker.type] ?? '')
735 const choices = parseChoices(e.answer ?? '')
736 if (choices.length > 0 || asker.pair?.isCouncil) await update($, staff, l => edit(l, asker.id, one => withVoiceNotes(one, choices, e.reason === 'answer' ? e.answer ?? '' : '')))
737 // After each hand-back, a check of the work against its report; a note may join Clawd's card.
738 if (brief.isKnowOn) void checkHandback(knowIo($), { ...e, agentId: asker.id }, by)
739 void leftAnswer(leftIo($), e, by)
740 }
741 await clockOut(runIo($), e.agentId, e.reason === 'answer' ? 'done' : 'failed')
742 await showStatus($)
743 } else {
744 if (brief.isKnowOn) void checkOwnTurn(knowIo($), e)
745 void leftOwnTurn(leftIo($), e, brief.isLeftOn)
746 isEditTurn = false
747 await askAgain(paneIo($))
748 const now = await $.clock.now()
749 await setBoss($, b => withTurnEnd(turnEndBoss(b, e.reason, now), e))
750 // The point Claude Code compacts at can move with the model: read again, never waited for. The record of the button follows it.
751 void noteThreshold(gaugeIo($)).then(() => keepCoffeeRecord(coffeeDebugIo($), 'turn'))
752 // An edit Claude just made shows in the Settings tab, marked as waiting for the next session.
753 await refreshTab($, brief, true)
754 }
755 return next(e)
756 })
757
758 // ---- The quiet chat: filler rows are not drawn (hooks/quiet.ts says which); the full view shows everything ----
759 // Only while Clawd runs the chat: his rules are what make him report on what is hidden. Read at each row: a press applies at once.
760 const isQuiet = () => brief.isQuiet && brief.isOn
761 {
762 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
763 const p = e.props
764 // Most rows are the person's own or already in full: nothing is read for them. A notification may be a merged line (no task), a peer message may come with no sender.
765 const isOwn = !p.task && !p.from && p.origin.kind !== 'task-notification' && p.origin.kind !== 'peer-send-message'
766 if (!isQuiet() || p.isExpanded || isOwn) return next(e)
767 if (!isHandback({ isExpanded: p.isExpanded, originKind: p.origin.kind, text: p.text, task: p.task, from: p.from }, await read($, staff))) return next(e)
768 return blank(resolver($), e)
769 })
770 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => (isQuiet() && isNoUpdate(e.props.text) ? blank(resolver($), e) : next(e)))
771 // Small rows: the office's own bookkeeping calls are hidden or dimmed (hooks/quiet.ts says which). Errors always show.
772 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => (isQuiet() ? smallRow(resolver($), e, rowLook(e.props, await read($, staff)), () => next(e)) : next(e)))
773 on('ui.render', { component: 'ToolResult' }, async ($, e, next) => (isQuiet() ? smallRow(resolver($), e, rowLook(e.props, await read($, staff)), () => next(e)) : next(e)))
774 on('ui.render', { component: 'ToolProgress' }, async ($, e, next) => (isQuiet() && isBackgroundHint(e.props.kind) ? blank(resolver($), e) : next(e)))
775 }
776
777 // ---- The four office panes, one per host tab: drawn by panel.tsx from a snapshot of the state ----
778 for (const pane of PANES) {
779 on('ui.render', { component: 'Pane', requestId: pane.id }, async ($, e) => {
780 const ui = $.ui.resolve(e)
781 // Picked by `e.surface`: the resolved table does not answer an `in` check. Input is missing on mobile, Raster is the terminal's, Svg the others'.
782 const tools: PanelTools = {
783 Box: ui.Box, Text: ui.Text, Button: ui.Button, Link: ui.Link, Markdown: ui.Markdown,
784 Input: e.surface === 'mobile' ? undefined : $.ui.resolve(e).Input,
785 Raster: e.surface === 'terminal' ? $.ui.resolve(e).Raster : undefined,
786 Svg: e.surface === 'terminal' ? undefined : $.ui.resolve(e).Svg,
787 }
788 const layout = { columns: e.props.bodyColumns, minHeight: pinHeight(e.surface, e.props.placement, e.props.scroll.bodyRows) }
789 return renderPanel(tools, layout, await panelData($, brief), panelActions($, brief), pane.view)
790 })
791 }
792}
793hooks/left-io.ts 142 lines1// Left undone, the work (no `$`): what each source adds to the list, and the two buttons. register.tsx holds the list's
2// atom and the hooks and hands in what each call may do as `LeftIo`; the pure parts are in left-scan.ts, left-list.ts and left-check.ts.
3import type { ModelCompleteResult } from 'claude-code'
4import type { LeftItem } from '../types'
5import { fit } from './desk'
6import { CHECK_MAX_TOKENS, CHECK_MODEL, CHECK_TIMEOUT_MS, checkAsk, leftStart as resetCheck, parseUndone, takeCheck } from './left-check'
7import { cleanLeft, promptOf, withLeft } from './left-list'
8import type { FreshItem } from './left-list'
9import { isProjectCode, linesWritten } from './left-scan'
10import type { FileHit } from './left-scan'
11import { plainText } from './know'
12import { side } from './side-ask'
13import { inLine } from './state'
14
15// What register.tsx's hooks need besides the work below, in one import.
16export { leftAsked, leftToolUsed, leftTurnStart } from './left-check'
17export { FILE_TOOLS } from './left-scan'
18
19/** A session starts: the turn and the request being counted start over, and the stored list is read as a clean one. */
20export function leftStart(raw: unknown): LeftItem[] {
21 resetCheck()
22 return cleanLeft(raw)
23}
24
25/** What the list may do, each one a `$` call made in register.tsx. */
26export type LeftIo = {
27 folder: () => string
28 now: () => Promise<number>
29 /** The list as it stands when the write lands: the change is made on that, so changes made at the same moment all land. */
30 change: (fn: (list: LeftItem[]) => LeftItem[]) => Promise<LeftItem[]>
31 save: (folder: string, list: LeftItem[]) => Promise<unknown>
32 read: (path: string) => Promise<string>
33 complete: (ask: { model: string; system: string; prompt: string; maxTokens: number; timeoutMs: number }) => Promise<ModelCompleteResult>
34 /** Puts text after what is in the person's prompt box; never sends it. */
35 fillPrompt: (text: string) => Promise<unknown>
36 /** The name an agent is filed under. */
37 byOf: (agentId: string) => Promise<string>
38}
39
40export type LeftActions = { leftDo: (id: string) => unknown; leftClear: () => unknown }
41
42/** One change to the list, made on the list as it stands when its turn comes and saved under the folder. A project that changed meanwhile is not written to; a save that fails is let go (the list stays for the session, and nothing is shown). */
43function commit(io: LeftIo, folder: string, fn: (list: LeftItem[]) => LeftItem[]) {
44 return inLine(async () => {
45 if (io.folder() !== folder) return
46 const next = await io.change(fn)
47 if (folder) await io.save(folder, next).catch(() => undefined)
48 })
49}
50
51async function add(io: LeftIo, folder: string, fresh: readonly FreshItem[]) {
52 if (fresh.length === 0) return
53 const at = await io.now()
54 await commit(io, folder, list => withLeft(list, fresh, at))
55}
56
57/** The buttons: Do it now puts the item's sentence in the prompt box (and keeps the item); Clear empties the list. */
58export function leftActions(io: LeftIo): LeftActions {
59 return {
60 leftDo: async id => {
61 const item = (await io.change(list => list)).find(one => one.id === id)
62 if (item) await io.fillPrompt(promptOf(item))
63 },
64 leftClear: () => commit(io, io.folder(), () => []),
65 }
66}
67
68/**
69 * A specialist handed its report back. Nothing is read from an answer any more (phrase matching listed descriptions of the
70 * work as if they were unfinished work); this stays so register.tsx's call to it still holds, and does nothing.
71 */
72export function leftAnswer(_io: LeftIo, _e: { reason: string; answer: string }, _by: string): Promise<void> {
73 return Promise.resolve()
74}
75
76// ---- Source 1: unfinished-work lines written into code files ----
77
78/** A file tool's call as the hook hears it: the tool, who made it, and its input. */
79export type WriteCall = { tool: string; agentId?: string } & Record<string, unknown>
80
81const pathOf = (call: WriteCall) => (typeof call.file_path === 'string' && call.file_path !== '' ? call.file_path : undefined)
82
83/** The path from the project folder, when the file lies inside it and is a code file outside docs/ and node_modules/; otherwise nothing. */
84function codePath(path: string, folder: string): string | undefined {
85 const root = folder.replace(/[\\/]+$/, '')
86 const relative = root !== '' && path.startsWith(`${root}/`) ? fit(plainText(path.slice(root.length + 1)), 200) : undefined
87 return relative !== undefined && isProjectCode(relative) ? relative : undefined
88}
89
90/** The line a hit landed on: a Write knows it; an edit's is found by looking for the text in the file as it is now. */
91function lineOf(tool: string, hit: FileHit, now: string | undefined): number | undefined {
92 if (tool === 'Write') return hit.line
93 const at = now === undefined ? -1 : now.split(/\r?\n/).findIndex(line => line.includes(hit.text))
94 return at < 0 ? undefined : at + 1
95}
96
97async function fromFile(io: LeftIo, call: WriteCall, path: string, file: string, before: string) {
98 const hits = linesWritten(call.tool, call, before)
99 if (hits.length === 0) return
100 const [by, now] = [call.agentId === undefined ? 'Clawd' : await io.byOf(call.agentId), call.tool === 'Write' ? undefined : await io.read(path).catch(() => undefined)]
101 await add(io, io.folder(), hits.map((hit): FreshItem => {
102 const line = lineOf(call.tool, hit, now)
103 return { text: hit.text, source: 'file', by, file, ...(line === undefined ? {} : { line }) }
104 }))
105}
106
107/**
108 * Wraps one call to a file tool. Only a code file inside the project is looked at. A Write is read against the file as it was;
109 * once the call has gone through (a refusal or an error counts for nothing), the lines it wrote are looked at, not waited for.
110 * The tool's own answer is returned as it came.
111 */
112export async function leftWatch<R>(io: LeftIo, call: WriteCall, run: () => Promise<R>): Promise<R> {
113 const path = pathOf(call)
114 const file = path === undefined ? undefined : codePath(path, io.folder())
115 if (path === undefined || file === undefined) return run()
116 const before = call.tool === 'Write' ? await io.read(path).catch(() => '') : ''
117 const ran = await run()
118 const answer = (ran ?? {}) as { deny?: unknown; isError?: unknown }
119 if (answer.deny === undefined && !answer.isError) void fromFile(io, call, path, file, before).catch(() => undefined)
120 return ran
121}
122
123// ---- Source 2: the strict second check, and the end of Clawd's own turn ----
124
125/** The one question to the small model; what it lists joins the list. Whatever goes wrong, nothing is added. */
126async function runCheck(io: LeftIo, folder: string, job: { request: string; report: string }) {
127 const ask = checkAsk(job.request, job.report)
128 const reply = await io.complete({ model: CHECK_MODEL, system: ask.system, prompt: ask.prompt, maxTokens: CHECK_MAX_TOKENS, timeoutMs: CHECK_TIMEOUT_MS })
129 if (!reply.isAnswered) return
130 await add(io, folder, parseUndone(reply.text).map((text): FreshItem => ({ text, source: 'check', by: 'Clawd' })))
131}
132
133/**
134 * Clawd's own turn ended. When `isCheckOn` and the turn used five tools or more without handing work to a specialist, a check
135 * of his final report joins the line of background questions to the model. His answer is judged only by that check. Never throws.
136 */
137export function leftOwnTurn(io: LeftIo, e: { reason: string; answer: string }, isCheckOn: boolean): Promise<void> {
138 const [folder, job] = [io.folder(), takeCheck(e)]
139 if (isCheckOn && job) side.queue(() => runCheck(io, folder, job).catch(() => undefined))
140 return Promise.resolve()
141}
142hooks/desk.ts 132 lines1// What every specialist is told, who stays on the payroll, how Clawd sizes a hire, and the key choices a specialist reports.
2
3/** Appended to every subagent's brief: questions go into the report for Clawd, who asks the user only what needs the user. */
4export const BRIEF_NOTE =
5 '\n\n(Office note from Clawd HQ: if you reach a decision or question only the user can settle, do not stall. ' +
6 'Make your best call, carry on, and end your final report with one line per item: ' +
7 '`QUESTION: <question> | <option> / <option> | recommend: <option>`. ' +
8 'Do the work yourself: do not hire or start other agents or subagents. If the job needs more hands, say so in your report and Clawd will staff it. ' +
9 'Clawd, the chief of staff, reads these and asks the user only what needs the user. ' +
10 'For each key choice you made yourself that later work should follow (a library, a schema, an interface, a convention), add `DECIDED: <choice> — <why>`. ' +
11 'The user watches your progress live. As you work, start each step with one short sentence in everyday words that says what you are doing now, ' +
12 'for example "Step 2 of 4: checking that the tests pass." Use no tool names, file paths or jargon in that sentence.)\n' +
13 '(Progress: before other work, call the `mcp__clawd-hq__step` tool with your plan as `total` (3 to 8 steps) and `done: 0`; ' +
14 'then call it again after each step with `done` and a note of a few plain words.)'
15
16/** Agent-written text as one short line: whitespace collapsed, cut to `max` characters with an ellipsis. */
17export function oneLine(text: string, max: number): string {
18 // Counted in whole characters (code points), so a cut never lands inside an emoji.
19 const chars = Array.from(text.replace(/\s+/g, ' ').trim())
20 return chars.length > max ? `${chars.slice(0, max - 1).join('')}…` : chars.join('')
21}
22
23/** A specialist's reported choice is a note on its record, so it is kept to this, at a word and without a mark. */
24const CHOICE_CHARS = 600
25
26/** One line like `oneLine`, but cut at a word and without a mark: for text the pane wraps, where an ellipsis would only hide words. */
27export function fit(text: string, max: number): string {
28 const chars = Array.from(text.replace(/\s+/g, ' ').trim())
29 if (chars.length <= max) return chars.join('')
30 const cut = chars.slice(0, max).join('')
31 const space = cut.lastIndexOf(' ')
32 return (space > max / 2 ? cut.slice(0, space) : cut).trimEnd()
33}
34
35// ---- Payroll ----
36
37/** Stacks an agent type is only useful for, by the files that mark a project as that stack. */
38export const STACKS: Array<{ stack: string; agents: RegExp; marks: RegExp }> = [
39 { stack: 'Go', agents: /^go-/, marks: /^go\.mod$/ },
40 { stack: 'Rust', agents: /^rust-/, marks: /^Cargo\.toml$/ },
41 { stack: 'Python', agents: /^(python|django|fastapi|pytorch)-/, marks: /^(pyproject\.toml|requirements.*\.txt|setup\.py|Pipfile|manage\.py)$/ },
42 { stack: 'Java/Kotlin', agents: /^(java|kotlin)-/, marks: /^(pom\.xml|build\.gradle(\.kts)?|settings\.gradle(\.kts)?)$/ },
43 { stack: 'Dart/Flutter', agents: /^(dart|flutter)-/, marks: /^pubspec\.yaml$/ },
44 { stack: 'Swift', agents: /^swift-/, marks: /^(Package\.swift|.*\.xcodeproj)$/ },
45 { stack: '.NET', agents: /^(csharp|fsharp)-/, marks: /\.(csproj|fsproj|sln)$/ },
46 { stack: 'C++', agents: /^cpp-/, marks: /^CMakeLists\.txt$/ },
47 { stack: 'HarmonyOS', agents: /^harmonyos-/, marks: /^oh-package\.json5$/ },
48 { stack: 'TypeScript/React', agents: /^(typescript|react)-/, marks: /^(package\.json|tsconfig\.json)$/ },
49]
50
51/** Specialists for domains a software project rarely needs; the CEO can rehire any of them. */
52export const NICHE = /^(healthcare|homelab|network|mle|gan|opensource|seo|marketing)-|^(chief-of-staff|loop-operator|harness-optimizer|conversation-analyzer)$/
53
54const bare = (type: string) => type.replace(/^[^:]+:/, '')
55
56/** Which plugin agent types this project has no use for, given the file names found in it. */
57export function proposeLayoffs(types: string[], files: string[]): { laidOff: string[]; stacks: string[]; why: string[] } {
58 const present = STACKS.filter(s => files.some(f => s.marks.test(f)))
59 const absent = STACKS.filter(s => !present.includes(s))
60 const laidOff: string[] = []
61 const why = new Set<string>()
62 for (const type of types) {
63 if (!type.includes(':')) continue // built-in agents are never laid off
64 const b = bare(type)
65 const stack = absent.find(s => s.agents.test(b))
66 if (stack) { laidOff.push(type); why.add(stack.stack) } else if (NICHE.test(b)) { laidOff.push(type); why.add('niche domains') }
67 }
68 return { laidOff: laidOff.sort(), stacks: present.map(s => s.stack), why: [...why] }
69}
70
71/** The names at the top of the project and one level below (hidden folders and node_modules not opened): what marks its stack. `list` is the host's folder listing. */
72export async function projectFiles(cwd: string, list: (path: string) => Promise<ReadonlyArray<{ name: string; kind: string }>>): Promise<string[]> {
73 if (!cwd) return []
74 const names: string[] = []
75 try {
76 for (const one of await list(cwd)) {
77 names.push(one.name)
78 if (one.kind === 'dir' && !one.name.startsWith('.') && one.name !== 'node_modules') {
79 try { for (const sub of await list(`${cwd}/${one.name}`)) names.push(sub.name) } catch { /* unreadable folder */ }
80 }
81 }
82 } catch { /* no project folder */ }
83 return names
84}
85
86// ---- Staffing: Clawd picks each agent's model and effort ----
87
88export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const
89export type Effort = (typeof EFFORTS)[number]
90
91/** Added to the Agent tool's description, so Clawd sizes every hire to the job. */
92export const STAFFING_NOTE =
93 '\n\nClawd HQ staffing: you are Clawd, the chief of staff, and you size every hire to the job. ' +
94 'Set `model`: `haiku` for jobs with a clear spec that a check can prove: lookups, searches, counting; summarising a log or test output; running tests and reporting what failed; wording, comment and README edits; and small code edits where the brief names the file and the exact change and a test shows it worked, such as renaming text across files, moving or removing a line, or changing a string. ' +
95 'Tell haiku to do the job itself and not hand it on, and give it the file, the exact change and the exact check that means done. ' +
96 'Not `haiku`: unclear specs, judgment calls, design across several files, debugging when the cause is unknown, security. ' +
97 'A job that only reads and reports starts at `haiku` unless it needs judgment. ' +
98 '`sonnet` for routine implementation, tests and reviews; ' +
99 '`opus` for architecture, hard debugging, security and anything ambiguous. ' +
100 'Start `prompt` with one line `[effort: low|medium|high|xhigh|max]`: low for lookups, medium by default, high for design and debugging, ' +
101 'xhigh or max only for the hardest problems. The office removes that line before the agent reads its brief and applies the effort to every request it makes.'
102
103/**
104 * Added after the staffing note while Clawd runs the chat. The tool's own text can say to start agents only when the
105 * user asks; a person who runs this office has asked, once and for all.
106 */
107export const HANDOVER_NOTE =
108 '\n\nClawd HQ standing instruction: the user who set up this office wants work handed to agents without being asked each time. ' +
109 'This replaces any line above that says to start agents only when the user asks. ' +
110 'Hand over every job of more than two or three steps that can run without the user, and run it in the background so you stay free to talk. ' +
111 'Do a job yourself only when it takes one or two steps.'
112
113const EFFORT_TAG = /^\s*\[effort:\s*([a-z]+)\s*\]\s*\n?/i
114
115/** The `[effort: …]` line Clawd starts a brief with, and the brief without it. */
116export function parseEffort(prompt: string): { effort?: Effort; prompt: string } {
117 const m = prompt.match(EFFORT_TAG)
118 if (!m) return { prompt }
119 const level = m[1]!.toLowerCase() as Effort
120 return EFFORTS.includes(level) ? { effort: level, prompt: prompt.slice(m[0].length) } : { prompt }
121}
122
123// ---- Key choices a specialist reports ----
124
125const DECIDED = /^[ \t]*[-*]?[ \t]*DECIDED:[ \t]*(.+?)[ \t]*$/gim
126
127/** The DECIDED lines of a subagent's final report. */
128export function parseChoices(text: string): string[] {
129 return [...text.matchAll(DECIDED)].map(m => fit(m[1] ?? '', CHOICE_CHARS)).filter(Boolean)
130}
131
132hooks/resume-effort.ts 20 lines1// The effort level a resumed specialist works at: the new line if the follow-up has one, else the one it was hired with.
2import type { Employee } from '../types'
3import type { Effort } from './desk'
4
5/**
6 * `said` is the level on the follow-up's own [effort: …] line. Without it, the first of `ids` (the id the engine answered
7 * with, then the id that was resumed) that has a level wins: the in-memory one, else the one on the staff record.
8 */
9export function resumedEffort(
10 said: Effort | undefined, ids: ReadonlyArray<string | undefined>, rows: readonly Employee[], memory: ReadonlyMap<string, Effort>,
11): Effort | undefined {
12 if (said) return said
13 for (const id of ids) {
14 if (!id) continue
15 const level = memory.get(id) ?? rows.find(one => one.id === id)?.effort
16 if (level) return level
17 }
18 return undefined
19}
20hooks/pair-up.ts 98 lines1// Specialists Clawd hires together as a pair-up for one job: which of them share a card on the Office tab and in the finished list,
2// what that card is titled, and its one status line. Pure. A hire joins a pair-up through a `PAIR-UP: <goal>` first line in its brief.
3import type { Employee } from '../types'
4import { fit } from './desk'
5import { ago } from './office'
6import { atWork, doneLine, doneThisSession, isActive, tokensLabel } from './panel-model'
7
8/** DECIDED: members hired with the same goal within 10 minutes of the first one share a card; a longer gap makes a separate job. */
9export const PAIR_WINDOW_MS = 10 * 60_000
10
11/** A goal is kept to a size a card can wrap, cut at a word and with no mark. */
12const GOAL_CHARS = 160
13
14const PAIR_LINE = /^\s*(PAIR-UP|COUNCIL):[ \t]*(\S[^\r\n]*?)[ \t]*(?:\r?\n|$)/i
15
16/**
17 * The `PAIR-UP: <goal>` line Clawd starts a pair-up member's brief with (after its effort line is taken off), and the brief without it. An empty goal is no pair-up.
18 * A `COUNCIL: <question>` line in the same place is a council voice's: the question comes back as the goal, marked `isCouncil`.
19 */
20export function parsePairUp(prompt: string): { goal?: string; isCouncil?: true; prompt: string } {
21 const m = prompt.match(PAIR_LINE)
22 const goal = m ? fit(m[2] ?? '', GOAL_CHARS) : ''
23 if (!m || goal === '') return { prompt }
24 return { goal, ...(m[1]!.toUpperCase() === 'COUNCIL' ? { isCouncil: true as const } : {}), prompt: prompt.slice(m[0].length) }
25}
26
27/** Two or more specialists hired together for one goal, in the order they were hired. `isCouncil` marks a council: voices on one question, drawn as one card with its own picture. */
28export type PairGroup = { goal: string; members: Employee[]; isCouncil?: true }
29
30const sameGoal = (a: string, b: string) => a.trim().replace(/\s+/g, ' ').toLowerCase() === b.trim().replace(/\s+/g, ' ').toLowerCase()
31
32/** Every pair-up on the books: members with the same goal, hired within the window of the first of them. One alone is no pair-up. */
33export function pairGroups(staff: Employee[]): PairGroup[] {
34 const hires = staff.filter((e): e is Employee & { pair: NonNullable<Employee['pair']> } => e.pair !== undefined).sort((a, b) => a.pair.at - b.pair.at)
35 // A council and a pair-up never share a card, even when their words match.
36 const groups = hires.reduce<Array<{ goal: string; at: number; isCouncil: boolean; members: Employee[] }>>((all, one) => {
37 const isCouncil = one.pair.isCouncil === true
38 const open = all.find(g => g.isCouncil === isCouncil && sameGoal(g.goal, one.pair.goal) && one.pair.at - g.at <= PAIR_WINDOW_MS)
39 return open
40 ? all.map(g => (g === open ? { ...g, members: [...g.members, one] } : g))
41 : [...all, { goal: one.pair.goal, at: one.pair.at, isCouncil, members: [one] }]
42 }, [])
43 return groups.filter(g => g.members.length >= 2).map(({ goal, members, isCouncil }) => ({ goal, members, ...(isCouncil ? { isCouncil: true as const } : {}) }))
44}
45
46const groupOf = (groups: PairGroup[], id: string) => groups.find(g => g.members.some(m => m.id === id))
47
48/** "A & B", and "A, B & C" for three or more. */
49export function pairTitle(names: string[]): string {
50 return names.length < 2 ? names.join('') : `${names.slice(0, -1).join(', ')} & ${names[names.length - 1]}`
51}
52
53export type PairState = 'working' | 'failed' | 'lost' | 'stopped' | 'done'
54
55/** Working while any member works; then failed if one failed, lost contact if one did, stopped if one was stopped on purpose; otherwise done. */
56export function pairState(members: Employee[]): PairState {
57 if (members.some(isActive)) return 'working'
58 return (['failed', 'lost', 'stopped'] as const).find(mood => members.some(m => m.mood === mood)) ?? 'done'
59}
60
61/** The group's one status line: the state, how long since the first member started (or how long the job took), and everyone's tokens. */
62export function pairLine(members: Employee[], now: number): { state: PairState; text: string } {
63 const state = pairState(members)
64 const start = Math.min(...members.map(m => m.startedAt))
65 const span = ago(Math.max(...members.map(m => m.endedAt ?? now)) - start)
66 const sum = members.reduce((n, m) => n + (m.tokens ?? 0), 0)
67 const tokens = sum > 0 ? ` · ${tokensLabel(sum)} tokens` : ''
68 if (state === 'working') return { state, text: `Working · ${ago(now - start)}${tokens}` }
69 if (state === 'lost') return { state, text: doneLine(members.find(m => m.mood === 'lost')!, now).took }
70 if (state === 'done') return { state, text: `Done · took ${span}${tokens}` }
71 return { state, text: `${state === 'failed' ? 'Failed' : 'Stopped'} after ${span}` }
72}
73
74/** One card on a tab: a specialist alone, or a pair-up. */
75export type Slot = { kind: 'one'; one: Employee } | { kind: 'pair'; group: PairGroup }
76
77/** The Office tab's floor: each specialist at work gets a card, but a pair-up gets one, at the place of its first member at work, with all its members. */
78export function floorSlots(staff: Employee[]): Slot[] {
79 const groups = pairGroups(staff)
80 return atWork(staff).flatMap((one): Slot[] => {
81 const group = groupOf(groups, one.id)
82 if (group === undefined) return [{ kind: 'one', one }]
83 return group.members.find(isActive) === one ? [{ kind: 'pair', group }] : []
84 })
85}
86
87const slotTime = (s: Slot) => (s.kind === 'one' ? s.one.endedAt ?? 0 : Math.max(...s.group.members.map(m => m.endedAt ?? 0)))
88
89/** The finished list, newest first: a pair-up is one card once none of its members works; while one does, its finished members stay on the floor's card. */
90export function finishedSlots(staff: Employee[], since: number): Slot[] {
91 const groups = pairGroups(staff)
92 const singles = doneThisSession(staff, since).filter(one => groupOf(groups, one.id) === undefined).map((one): Slot => ({ kind: 'one', one }))
93 const over = groups
94 .filter(g => !g.members.some(isActive) && g.members.some(m => (m.endedAt ?? -1) >= since))
95 .map((group): Slot => ({ kind: 'pair', group }))
96 return [...singles, ...over].sort((a, b) => slotTime(b) - slotTime(a))
97}
98hooks/artifacts.ts 218 lines1// The Artifact Desk: the pages on claude.ai that Claude published or opened with the Artifact tool in this project.
2// Pure: which calls count, which link and title they leave, and how the list is kept and shown. register.tsx keeps the list.
3import type { Artifact } from '../types'
4import { fit } from './desk'
5import { inLine } from './state'
6
7/** The newest this many artifacts are kept per project. */
8export const ARTIFACT_KEEP = 50
9/** The Office tab draws the newest this many; the rest are counted. */
10export const ARTIFACT_SHOWN = 6
11/** A title is cut at a word to this many characters. */
12export const TITLE_CHARS = 80
13/** The title of a page that came with none, and has none recorded. */
14const FALLBACK_TITLE = 'Artifact'
15
16// The only two shapes of a link that is ever kept or drawn: the page's id, or a uuid under /code/.
17const LINK = /^https:\/\/claude\.ai\/(?:artifact\/[A-Za-z0-9_-]{1,64}|code\/artifact\/[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})$/
18// A claude.ai address inside a text: not glued to a word or to another address; trailing punctuation is peeled off after.
19const LINK_IN_TEXT = /(?<![\w/.@:=?&%#+-])https:\/\/claude\.ai\/\S+/g
20const TRAILING = /[)\]}>"'`.,;:!?*_]+$/
21// Control characters go; the few that separate words become a space first. The soft hyphen, the direction marks, the zero-width characters and the tag characters go too: they can disguise or hide text in a title.
22const SPACING = /[\t\n\r\v\f]+/g
23const INVISIBLE = /[\u0000-\u001f\u007f-\u009f----\u{e0000}-\u{e007f}]/gu
24/** Only these actions leave a page in the list; a delete takes one out. Every other action is ignored. */
25const KEEPS = new Set(['publish', 'open'])
26
27export function isArtifactLink(url: unknown): url is string {
28 return typeof url === 'string' && LINK.test(url)
29}
30
31/** Untrusted text as a title: one line, no control characters, cut at a word; nothing when nothing is left. */
32function tidy(text: unknown): string | undefined {
33 if (typeof text !== 'string') return undefined
34 return fit(text.replace(SPACING, ' ').replace(INVISIBLE, ''), TITLE_CHARS) || undefined
35}
36
37/** What the tool's answer says, as text to look through: what the model read, a plain result, and the text fields of a record. */
38function textsOf(ran: ArtifactAnswer): string[] {
39 const { text, result } = ran
40 const fields = result !== null && typeof result === 'object' ? Object.values(result) : [result]
41 return [text, ...fields].filter((t): t is string => typeof t === 'string')
42}
43
44/** The first link in a text that is exactly one of the two shapes; any other address in it is stepped over. */
45function firstLink(texts: string[]): string | undefined {
46 for (const text of texts) {
47 for (const found of text.matchAll(LINK_IN_TEXT)) {
48 const url = found[0].replace(TRAILING, '')
49 if (isArtifactLink(url)) return url
50 }
51 }
52 return undefined
53}
54
55function titleFromAnswer(ran: ArtifactAnswer): string | undefined {
56 const { result, text } = ran
57 const named = result !== null && typeof result === 'object' ? tidy((result as { title?: unknown }).title) : undefined
58 return named ?? tidy(typeof text === 'string' ? /^\s*title:[ \t]*(.+)$/im.exec(text)?.[1] : undefined)
59}
60
61function titleFromFile(path: unknown): string | undefined {
62 return typeof path === 'string' ? tidy(path.split(/[\\/]/).filter(Boolean).pop()) : undefined
63}
64
65/** The Artifact tool's answer, as `tool.call` hands it back. */
66export type ArtifactAnswer = { result?: unknown; text?: unknown; isError?: unknown; deny?: unknown }
67
68/** What one call to the Artifact tool does to the list: keep this page (with the title it came with, if any) or take it out. */
69export type ArtifactCall = { link: string; title: string | undefined; isDelete: boolean }
70
71/**
72 * The call's effect on the list, or nothing when it has none. Only a publish (no action, or "publish"), an open and a
73 * delete count; a call that failed counts for nothing. The link is the input's `url`, else the first one in the answer.
74 * The input's `type_url` is the page's template, never the page.
75 */
76export function artifactCall(input: Record<string, unknown>, ran: ArtifactAnswer | undefined): ArtifactCall | undefined {
77 if (!ran || ran.isError || ran.deny) return undefined
78 const action = input.action === undefined ? 'publish' : input.action
79 const isDelete = action === 'delete'
80 if (!isDelete && !(typeof action === 'string' && KEEPS.has(action))) return undefined
81 // A url the input names that is not ours is not stepped over for one in the answer: the call is about that other page.
82 const named = typeof input.url === 'string' && input.url !== ''
83 const link = named ? (isArtifactLink(input.url) ? input.url : undefined) : firstLink(textsOf(ran))
84 if (link === undefined) return undefined
85 return { link, title: tidy(input.title) ?? titleFromAnswer(ran) ?? titleFromFile(input.file_path), isDelete }
86}
87
88/** The page at the top with the time it was last published or opened. A title that is not known keeps the recorded one. */
89export function withArtifact(list: Artifact[], url: string, title: string | undefined, at: number): Artifact[] {
90 const old = list.find(a => a.url === url)
91 const entry: Artifact = { url, title: title ?? old?.title ?? FALLBACK_TITLE, at }
92 return [entry, ...list.filter(a => a.url !== url)].slice(0, ARTIFACT_KEEP)
93}
94
95export function withoutArtifact(list: Artifact[], url: string): Artifact[] {
96 return list.some(a => a.url === url) ? list.filter(a => a.url !== url) : list
97}
98
99/** The read-only call that lists every page the person can see, as many as the tool will give at once. */
100export const LIST_LIMIT = 200
101export const LIST_INPUT = { action: 'list', scope: 'all', limit: LIST_LIMIT } as const
102
103/** Every real link in a list answer, once each. Nothing when the answer failed, was refused, names no page, or has as many as the limit (it may be cut short). */
104export function listedLinks(ran: ArtifactAnswer | undefined, limit: number): string[] | undefined {
105 if (!ran || ran.isError || ran.deny) return undefined
106 const found = new Set<string>()
107 for (const text of textsOf(ran)) {
108 for (const one of text.matchAll(LINK_IN_TEXT)) {
109 const url = one[0].replace(TRAILING, '')
110 if (isArtifactLink(url)) found.add(url)
111 }
112 }
113 return found.size === 0 || found.size >= limit ? undefined : [...found]
114}
115
116/** What the sweep may do: ask whether the call would run unasked, and make the call. */
117export type ListIo = {
118 check: (input: { tool: 'Artifact'; input: typeof LIST_INPUT }) => Promise<{ decision?: unknown }>
119 list: (input: typeof LIST_INPUT) => Promise<ArtifactAnswer>
120}
121
122/** The links the Artifact tool lists now, but only if the engine says the call needs no question to the person. Any other verdict, or any failure, is nothing. */
123export async function listedPages(io: ListIo, limit: number): Promise<string[] | undefined> {
124 try {
125 if ((await io.check({ tool: 'Artifact', input: LIST_INPUT })).decision !== 'allow') return undefined
126 return listedLinks(await io.list(LIST_INPUT), limit)
127 } catch {
128 return undefined
129 }
130}
131
132/** The list without the pages the answer left out. A page published or opened since the call began is newer than the answer and stays. */
133export function withoutGone(list: Artifact[], links: string[], startedAt: number): Artifact[] {
134 const there = new Set(links)
135 const kept = list.filter(a => there.has(a.url) || a.at > startedAt)
136 return kept.length === list.length ? list : kept
137}
138
139/** What the desk may do. The folder is read when the work lands, since the session can move to another project meanwhile. */
140export type ArtifactIo = ListIo & {
141 folder: () => string
142 now: () => Promise<number>
143 /** The list as it stands when the write lands: the change is made on that, so calls made at the same moment all land. Queued. */
144 change: (fn: (list: Artifact[]) => Artifact[]) => Promise<Artifact[]>
145 save: (folder: string, list: Artifact[]) => Promise<unknown>
146 /** Shows the text once a session. */
147 warnOnce: (text: string) => void
148}
149
150/** Notes what a call to the Artifact tool did. */
151export async function keepArtifact(io: ArtifactIo, folder: string, input: Record<string, unknown>, ran: ArtifactAnswer) {
152 const call = artifactCall(input, ran)
153 if (!call) return
154 const at = await io.now()
155 await commit(io, folder, list => (call.isDelete ? withoutArtifact(list, call.link) : withArtifact(list, call.link, call.title, at)))
156}
157
158/** The Hide button: the page leaves this project's desk and the saved list. Publishing or opening it again brings it back. The page on claude.ai is not touched. */
159export function hideArtifact(io: ArtifactIo, folder: string, url: string) {
160 return commit(io, folder, list => withoutArtifact(list, url))
161}
162
163/** One change to the desk's list, made on the list as it stands when its turn comes, then saved under the folder. */
164function commit(io: ArtifactIo, folder: string, fn: (list: Artifact[]) => Artifact[]) {
165 return inLine(async () => {
166 // The session moved to another project while the call ran: this page is not that project's, so it is dropped.
167 if (io.folder() !== folder) return
168 const next = await io.change(fn)
169 if (!folder) return
170 try {
171 await io.save(folder, next)
172 } catch {
173 // The change stays in this session's list; the person hears of it once.
174 io.warnOnce('Could not save the artifact list. It is kept for this session only.')
175 }
176 })
177}
178
179/** Once per session start: pages gone from claude.ai leave the list. Only a list call the engine allows unasked is made; anything else removes nothing. */
180export async function sweepArtifacts(io: ArtifactIo, folder: string) {
181 const startedAt = await io.now()
182 const links = await listedPages(io, LIST_LIMIT)
183 if (!links || !folder) return
184 await inLine(async () => {
185 if (io.folder() !== folder) return
186 await io.save(folder, await io.change(list => withoutGone(list, links, startedAt))).catch(() => undefined)
187 })
188}
189
190/** A list read back from the store, which anyone can edit: only well-formed entries with a real link survive, once each. */
191export function cleanArtifacts(raw: unknown): Artifact[] {
192 if (!Array.isArray(raw)) return []
193 const seen = new Set<string>()
194 const kept: Artifact[] = []
195 for (const one of raw as Array<Partial<Artifact> | null>) {
196 if (one === null || typeof one !== 'object' || !isArtifactLink(one.url) || seen.has(one.url)) continue
197 if (typeof one.title !== 'string' || typeof one.at !== 'number' || !Number.isFinite(one.at)) continue
198 seen.add(one.url)
199 kept.push({ url: one.url, title: tidy(one.title) ?? FALLBACK_TITLE, at: one.at })
200 }
201 return kept.slice(0, ARTIFACT_KEEP)
202}
203
204/** The newest few to draw (real links only), and how many older ones there are. */
205export function artifactsShown(list: Artifact[]): { rows: Artifact[]; older: number } {
206 const real = list.filter(a => isArtifactLink(a.url))
207 return { rows: real.slice(0, ARTIFACT_SHOWN), older: Math.max(0, real.length - ARTIFACT_SHOWN) }
208}
209
210/** How long ago, in plain steps: under a minute, minutes, hours, then days from two days on. */
211export function since(ms: number): string {
212 const minutes = Math.floor(Math.max(0, ms) / 60_000)
213 if (minutes < 1) return 'just now'
214 if (minutes < 60) return `${minutes}m ago`
215 const hours = Math.floor(minutes / 60)
216 return hours < 48 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`
217}
218hooks/activity.ts 98 lines1// What a specialist is doing right now: one plain sentence built from its last tool call, and its own words from its last step.
2// Pure: no model is asked. A Bash command's own text is never used (it can hold secrets); only the description its caller wrote for it.
3import { fit } from './desk'
4
5/** A tool sentence is one line this long at most; the pane wraps it, so only a runaway one is cut (at a word, with no mark). */
6export const MAX_SENTENCE = 200
7const QUOTED_CHARS = 40
8/** What a specialist says: up to this many sentences, and this many characters in all. */
9const SAID_SENTENCES = 3
10const SAID_CHARS = 280
11
12/** Between a model step and its tool call: the specialist is working something out. */
13export const THINKING = 'Thinking'
14/** Before anything has been seen of the run. */
15export const READING_BRIEF = 'Reading the brief'
16
17type Input = Record<string, unknown>
18
19const text = (input: Input, key: string): string | undefined => {
20 const value = input[key]
21 return typeof value === 'string' && value.trim() !== '' ? value : undefined
22}
23
24const fileName = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path
25const quoted = (value: string) => `“${fit(value, QUOTED_CHARS)}”`
26/** "ecc:planner" and "acme:(o_o) planner" both read "planner". */
27const bareName = (name: string) => name.replace(/^[^:]+:/, '').replace(/^\([^()]*\)\s*/, '')
28const withArticle = (word: string) => `${/^[aeiou]/i.test(word) ? 'an' : 'a'} ${word}`
29
30const onFile = (verb: string, input: Input) => {
31 const path = text(input, 'file_path') ?? text(input, 'notebook_path')
32 return `${verb} ${path ? fileName(path) : 'a file'}`
33}
34
35const onSearch = (what: string, query: string | undefined) => (query ? `${what} for ${quoted(query)}` : what)
36
37const onPage = (input: Input) => {
38 const host = /^https?:\/\/([^/?#:\s]+)/i.exec(text(input, 'url') ?? '')?.[1]
39 return `Reading ${host ?? 'a web page'}`
40}
41
42function onMcp(tool: string) {
43 const [server = '', ...name] = tool.slice('mcp__'.length).split('__')
44 const words = name.join(' ').replace(/_/g, ' ').trim()
45 return words ? `Using ${server}: ${words}` : `Using ${server}`
46}
47
48function describe(tool: string, input: Input): string {
49 switch (tool) {
50 case 'Read': return onFile('Reading', input)
51 case 'Edit': case 'MultiEdit': case 'NotebookEdit': return onFile('Editing', input)
52 case 'Write': return onFile('Writing', input)
53 case 'Bash': return text(input, 'description') ?? 'Running a command'
54 case 'Grep': case 'Glob': return onSearch('Searching the code', text(input, 'pattern'))
55 case 'WebSearch': return onSearch('Searching the web', text(input, 'query'))
56 case 'WebFetch': return onPage(input)
57 case 'Agent': case 'Task': return `Briefing ${withArticle(bareName(text(input, 'subagent_type') ?? 'agent'))}`
58 case 'Skill': { const skill = text(input, 'skill'); return skill ? `Using the ${bareName(skill)} skill` : 'Using a skill' }
59 case 'SendMessage': return 'Sending a message'
60 default: return tool.startsWith('mcp__') ? onMcp(tool) : `Using ${tool}`
61 }
62}
63
64/** One line saying what this tool call does. */
65export const sentenceOf = (tool: string, input: Input): string => fit(describe(tool, input), MAX_SENTENCE)
66
67const SENTENCE_END = /(?<=[.!?])\s+(?=[A-Z“"'(\d])/
68const LIST_OR_TABLE = /^\s*([-*+]\s|\d+[.)]\s|\|)/
69const HEADING = /^\s*#{1,6}\s/
70const FENCED = /(^|\n)[ \t]*```[\s\S]*?(\n[ \t]*```|$)/g
71
72/**
73 * What a specialist said in its last step, as plain words: the first one to three sentences of its first paragraph.
74 * Code, links and marks are dropped; a heading is its own block; a list or a table is not a sentence, so the words stop where one starts.
75 */
76export function narrationOf(answer: string): string | undefined {
77 const paragraph = answer
78 .replace(FENCED, '\n\n')
79 .split(/\n\s*\n/)
80 .map(p => p.trim())
81 .find(p => p !== '')
82 if (paragraph === undefined) return undefined
83 const lines = paragraph.split('\n').filter(l => !HEADING.test(l))
84 const end = lines.findIndex(l => LIST_OR_TABLE.test(l))
85 const plain = (end === -1 ? lines : lines.slice(0, end)).join(' ')
86 .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
87 .replace(/`([^`]*)`/g, '$1')
88 .replace(/\*\*([^*]+)\*\*/g, '$1')
89 .replace(/~~([^~]+)~~/g, '$1')
90 const kept: string[] = []
91 for (const sentence of plain.split(SENTENCE_END).map(s => s.replace(/\s+/g, ' ').trim()).filter(Boolean)) {
92 const next = [...kept, sentence].join(' ')
93 if (kept.length >= SAID_SENTENCES || (kept.length > 0 && next.length > SAID_CHARS)) break
94 kept.push(sentence)
95 }
96 return kept.length === 0 ? undefined : fit(kept.join(' '), SAID_CHARS)
97}
98hooks/constants.ts 16 lines1// The office's fixed numbers and tool names. register.tsx holds the hooks that use them.
2export const FRAME_MS = 400
3export const CHEER_TICKS = 5
4/** A given name is a word or two; anything longer is cut. */
5export const NAME_CHARS = 40
6/** What an agent type is for, kept at a word with no mark: long enough that the People row's first sentence is seldom cut. */
7export const BLURB_CHARS = 600
8// Agent-written text is cut to one line where it is stored.
9export const DESCRIPTION_CHARS = 160
10export const MAX_BLURBS = 120
11export const DEMO_TOOL = 'mcp__clawd-hq__demo'
12export const RULE_TOOL = 'mcp__clawd-hq__offer_rule'
13export const STEP_TOOL = 'mcp__clawd-hq__step'
14export const TEAM_TOOL = 'mcp__clawd-hq__team_pick'
15export const FIND_TOOL = 'mcp__clawd-hq__find_helpers'
16export const CONTRACTOR_TOOL = 'mcp__clawd-hq__hire_contractor'hooks/own-tools.ts 33 lines1// The tools the office registers for the model (the tour, the offer of a lasting rule, the step report, the search for helpers, the hire of a contractor) and what a call of each is answered with.
2// No `$`: what each does comes in as a closure.
3import { CONTRACTOR_TOOL, DEMO_TOOL, FIND_TOOL, RULE_TOOL, STEP_TOOL } from './constants'
4import { BRAND } from './office'
5
6/** What the office's own tools may do. */
7export type OwnToolIo = {
8 /** Opens the office and plays the tour. */
9 readonly tour: () => Promise<void>
10 /** Clawd's offer of a lasting rule for CLAUDE.md (hooks/rule-io.ts); a specialist's call is refused. */
11 readonly offerRule: (agentId: string | undefined, input: Record<string, unknown>) => Promise<{ readonly result: string } | { readonly deny: string }>
12 /** A specialist's report of its steps; only one at work here counts. */
13 readonly step: (agentId: string | undefined, input: Record<string, unknown>) => Promise<{ readonly result: string } | { readonly deny: string }>
14 /** Clawd's search of everything installed for a job (hooks/find-helpers.ts); a specialist's call is refused. */
15 readonly find: (agentId: string | undefined, input: Record<string, unknown>) => Promise<{ readonly result: string } | { readonly deny: string }>
16 /** Clawd's hire of an off-team skill for one job (hooks/contractor.ts); a specialist's call is refused. */
17 readonly contractor: (agentId: string | undefined, input: Record<string, unknown>) => Promise<{ readonly result: string } | { readonly deny: string }>
18}
19
20const TOUR_TEXT = `The ${BRAND} tour is playing in the side panel for about a minute. If the panel is not visible, the user can type /office.`
21
22/** The answer to a call of one of the office's own tools, or `undefined` when the tool is not one of them. */
23export async function ownToolAnswer(io: OwnToolIo, tool: string, agentId: string | undefined, input: Record<string, unknown>): Promise<{ readonly result: string } | { readonly deny: string } | undefined> {
24 if (tool === DEMO_TOOL) {
25 await io.tour()
26 return { result: TOUR_TEXT }
27 }
28 if (tool === RULE_TOOL) return io.offerRule(agentId, input)
29 if (tool === FIND_TOOL) return io.find(agentId, input)
30 if (tool === CONTRACTOR_TOOL) return io.contractor(agentId, input)
31 return tool === STEP_TOOL ? io.step(agentId, input) : undefined
32}
33hooks/quiet-rows.tsx 26 lines1// The quiet chat's two ways to draw a row: as nothing, or as the look in hooks/quiet.ts says. No `$`: the drawing table comes in as `resolve`.
2import type { EngineInterface, RenderElement } from 'claude-code'
3import { dimLine } from './quiet'
4import type { rowLook, ToolRow } from './quiet'
5
6/** `$.ui.resolve`, handed in as a closure: picks the drawing surface's own elements for a render event. */
7export type Resolve = EngineInterface['ui']['resolve']
8type RenderEvent = Parameters<Resolve>[0]
9
10/** A row drawn as nothing. */
11export function blank(resolve: Resolve, e: RenderEvent) {
12 const { Text } = resolve(e)
13 return <Text>{''}</Text>
14}
15
16/**
17 * A small row as its look says: drawn as it is, as nothing, or dimmed. A dimmed row is a short line of its own words:
18 * the engine's drawing (`draw()`) is a node no Text may hold, so wrapping it in a dim Text is refused.
19 */
20export async function smallRow(resolve: Resolve, e: RenderEvent & { props: ToolRow }, look: ReturnType<typeof rowLook>, draw: () => Promise<RenderElement>): Promise<RenderElement> {
21 if (look === 'show') return draw()
22 if (look === 'hide') return blank(resolve, e)
23 const { Text } = resolve(e)
24 return <Text dimColor>{dimLine(e.props)}</Text>
25}
26hooks/scout-box.ts 105 lines1// The mailbox between the scout and the setup step that started it: the files it opens, the picks it sends, and the wait for them.
2// Plain state, no `$`: the timer comes in as a closure. One scout at a time; ids stay known for a while after it is done,
3// so a scout that carries on after its time is up is still refused rather than mistaken for a stranger.
4import type { ScoutCheck, ScoutReport } from './onboard-types'
5
6/** How many scout ids are remembered. */
7const KEEP_IDS = 20
8const MAX_READS = 400
9const READ_CHARS = 500
10/** The scout may send picks this many times; a try the check refuses is sent back to it with the reason. */
11export const MAX_TRIES = 3
12const ENOUGH = 'That was the third try that could not be used, so the scout is finished.'
13const CLOSED = 'The scout has finished its work.'
14
15type Slot = { readonly reads: readonly string[]; readonly tries: number; readonly isClosed: boolean; readonly report?: ScoutReport }
16type Timer = { readonly cancel: () => void }
17export type After = (ms: number, fn: () => void) => Timer
18/** What sending picks does: they are taken, or sent back with the reason. */
19export type Delivery = { readonly isTaken: true } | { readonly problem: string }
20
21export type ScoutBox = {
22 /** Judges the picks of the scout about to start. */
23 readonly begin: (check: ScoutCheck) => void
24 /** Notes an id as a scout. */
25 readonly mark: (id: string) => void
26 readonly isScout: (id: string) => boolean
27 /** Whether the scout is done: it sent its picks, ran out of time, or ended. Everything it calls after that is refused. */
28 readonly isClosed: (id: string) => boolean
29 readonly noteRead: (id: string, path: string) => void
30 readonly deliver: (id: string, picks: unknown) => Delivery
31 /** The scout ended; if it sent no picks, the wait is over. */
32 readonly finish: (id: string) => void
33 /** The picks, or `undefined` when time ran out or the scout ended without any. */
34 readonly wait: (id: string, ms: number, after: After) => Promise<ScoutReport | undefined>
35}
36
37/** The scouts known so far, newest last, replaced rather than changed. */
38function createSlots() {
39 let slots: ReadonlyMap<string, Slot> = new Map()
40 return {
41 get: (id: string) => slots.get(id),
42 mark: (id: string) => {
43 if (!slots.has(id)) slots = new Map([...[...slots].slice(1 - KEEP_IDS), [id, { reads: [], tries: 0, isClosed: false }]])
44 },
45 patch: (id: string, fn: (s: Slot) => Slot) => {
46 const slot = slots.get(id)
47 if (slot) slots = new Map(slots).set(id, fn(slot))
48 },
49 }
50}
51
52/** Who is waiting for a scout's picks. Whoever settles it, the timer goes. */
53function createWaiters() {
54 const waiting = new Map<string, (report: ScoutReport | undefined) => void>()
55 return {
56 settle: (id: string, report: ScoutReport | undefined) => {
57 const done = waiting.get(id)
58 waiting.delete(id)
59 done?.(report)
60 },
61 hold: (id: string, ms: number, after: After, onTimeout: () => void) => new Promise<ScoutReport | undefined>(resolve => {
62 let timer: Timer | undefined
63 waiting.set(id, report => { timer?.cancel(); resolve(report) })
64 timer = after(ms, onTimeout)
65 }),
66 }
67}
68
69export function createScoutBox(): ScoutBox {
70 const slots = createSlots()
71 const waiters = createWaiters()
72 let check: ScoutCheck = () => undefined
73 const close = (id: string, report?: ScoutReport) => {
74 slots.patch(id, s => ({ ...s, isClosed: true, ...(report ? { report } : {}) }))
75 waiters.settle(id, report)
76 }
77 return {
78 begin: next => { check = next },
79 mark: slots.mark,
80 isScout: id => slots.get(id) !== undefined,
81 isClosed: id => slots.get(id)?.isClosed ?? false,
82 noteRead: (id, path) => slots.patch(id, s => (s.reads.length >= MAX_READS || path.length > READ_CHARS ? s : { ...s, reads: [...s.reads, path] })),
83 deliver: (id, picks) => {
84 const slot = slots.get(id)
85 if (!slot || slot.isClosed) return { problem: CLOSED }
86 const problem = check(picks, slot.reads)
87 if (problem === undefined) {
88 close(id, { picks, reads: slot.reads })
89 return { isTaken: true }
90 }
91 if (slot.tries + 1 >= MAX_TRIES) {
92 close(id)
93 return { problem: ENOUGH }
94 }
95 slots.patch(id, s => ({ ...s, tries: s.tries + 1 }))
96 return { problem }
97 },
98 finish: id => { if (slots.get(id)?.isClosed === false) close(id) },
99 wait: (id, ms, after) => {
100 const slot = slots.get(id)
101 return !slot || slot.isClosed ? Promise.resolve(slot?.report) : waiters.hold(id, ms, after, () => close(id))
102 },
103 }
104}
105hooks/scout-run.ts 91 lines1// Running the scout: starting it, waiting for its picks, stopping it when it is given up on, and answering each call it makes.
2// No `$`: the host's calls come in as closures.
3import { TEAM_TOOL } from './constants'
4import type { ScoutCheck, ScoutReport } from './onboard-types'
5import type { After, ScoutBox } from './scout-box'
6import { guardScout } from './scout-guard'
7import type { RealIo } from './scout-guard'
8import { SCOUT_TYPE } from './scout-spec'
9
10/** What starting a scout asks for. */
11export type ScoutStart = { readonly subagentType: string; readonly description: string; readonly prompt: string }
12/** The host's calls a scout needs: start it, list the agents, stop one, and a timer. */
13export type ScoutHost = {
14 readonly spawn: (start: ScoutStart) => Promise<{ readonly agentId?: string; readonly deny?: string }>
15 readonly list: () => Promise<readonly { readonly id: string; readonly type: string }[]>
16 readonly stop: (id: string) => Promise<unknown>
17 readonly after: After
18}
19
20const CLOSED_DENY = 'Refused by Clawd HQ: the scout\'s work is finished.'
21/** What stands in for the guard when the hook holding it fails: the scout's call is refused, never let through unchecked. */
22export const SCOUT_CRASH_DENY = 'Refused by Clawd HQ: that call could not be checked.'
23/** The agent type a start asks for, in the event's spelling or the Agent tool's own (a start the plugin makes itself can reach a hook as either). */
24export const spawnTypeOf = (e: object): unknown => (e as { subagentType?: unknown }).subagentType ?? (e as { subagent_type?: unknown }).subagent_type
25/** What the pick tool says to anyone but the scout. */
26export const NOT_SCOUT_DENY = 'Only the Clawd HQ scout uses this tool, and the plugin starts it itself during setup.'
27const TAKEN = 'Your team is noted. You are done: reply with the single word "done" and stop.'
28
29/** The started scout's id: the one the start gave, else the newest scout the engine lists that is not known yet. `undefined` when it would not start. */
30async function startedId(box: ScoutBox, host: ScoutHost, prompt: string): Promise<string | undefined> {
31 const started = await host.spawn({ subagentType: SCOUT_TYPE, description: 'Look around the project', prompt }).catch(() => undefined)
32 if (started === undefined || started.deny !== undefined) return undefined
33 if (started.agentId !== undefined) return started.agentId
34 const listed = await host.list().catch(() => [])
35 return listed.find(a => a.type === SCOUT_TYPE && !box.isScout(a.id))?.id
36}
37
38/**
39 * Starts the scout and waits for its picks; `undefined` when it could not start, ran out of time, or ended with nothing the check accepted.
40 * A scout given up on is stopped, so it does not run on and spend; a stop that fails changes nothing.
41 */
42export async function runScout(box: ScoutBox, host: ScoutHost, brief: string, check: ScoutCheck, timeoutMs: number): Promise<ScoutReport | undefined> {
43 box.begin(check)
44 const id = await startedId(box, host, brief)
45 if (id === undefined) return undefined
46 box.mark(id)
47 const report = await box.wait(id, timeoutMs, host.after)
48 if (report === undefined) await host.stop(id).catch(() => undefined)
49 return report
50}
51
52/** What a call of the scout's is answered with: refused, answered here (its picks), or run with these fields set over its own. */
53export type ScoutAnswer = { readonly deny: string } | { readonly result: string } | { readonly run: Readonly<Record<string, unknown>> }
54
55/** The scout's call, judged by the guard and the mailbox. Only calls from a scout come here. */
56export async function scoutCall(box: ScoutBox, io: RealIo, folder: string, id: string, tool: string, input: Record<string, unknown>): Promise<ScoutAnswer> {
57 if (box.isClosed(id)) return { deny: CLOSED_DENY }
58 if (tool === TEAM_TOOL) {
59 const sent = box.deliver(id, input)
60 return 'problem' in sent ? { deny: sent.problem } : { result: TAKEN }
61 }
62 const verdict = await guardScout(io, tool, input, folder)
63 if ('deny' in verdict) return verdict
64 if (verdict.read !== undefined) box.noteRead(id, verdict.read)
65 return { run: verdict.run }
66}
67
68/** What the route asks the host: where a path really lands, whether an id is a hire on the books, and what type the engine lists an id as. */
69export type RouteIo = RealIo & {
70 readonly isHired: (id: string) => Promise<boolean>
71 readonly typeOf: (id: string) => Promise<string | undefined>
72}
73
74/** Whether an id is the scout: marked, or, when it is no hire on the books, listed by the engine under the scout's type (then it is marked). */
75async function isScoutId(box: ScoutBox, io: RouteIo, id: string): Promise<boolean> {
76 if (box.isScout(id)) return true
77 if (await io.isHired(id)) return false
78 if ((await io.typeOf(id).catch(() => undefined)) !== SCOUT_TYPE) return false
79 box.mark(id)
80 return true
81}
82
83/**
84 * Every tool call goes through here first. A scout's is answered (or has its fields set); the pick tool is turned away from anyone
85 * else; `undefined` means the call is not the scout's and goes on as before. A scout is known from its very first call, marked or not.
86 */
87export async function scoutRoute(box: ScoutBox, io: RouteIo, folder: string, id: string | undefined, tool: string, input: Record<string, unknown>): Promise<ScoutAnswer | undefined> {
88 if (id !== undefined && (await isScoutId(box, io, id))) return scoutCall(box, io, folder, id, tool, input)
89 return tool === TEAM_TOOL ? { deny: NOT_SCOUT_DENY } : undefined
90}
91