nanocoder icon indicating copy to clipboard operation
nanocoder copied to clipboard

[Feature] Lifecycle hooks for agent events

Open addyCooks opened this issue 3 months ago • 1 comments

Description

Add a lifecycle hooks system: user-defined shell commands that Nanocoder runs at defined points in the agent loop before/after a tool runs, on session start/end, on prompt submit, before compaction.

Hooks are deterministic and free. No model is involved, no tokens are spent, and they fire every time rather than when the model remembers to.

Use Case

Nanocoder currently has no way to run user code in response to its own behaviour.

The closest existing mechanism is a skill subscribe: block, but it is a different shape and does not cover this:

Skill subscriptions (today) Hooks (proposed)
Triggered by The outside world (file changed, cron fired) Nanocoder itself
What runs An AI subagent A shell command
Cost LLM tokens on every fire Free, instant
Deterministic No Yes
Requires the daemon Yes, the TUI never starts event sources No
Available moments 2 (file.changed, schedule.cron) Any lifecycle point
Can veto an action No Yes

So today you can answer "the world changed, should an AI look at it?" but not "the agent is about to do X, should I allow it, and what should happen after?"

Concrete things this unlocks:

  • Auto-format after every edit. Run biome check --write on the file the agent just wrote. Today the options are an AGENTS.md instruction the model forgets, or spending a full LLM turn on it. (This is #1009 one specific instance of the general mechanism.)
  • Deterministic policy. "Never touch .env." "Never push to main." "No execute_bash while the working tree is dirty." approval-policy.ts currently decides whether the user is asked; it cannot run a user-supplied rule and refuse.
  • Automatic context injection. On session start, run git log -5 / docker ps and put the output in front of the model without the user typing !cmd each time.
  • Custom notifications. Post to Slack when a long run completes, alongside the built-in desktop notification.
  • Audit logging. Append every tool call to a file would make #1004 a few lines of config rather than a feature.

This is also one of the four weaknesses docs/battlemap.md concedes in writing:

Claude Code's Hooks system (process-level event hooks) also has no direct Nanocoder equivalent; Nanocoder's event story runs through Skill subscribe: blocks via the daemon, not arbitrary user-defined shell hooks on the agent lifecycle.

The other three admitted gaps (community size, surface breadth, distribution polish) are resourcing problems. This one is a feature someone can build.

Secondary benefit: it lowers the bar for extending Nanocoder from "write a skill in markdown, or TypeScript" to "add a shell one-liner to a config file" a much larger group of potential contributors for a 51-contributor project.

Proposed Solution

Hook definitions in agents.config.json, keyed by lifecycle point, optionally filtered by tool name:

{
  "hooks": {
    "post-tool-use": [
      { "matchTools": ["write_file", "string_replace"], "command": "biome check --write $NANOCODER_FILE" }
    ],
    "pre-tool-use": [
      { "matchTools": ["execute_bash"], "command": ".nanocoder/hooks/guard.sh" }
    ],
    "session-start": [
      { "command": "git log --oneline -5" }
    ]
  }
}

Proposed lifecycle points:

Hook Fires
session-start / session-end App init / shutdown
user-prompt-submit Before a prompt is sent
pre-tool-use Before a tool executes can block
post-tool-use After a tool returns
pre-compact Before context compaction

Contract:

  • Hook context passed via environment variables (tool name, arguments, changed file path, session id, working directory).
  • A non-zero exit from pre-tool-use denies the tool call, and stdout is returned to the model as the denial reason so it can adapt rather than retry blindly.
  • stdout from session-start / post-tool-use is optionally injected as context.
  • Every hook has a timeout, so a hanging script cannot wedge the session.
  • Hooks are project-local config and therefore a code-execution surface they should respect the existing directory-trust boundary, and probably be listed by /doctor so a user can see what is wired up.

Alternatives Considered

  • Skill subscribe: blocks. Already exist, but only fire on file.changed and schedule.cron, only run through the daemon, only dispatch to an AI subagent, and cannot veto anything. Wrong shape for this problem.
  • Instructions in AGENTS.md. "Always run the formatter after editing." Works until the model forgets, which is often, and costs tokens every turn.
  • Custom tools. The model has to choose to call them. Not deterministic, and useless for enforcing a rule the model is trying to break.
  • An MCP server. Far too heavyweight for "run this shell command after an edit", and MCP has no hook into Nanocoder's own lifecycle.
  • Adding more one-off features. #1009 (auto-format) and #1004 (audit log) are both individual cases of this mechanism. Building it once is cheaper than building each separately, and covers the next N requests too.

Additional Context

  • [x] I have searched existing issues to ensure this is not a duplicate
  • [x] This feature aligns with the project's goals (local-first AI assistance)

Implementation Notes (optional)

The insertion points are already centralised, which keeps the change small:

  • pre-tool-use / post-tool-use → source/tools/approval-policy.ts. resolveToolApproval() is already documented as the single authority every path routes through (interactive loop, subagents, plain shell), so there is exactly one place to add the gate rather than one per surface.
  • session-start / session-end → source/app/App.tsx init and the shutdown path in source/utils/shutdown/.
  • pre-compact → source/utils/auto-compact.ts, in performAutoCompact().
  • user-prompt-submit → the input submit handler.

source/services/bash-executor.ts already handles spawning with timeout and cwd/env resolution and can be reused for hook execution.

Open design question

Should pre-tool-use be able to block, or only observe?

Blocking is what makes the feature genuinely useful an observe-only hook cannot enforce "never touch .env". The cost is that a buggy hook can wedge the agent, and it introduces a second denial path alongside the approval policy.

My suggestion: allow blocking, but keep it strictly inside the existing approval model a hook returns a decision that feeds resolveToolApproval() rather than short-circuiting it, so there is still one authority and one place to reason about tool gating. Timeouts and a clear "denied by hook X" message in the transcript would cover the failure modes.

Happy to adjust the scope if the maintainers would rather start observe-only and add blocking later.

addyCooks avatar Aug 29 '26 07:08 addyCooks

Hey @akramcodez,

would love to hear if this direction makes sense to you.

The one thing I wasn't sure about: should pre-tool-use be able to block a tool call, or just observe? blocking is what makes policy rules work, but it adds a second denial path next to resolveToolApproval() I might be missing context on why that'd be a problem. observe-only would be a smaller first step if that's safer.

If you think it's worth doing, I'd be happy to take it on could scope the first PR to just pre-tool-use / post-tool-use to keep it reviewable

addyCooks avatar Aug 29 '26 07:08 addyCooks