At session start, one toast when beads in progress have had no update for 7 days, with their ids. Reads with bd stale, and says nothing without bd or a beads…

Small mods for Claude Code. Pick the ones you want and combine them.
Baselane mods are Claude Code plugins made of function hooks. Each mod does one thing: a guard that asks before rm -rf, a band with the session cost, a side pane with your git status, a sound when tests pass, a pirate voice for Claude's prose. There are 100+ mods in families such as guards, panes, meters, sounds and stats. Install one, or stack ten. They do not need each other.
You need Claude Code 2.1.288 or later, with mods.
claude plugin marketplace add baselane-sh/mods-catalog
claude plugin install guard-essentials@baselane-mods
claude plugin install receipt@baselane-mods
Start Claude Code. Now it asks before harsh commands, and /receipt prints a receipt of the session.
Browse every mod at https://baselane-sh.github.io/mods-catalog/. The gallery (baselane-mods) pins each mod to a reviewed commit, so a new mod reaches the gallery a short time after it reaches this repo. For update, uninstall, options and starter sets, read docs/INSTALL.md.
This repo also has a development marketplace, baselane-mods-dev, that tracks main. Use it only to try changes that are not released yet:
claude plugin marketplace add baselane-sh/mods
claude plugin install <name>@baselane-mods-dev
Each mod is released with a git tag <name>--v<version>.
Most mods have one rule. A pack is one mod with several rules from the same family. For example, guard-essentials holds several guards and band-pack puts several meters in one band.
guard-pack and infra-guard installed, the terraform destroy check runs two times, and you can see two questions.guard-essentials, cost-meter and git-pane work well together.The catalog below marks each pack with "pack".
Beads (bd) is an issue tracker that lives in your repo. 19 mods show your beads in Claude Code: bars above the prompt, panes, slash commands, a guard and reminders. They need bd 1.2 or later and a repo with a .beads folder. Without these, they do nothing.
The core set in one go (the bars, the panes, /ready and the guard):
claude plugin install beads-bars@baselane-mods
claude plugin install beads-pane@baselane-mods
claude plugin install epics-pane@baselane-mods
claude plugin install ready@baselane-mods
claude plugin install beads-guard@baselane-mods
Each beads mod is also in the catalog below, in its family.
ntfy-notify or long-run-notify, or a webhook URL for slack-notify or discord-notify. With a destination set, those mods send a short message only: a generic "needs input" text with the project folder name, or the project name and the seconds. One exception needs no setup: ci-band and ops-band ask GitHub, through your own gh login, for the latest Actions run of your branch every 2 minutes, sending the repository and branch name. Without gh, or with gh not logged in, they do nothing.sports-narrator makes one small model call at the end of a turn that used tools. It sends tool names, file names and the first two words of each shell command, never file contents. It spends tokens, so you must turn it on.bd on your machine, such as bd status --json and bd ready --json. No beads mod creates, changes or closes a bead. beads-guard asks before a bd command that deletes or rewrites beads.secret-output-guard tells Claude not to repeat a credential, auto-format and auto-lint tell Claude to read a file again, beads-prime adds the workflow text that bd prime prints from your repo's .beads files, and bead-claim-nudge and bead-commit-nudge add a one-line reminder at your next prompt./wrapped read records that the mods keep on your machine./handoff writes .claude/handoff.md and never overwrites it. session-journal appends to ~/.claude/journal.log. auto-format and auto-lint run your project's own formatter or linter fix, which can rewrite files. The descriptions say what each mod writes.lsof for port-watch, gh for ci-band, bd 1.2 or later for the beads mods, ps for process-pane, and on macOS pmset for battery-band and pgrep with osascript for now-playing.plugins/ and .claude-plugin/marketplace.json are generated. Do not edit them by hand.
node scripts/build.mjs # build one plugin folder per catalog entry
bash scripts/check.sh # rebuild, then validate, test and type-check every mod
bash scripts/check.sh git-pane # check only the mods you name
node scripts/gen-docs.mjs # rewrite the catalog in this README
node --test 'scripts/*.test.mjs' # test the docs generator
A change is done when check.sh prints check: 0 failure(s). Read AGENTS.md for the layout and the API facts.
To add a mod:
engines/<engine>/hooks/rules/<id>.ts, with a test in engines/<engine>/tests/<id>.test.ts.catalog/<name>.json: { "name", "description", "rules": ["<id>"] }. Give the description the slash command, if the mod has one (for example "Open it with /git"). The catalog table reads it from there.node scripts/build.mjs, then bash scripts/check.sh <mod>, then node scripts/gen-docs.mjs.A new engine needs a family in scripts/gen-docs.mjs. Keep files small, do not change inputs in place, and do not use the em-dash character.
MIT. Copyright (c) 2026 Baselane, LLC. Read LICENSE.
<!-- catalog:start -->
199 mods in 10 families.
"needs setup" means the mod has options that you set with claude plugin configure <mod>. Its description tells you if it works before you set them. "pack" means one mod with several rules.
Ask you before a harsh or risky command runs.
| Mod | What it does | Command | Notes | ||
|---|---|---|---|---|---|
beads-guard | Asks before bd commands that delete data or rewrite history: delete, purge, prune, gc, sql, admin, import, rename, forget, restore, migrate and more. Reads only the command text, runs no bd. | ||||
secret-filename-guard | Asks before a Bash command touches a secret-looking file (.env, private keys, credentials). | ||||
secret-guard | Asks before a live API key, token or private key is written, edited or run. | ||||
env-exfil-guard | Asks before a command prints your environment, echoes a secret variable or sends local data to a remote host. | ||||
infra-guard | Asks before terraform destroy, kubectl delete, force-push, DROP TABLE or rm -rf. | ||||
secret-commit-guard | Asks before a git commit that would record a credential or a secret-named file. Reads the staged diff with git. | ||||
protect-main | Asks before a commit, push or merge while you are on main or master. Reads the branch with git. | ||||
gitignore-check | Asks before git add or commit when secret-looking files are not ignored or are already tracked. Checks with git ls-files. | ||||
secret-output-guard | Tells Claude not to repeat a credential that showed up in command or file output, and names the source to rotate. | ||||
curl-pipe-guard | Asks before a download is piped into a shell or interpreter (curl \ | sh, wget -O- \ | bash, bash <(curl ...)). | ||
sudo-guard | Asks before sudo, doas or su -c runs a command with elevated rights. | ||||
no-verify-guard | Asks before git hooks are skipped (--no-verify, commit -n, HUSKY=0, core.hooksPath=/dev/null). | ||||
lockfile-guard | Asks before a lockfile is written or edited by hand; the package manager should change it. | ||||
package-guard | Asks before a new dependency is installed (npm, pnpm, yarn, bun, pip, uv, poetry, cargo, go, gem) and names the packages. | ||||
prod-db-guard | Asks before destructive SQL runs in a command: TRUNCATE, DELETE or UPDATE with no WHERE. | ||||
path-jail | Asks before Write, Edit or NotebookEdit changes a file outside the working directory, by real path. | ||||
docker-guard | Asks before Docker commands that delete data: system, volume or image prune, rm -f, volume rm and compose down -v. | ||||
k8s-guard | Asks before kubectl apply or replace with --force, kubectl drain, helm uninstall, and kubectl delete behind global flags (plain kubectl delete is infra-guard's). | ||||
migration-guard | Asks before Write or Edit changes a migration that already exists; new migration files pass. | ||||
ci-config-guard | Asks before Write or Edit changes CI config: .github/workflows, .gitlab-ci.yml or .circleci/config.yml. | ||||
chmod-guard | Asks before chmod makes files world-writable (777, a+w, o+w) or chmod or chown runs recursively on a broad path (/, a system folder, a home folder). | ||||
git-history-guard | Asks before git commands that throw away work or rewrite history: reset --hard, clean, rebase, filter-branch, filter-repo, push --delete, branch -D and stash clear. | ||||
big-file-guard | Asks before a Write creates content over 1 MB, or git add names a file over 5 MB. Measures the files with find. | ||||
publish-guard | Asks before a package is published: npm, pnpm, yarn or bun publish, cargo publish, twine upload, gem push, poetry or uv publish. Dry runs pass. | ||||
tag-guard | Asks before release tags go to a remote: git push --tags, --follow-tags or --mirror, a push of a tag ref, and a push that deletes a remote tag. Dry runs pass. Reads tags with git. | ||||
deploy-guard | Asks before a production deploy: vercel --prod, netlify deploy --prod, firebase deploy, fly deploy, gcloud app deploy, eb deploy, heroku rollback, serverless deploy to prod. | ||||
db-reset-guard | Asks before a framework wipes a database: prisma migrate reset, rails or rake db:drop and db:reset, alembic downgrade, django flush, supabase db reset, knex rollback --all. | ||||
ssh-guard | Asks before a private key in .ssh is read, authorized_keys or the SSH config is changed, or ssh-keygen would overwrite a key. Public keys and ssh -i pass. Reads HOME with printenv. | ||||
cron-guard | Asks before scheduled jobs or services are wiped or stopped: crontab -r, crontab replaced from stdin or a file, launchctl unload or bootout, systemctl stop, disable or mask. | ||||
upload-guard | Asks before local files go to a remote host: scp or rsync to host:path, piped input to nc, curl -T, sftp put. Local copies, downloads and localhost pass. | ||||
registry-push-guard | Asks before an image or chart is pushed to a registry: docker push, docker buildx --push, podman push, helm push, gcloud artifacts docker push. Local registries pass. | ||||
guard-essentials | Asks only before harsh or disaster commands: destructive infra, git and SQL, piping downloads into a shell, sudo, leaking or committing secrets. Reads git. The quiet choice for daily work. | pack | |||
guard-pack | The 15 core Baselane guards in one mod (secrets, git, infra, packages, path jail). Some read git, measure files with find, read HOME with printenv, or check where a path really lands. | pack | |||
guard-devops | Asks before harsh DevOps commands: destructive Docker, Kubernetes and Helm calls, CI config edits, broad chmod and chown, and git commands that lose work. Add infra-guard for plain kubectl delete. | pack | |||
release-pack | Asks before a release leaves your machine: package publish, tag push, production deploy and registry push guards in one mod. The tag guard reads tags with git. | pack | |||
ship-safe-pack | The release-pack guards plus db-reset-guard and upload-guard: asks before publish, tag push, production deploy, registry push, database wipes and file uploads. Reads tags with git. | pack |
One quiet toast at turn end when something needs your attention.
| Mod | What it does | Command | Notes |
|---|---|---|---|
bead-claim-nudge | At turn end, if Claude edited a file and no bead is in progress, shows a toast and reminds Claude at your next prompt, once per session. Reads with bd count; quiet without bd. | ||
bead-commit-nudge | At turn end, if a git commit named no bead id while a bead is in progress, shows a toast and reminds Claude at your next prompt. Reads with bd count and bd where; quiet without bd. | ||
test-reminder | Reminds you at turn end when source files changed but no test command ran since. | ||
ctx-nudge | Reminds you to /clear or /compact when the context window passes 75 percent. | ||
clippy | One helpful toast per session per trigger, in the classic paperclip voice: when you edit a migrations folder, a Dockerfile or a GitHub workflow, or run rm -rf. At most one toast per turn. | ||
sports-narrator | One line of sports play-by-play at turn end. OFF by default: one haiku call per turn with tools. Turn on the enabled option. Sends tool names, file names and the first two words of each command. | needs setup | |
commit-nudge | Suggests a commit at turn end after 8 or more file edits since the last git commit. One toast per batch of edits; a successful git commit resets the count. | ||
todo-nudge | At turn end, one toast with the count of TODO, FIXME and HACK lines your edits added this turn. Quiet when none were added. | ||
break-nudge | Suggests a short break once the session has run 90 minutes, and again every 90 minutes after that. | ||
docs-nudge | At turn end, one toast when edits added exported code (an export statement in .ts or .js, or a public function signature) and no README or docs file was edited this session. | ||
debug-print-nudge | At turn end, one toast naming the count of console.log, print(, debugger and dbg! lines your edits added this turn. Only code files count. | ||
typecheck-nudge | At turn end, one toast when .ts or .tsx files were edited and no type check (tsc, vue-tsc, a typecheck script or a build) ran since the last edit. | ||
lockfile-nudge | At turn end, one toast when dependencies in package.json, pyproject.toml, Cargo.toml or go.mod changed and neither the matching lockfile was edited nor an install command ran. | ||
big-diff-nudge | Suggests splitting the change once your edits added or removed more than 500 lines since the last git commit. A successful commit resets the count. | ||
migration-nudge | At turn end, one toast when a schema file changed (schema.prisma, models.py, SQL under schema/, a drizzle schema) and no migration file was created this session. | ||
env-example-nudge | At turn end, one toast when edits add a reference to an environment variable (process.env, os.environ, os.getenv, Deno.env) that .env.example does not list. Reads only .env.example names, never .env. | ||
nudge-pack | Two turn-end reminders in one mod: test-reminder and ctx-nudge. | pack | |
focus-pack | Three quiet nudges in one mod: commit after 8 edits, TODO/FIXME/HACK lines added, and debug prints added. | pack | |
quality-pack | Three quiet nudges in one mod: type check after TypeScript edits, lockfile after dependency edits, and a split suggestion past 500 changed lines. | pack |
Slash commands that print a result and, where it helps, copy it.
| Mod | What it does | Command | Notes |
|---|---|---|---|
ready | Adds /ready: the 20 top ready beads, one line each, and the total. Read with bd, the beads tracker. Read-only. Prints only, copies nothing. | /ready | |
bead | Adds /bead <id>: one bead with status, priority, labels, description, blockers and children. Read with bd, the beads tracker. Read-only. Prints only, copies nothing. | /bead | |
beads-standup | Adds /beads-standup: beads closed since yesterday, in progress, and the next 5 ready. Read with bd, the beads tracker. Read-only. Prints only, copies nothing. | /beads-standup | |
receipt | Adds /receipt: a shareable receipt of the session (tools, files, commands, blocks, context, cost), printed and copied. | /receipt | |
standup | Adds /standup: Yesterday, Today and Blockers from your git log and this session's record, printed and copied. | /standup | |
changelog | Adds /changelog: commits since the last tag (or the last 30), read with git log and grouped by conventional-commit type, as Markdown. Copies the result to your clipboard. | /changelog | |
pr-description | Adds /pr-description: title, summary, diff totals and a test plan stub for the current branch against main or master, read with git. Copies the result to your clipboard. | /pr-description | |
handoff | Adds /handoff: writes a session summary with the git status to .claude/handoff.md (never overwriting) and answers with the path. Copies the result to your clipboard. | /handoff | |
todos | Adds /todos: TODO, FIXME and HACK lines in tracked files, found with git grep, grouped by file (50 lines at most). Read-only. Copies the result to your clipboard. | /todos | |
loc | Adds /loc: lines of tracked text files by language, read with git, sorted, with a total. Skips lockfiles and binaries. Read-only. Copies the result to your clipboard. | /loc | |
hotspots | Adds /hotspots: the 10 files changed most often in the last 90 days, from git log, with change counts. Read-only. Copies the result to your clipboard. | /hotspots | |
commit-msg | Adds /commit-msg: a Conventional Commits message proposed from the staged diff, read with git. Heuristic, no model call, writes nothing. Copies the result to your clipboard. | /commit-msg | |
branches | Adds /branches: local branches merged into the default branch or idle for 30 days, as a cleanup list, read with git. Never deletes. Copies the result to your clipboard. | /branches | |
tree | Adds /tree: tracked files (git ls-files) as a tree, 2 levels deep, folders with file counts (80 lines at most). Read-only. Copies the result to your clipboard. | /tree | |
deps | Adds /deps: direct dependencies with versions from package.json, pyproject.toml, requirements.txt, go.mod and Cargo.toml at the repo root. No network. Read-only. Copies the result to your clipboard. | /deps | |
authors | Adds /authors: the top 15 contributors by commit count with their last commit date, from git log. Names only, never email addresses. Read-only. Copies the result to your clipboard. | /authors | |
scripts | Adds /scripts: runnable tasks from package.json scripts, Makefile targets, justfile recipes and pyproject scripts at the git repo root. Read-only. Copies the result to your clipboard. | /scripts | |
env-check | Adds /env-check: variable names in .env.example against .env at the git repo root, listing missing and extra names. Reads names only, never a value. Read-only. Copies the result to your clipboard. | /env-check | |
size | Adds /size: the 15 largest tracked files and the total tracked size at HEAD, read with git. Read-only. Copies the result to your clipboard. | /size | |
licenses | Adds /licenses: the licence of each direct dependency, from node_modules and Python dist-info at the git repo root. Shows unknown when it cannot tell. Read-only. Copies the result to your clipboard. | /licenses | |
conflicts | Adds /conflicts: tracked files that still hold merge conflict markers, with line numbers, found with git grep. Read-only. Copies the result to your clipboard. | /conflicts | |
secret-scan | Adds /secret-scan: tracked files and line numbers that hold secret-shaped text, found with git grep. Never prints a matched value. Read-only. Copies the result to your clipboard. | /secret-scan | |
envinfo | Adds /envinfo: versions of git, node, npm, python3, go, rustc and docker if installed, by running each (2 s limit), and the OS. Read-only. Copies the result to your clipboard. | /envinfo | |
stashes | Adds /stashes: git stashes with their age and the branch each was made on. Read-only, never applies or drops. Copies the result to your clipboard. | /stashes | |
recent | Adds /recent: your last 15 commits across all local branches (author is git user.name), with branch and date. Read-only. Copies the result to your clipboard. | /recent | |
file-owners | Adds /owners <path>: the top 5 authors of a file or folder by lines, from git blame. Names only, never addresses. Read-only. Copies the result to your clipboard. | /owners | |
readme-check | Adds /readme-check: missing README sections (install, usage, licence, contributing) and broken relative links, at the git repo root. Read-only. Copies the result to your clipboard. | /readme-check | |
command-pack | The five original slash commands in one mod: /receipt, /standup, /changelog, /pr-description and /handoff. They read git; /handoff also writes .claude/handoff.md. They copy results to the clipboard. | /receipt, /standup, /changelog, /pr-description, /handoff | pack |
repo-pack | Five read-only repo commands in one mod: /todos, /loc, /hotspots, /commit-msg and /branches. They read git. They copy results to the clipboard. | /todos, /loc, /hotspots, /commit-msg, /branches | pack |
explore-pack | Five read-only repo exploration commands in one mod: /tree, /deps, /authors, /scripts and /env-check. They read git and project files. They copy results to the clipboard. | /tree, /deps, /authors, /scripts, /env-check | pack |
audit-pack | Three read-only audit commands in one mod: /secret-scan, /conflicts and /licenses. They read git, project files and dependency folders. They copy results to the clipboard. | /secret-scan, /conflicts, /licenses | pack |
A one-line band above the prompt.
| Mod | What it does | Command | Notes |
|---|---|---|---|
cost-meter | A band above the prompt with the session cost so far and what the last turn cost. | ||
latte-meter | A band above the prompt that counts the session cost in lattes. Set the latte price in the plugin options. | needs setup | |
context-meter | A band above the prompt with a 10 cell bar of the context window used, yellow from 60 percent, red from 80. | ||
daily-spend | A band above the prompt with today's total cost across all your sessions. |
| pomodoro | A band above the prompt with a 25/5 focus timer (focus 18:42, break 03:10). Start and stop it with /pomodoro; a to
hooks/register.ts 10 lines1import type { Register } from 'claude-code'
2
3import { startSessionWithRun } from './hosts/start-run'
4import { rule as beadStaleNudge } from './rules/bead-stale-nudge'
5
6export const register: Register = on => {
7 const rules = [beadStaleNudge]
8 startSessionWithRun(on, rules)
9}
10hooks/hosts/start-run.ts 18 lines1import type { On } from 'claude-code'
2
3import { START_RUN_TIMEOUT_MS, sessionStart } from '../engine'
4import type { LifecycleRule, StartTools } from '../engine'
5
6// As the session starts, for rules that run a program and show a toast. Not
7// awaited: the session does not wait on a program.
8export const startSessionWithRun = (on: On, rules: readonly LifecycleRule[]): void => {
9 on('session.start', async ($, e, next) => {
10 const tools: StartTools = {
11 run: (argv, cwd) => $.process.run(argv, { cwd, timeoutMs: START_RUN_TIMEOUT_MS }),
12 toast: text => $.ui.toast(text),
13 }
14 void sessionStart(rules, tools, text => $.ui.log(text), { cwd: e.cwd })
15 return next(e)
16 })
17}
18hooks/rules/bead-stale-nudge.ts 44 lines1import type { LifecycleRule } from '../engine'
2
3export const STALE_DAYS = 7
4const LISTED = 5
5const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
6
7// The ids in `bd stale --json`, or none for anything that is not a list of
8// beads. Ids are checked, so a strange id never reaches the toast.
9export const staleIds = (stdout: string): readonly string[] => {
10 const parsed: unknown = JSON.parse(stdout)
11 if (!Array.isArray(parsed)) return []
12 return parsed.flatMap((item: unknown) => {
13 const id = typeof item === 'object' && item !== null && 'id' in item ? item.id : undefined
14 return typeof id === 'string' && ID.test(id) ? [id] : []
15 })
16}
17
18export const toastText = (ids: readonly string[]): string => {
19 const shown = ids.slice(0, LISTED).join(', ')
20 const more = ids.length > LISTED ? ` and ${ids.length - LISTED} more` : ''
21 const subject = ids.length === 1 ? '1 bead in progress has' : `${ids.length} beads in progress have`
22 return `${subject} had no update for ${STALE_DAYS} days: ${shown}${more}`
23}
24
25// At session start, one toast when beads in progress have had no update for 7
26// days. Reads with `bd stale`; without bd, without a beads project or on any
27// odd answer it says nothing.
28export const rule: LifecycleRule = {
29 id: 'bead-stale-nudge',
30 onSessionStart: async (e, tools) => {
31 const done = await tools
32 .run(['bd', 'stale', '--days', String(STALE_DAYS), '--status', 'in_progress', '--limit', '500', '--json'], e.cwd)
33 .catch(() => undefined)
34 if (done === undefined || done.exitCode !== 0 || done.stdout.trim() === '') return
35 let ids: readonly string[]
36 try {
37 ids = staleIds(done.stdout)
38 } catch {
39 return
40 }
41 if (ids.length > 0) await tools.toast(toastText(ids))
42 },
43}
44hooks/engine.ts 182 lines1import type { PluginOptions, ProcessRunResult, ToolCallEnvelope, ToolCallResult } from 'claude-code'
2
3// What each kind of rule may use. The engine forbids passing `$` itself, so
4// it hands over these functions instead, one set per hook.
5export type PushTools = {
6 post: (url: string, headers: Record<string, string>, body: string) => Promise<void>
7}
8
9export type RunTools = {
10 run: (argv: readonly string[]) => Promise<ProcessRunResult>
11}
12
13export type NotifyTools = PushTools & RunTools
14
15// What a rule at the session's start may use: a program run in the session's
16// folder, and a toast for the person.
17export type StartTools = {
18 run: (argv: readonly string[], cwd: string) => Promise<ProcessRunResult>
19 toast: (text: string) => unknown
20}
21
22export type ToolTools = PushTools & {
23 cwd: () => Promise<string>
24 root: () => Promise<string>
25 exists: (path: string) => Promise<boolean>
26 read: (path: string) => Promise<string>
27 list: (path: string) => Promise<readonly string[]>
28 run: (argv: readonly string[], cwd?: string) => Promise<ProcessRunResult>
29}
30
31export type JournalTools = {
32 home: () => Promise<string | undefined>
33 now: () => Promise<number>
34 exists: (path: string) => Promise<boolean>
35 read: (path: string) => Promise<string>
36 write: (path: string, text: string) => Promise<void>
37}
38
39// The plugin's userConfig values, checked.
40export type Settings = { ntfyTopic: string; longRunSecs: number; slackWebhookUrl: string; discordWebhookUrl: string }
41
42export const DEFAULT_LONG_RUN_SECS = 60
43
44const text = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')
45
46export const settingsFrom = (options: PluginOptions): Settings => {
47 const secs = options['longRunSecs']
48 return {
49 ntfyTopic: text(options['ntfyTopic']),
50 longRunSecs: typeof secs === 'number' && Number.isFinite(secs) && secs > 0 ? secs : DEFAULT_LONG_RUN_SECS,
51 slackWebhookUrl: text(options['slackWebhookUrl']),
52 discordWebhookUrl: text(options['discordWebhookUrl']),
53 }
54}
55
56// A finished tool call, as the rules after a tool see it.
57export type ToolRun = { e: ToolCallEnvelope; elapsedMs: number }
58
59// A finished main-loop turn, as the rules at a turn's end see it.
60export type TurnEnd = { cwd: string; durationMs: number; isAborted: boolean }
61
62// One lifecycle rule. Each member is optional: a rule names what it does at
63// the moments it cares about. `afterTool` may return a note the model reads
64// with the tool's result; the others act on the outside world.
65export type LifecycleRule = {
66 id: string
67 afterTool?: (run: ToolRun, tools: ToolTools, settings: Settings) => Promise<string | undefined>
68 onNeedsInput?: (e: { cwd: string }, tools: NotifyTools, settings: Settings) => Promise<void>
69 onSessionStart?: (e: { cwd: string }, tools: StartTools) => Promise<void>
70 onTurnEnd?: (e: TurnEnd, tools: RunTools, settings: Settings) => Promise<void>
71 onSessionEnd?: (e: { cwd: string; reason: string }, tools: JournalTools, settings: Settings) => Promise<void>
72}
73
74const PUSH_TIMEOUT_MS = 5000
75// The Notification types that wait for the person. Others (auth_success and
76// the like) need no input, so they send nothing.
77const NEEDS_INPUT = new Set(['permission_prompt', 'idle_prompt', 'elicitation_dialog'])
78// A desktop notification or a spoken line must not hold up the session long.
79export const NOTIFY_TIMEOUT_MS = 10_000
80export const RUN_TIMEOUT_MS = 30_000
81// A read of bd at the session start must not hold anything up for long.
82export const START_RUN_TIMEOUT_MS = 10_000
83
84type Log = (text: string) => unknown
85
86const failed = (id: string, error: unknown): string =>
87 `${id}: skipped, ${error instanceof Error ? error.message : String(error)}`
88
89// A rule that throws is logged and skipped, never allowed to break the tool
90// call or the shutdown.
91const guarded = async (id: string, log: Log, work: () => Promise<void>): Promise<void> => {
92 try {
93 await work()
94 } catch (error) {
95 await log(failed(id, error))
96 }
97}
98
99// The fetch has no timeout of its own, and a stuck push must not hold up the
100// tool result. `fetch` and `sleep` are closures over the hook's `$`.
101export const push = async (fetch: () => Promise<{ ok: boolean; status: number }>, sleep: (ms: number) => Promise<void>) => {
102 const answer = await Promise.race([
103 fetch(),
104 sleep(PUSH_TIMEOUT_MS).then(() => {
105 throw new Error('the push timed out')
106 }),
107 ])
108 if (!answer.ok) throw new Error(`the push was refused (HTTP ${answer.status})`)
109}
110
111// The tools a host does not give. A rule that calls one is logged and
112// skipped, and its tests fail: name what it uses in engine.json `needs`.
113const absent = (name: string) => (): Promise<never> =>
114 Promise.reject(new Error(`${name} is not given to this mod; name it in engine.json needs`))
115
116export const NO_TOOL_TOOLS: ToolTools = {
117 cwd: absent('cwd'),
118 root: absent('root'),
119 exists: absent('exists'),
120 read: absent('read'),
121 list: absent('list'),
122 run: absent('run'),
123 post: absent('post'),
124}
125
126export const NO_NOTIFY_TOOLS: NotifyTools = { post: absent('post'), run: absent('run') }
127
128// After each tool call that ran (not denied, no error): each rule's
129// `afterTool`, and the notes they return beside the result. `now` and `log`
130// close over the hook's `$`.
131export const afterTool = async (
132 rules: readonly LifecycleRule[],
133 settings: Settings,
134 tools: ToolTools,
135 host: { now: () => Promise<number>; log: Log },
136 e: ToolCallEnvelope,
137 next: (e: ToolCallEnvelope) => Promise<ToolCallResult>,
138): Promise<ToolCallResult> => {
139 const startedAt = await host.now()
140 const ran = await next(e)
141 if (ran.deny !== undefined || ran.isError !== undefined) return ran
142 const elapsedMs = (await host.now()) - startedAt
143 let notes: readonly string[] = []
144 for (const rule of rules) {
145 await guarded(rule.id, host.log, async () => {
146 const note = await rule.afterTool?.({ e, elapsedMs }, tools, settings)
147 if (note !== undefined) notes = [...notes, note]
148 })
149 }
150 return notes.length === 0 ? ran : { ...ran, context: [...(ran.context ?? []), ...notes] }
151}
152
153// Only the Notification types that wait for the person reach the rules.
154export const needsInput = async (
155 rules: readonly LifecycleRule[],
156 settings: Settings,
157 tools: NotifyTools,
158 log: Log,
159 e: { cwd: string; notification_type: string },
160): Promise<void> => {
161 if (!NEEDS_INPUT.has(e.notification_type)) return
162 for (const rule of rules) await guarded(rule.id, log, async () => rule.onNeedsInput?.(e, tools, settings))
163}
164
165export const sessionStart = async (rules: readonly LifecycleRule[], tools: StartTools, log: Log, e: { cwd: string }): Promise<void> => {
166 for (const rule of rules) await guarded(rule.id, log, async () => rule.onSessionStart?.(e, tools))
167}
168
169export const turnEnd = async (rules: readonly LifecycleRule[], settings: Settings, tools: RunTools, log: Log, end: TurnEnd): Promise<void> => {
170 for (const rule of rules) await guarded(rule.id, log, async () => rule.onTurnEnd?.(end, tools, settings))
171}
172
173export const sessionEnd = async (
174 rules: readonly LifecycleRule[],
175 settings: Settings,
176 tools: JournalTools,
177 log: Log,
178 e: { cwd: string; reason: string },
179): Promise<void> => {
180 for (const rule of rules) await guarded(rule.id, log, async () => rule.onSessionEnd?.(e, tools, settings))
181}
182