hooks #
The hooks extension is installed but disabled by default. Enable it per session
through /extensions. It contributes Managed.hooks to the host contract in
harness/hook.gleam; hooks/engine.gleam owns matching and execution, not the loop.
configuration #
At preparation/reload, the extension reads $ALBEDO_HOME/hooks.json (default
~/.albedo/hooks.json), followed by <workspace>/.albedo/hooks.json.
All layers run; project definitions do not replace user definitions. Missing files
are ignored; malformed files/definitions and unsupported hook types produce
Managed.warnings, without crashing preparation.
{"hooks":{"PreToolUse":[{"matcher":"Edit|Write","hooks":[
{"type":"command","command":"./check-tool.sh","timeout":30,
"statusMessage":"Checking tool","additionalContextLimit":10000}
]}]}}
Only type: "command" runs. Timeout is positive integer seconds, default 600.
additionalContextLimit is nonnegative characters, default 10000, per hook.
statusMessage is retained as metadata; progress display is not implemented yet.
Matchers are regular expressions against the firing's matcher subject (tool name
for tool events, agent type for subagent events); empty and * match everything.
Both ^Bash$ and Edit|Write work. Invalid regexes are skipped with a warning.
Recognized event names: UserPromptSubmit, PreToolUse, PostToolUse, Stop,
SessionStart, SessionEnd, PreCompact, PostCompact, SubagentStart,
SubagentStop. Recognition does not imply the host currently fires every event.
execution and stdin #
Matching commands run concurrently, in the firing's workspace, via a shell. The engine uses an Erlang port with a short Python 3 subprocess helper: stdin is one JSON object followed by EOF; stdout and stderr are captured separately. The helper runs each command in its own process group and kills that group on timeout. Hook failures fail open with a message. Captured output is limited to 1 MiB per stream (overflow fails open); temporary output files are removed on helper completion. Temporary disk usage can grow during execution; hooks do not participate in the Python kernel's heavy-job admission pool.
Common stdin keys:
{"session_id":"...","cwd":"...","hook_event_name":"PreToolUse",
"transcript_path":"","permission_mode":"default"}
The firing's serialized JSON fields are merged into this object (including any
provided transcript_path); event-specific keys include tool_name, tool_input,
tool_response, prompt, and stop_hook_active as supplied by the loop.
stdout / exit contract #
- Exit 0: parse a JSON object. Plain stdout for
UserPromptSubmitorSessionStartbecomes context. For other events, empty stdout is ignored; non-JSON stdout is ignored with a fail-open diagnostic. - Exit 2: block, using stderr as the reason. This applies to
PostToolUseandStoptoo; the host decides what blocking means at that lifecycle point. - Other nonzero exit, timeout, helper crash, or malformed JSON: no block, and a user-visible diagnostic message.
JSON keys:
| Key | Outcome |
|---|---|
continue: false, stopReason |
halt |
systemMessage |
user-visible message |
decision: "block", reason |
block |
hookSpecificOutput.permissionDecision: "deny", permissionDecisionReason |
block |
hookSpecificOutput.permissionDecision: "allow", updatedInput |
serialized replacement input |
hookSpecificOutput.additionalContext |
model-visible context |
permissionDecision: "ask" and unknown fields are ignored with diagnostics.
Contexts over the limit receive a visible [hook context truncated] marker.
ordering and policy #
Results merge in configuration order, regardless of completion order: user layer before project layer, matcher groups and commands in array order. First block reason wins, first updated input wins, first halt reason wins; contexts and messages concatenate. A block beats an allow; a halt takes precedence at the host boundary.
trust and review #
User configuration is implicitly trusted. Project command definitions are
skipped until a user approves them, with a preparation warning naming the
number that need review. The outer loop and inner Python route use the same
immutable approval snapshot and engine.fire_with_filter policy seam.
/hooks lists the prepared definitions with their full SHA-256 id, source,
event, matcher, command, and status (trusted, needs review, or skipped).
Unsupported/malformed definitions appear as skipped rows with reasons. When the
whole extension is disabled its command is unavailable; /extensions shows that
disabled state.
/hooks trust <id>approves one reviewed project definition./hooks trust allapproves all project definitions in the prepared listing./hooks untrust <id>revokes an approval.
The entire /hooks command is user-only: no typed model binding is minted,
and commands.invoke('/hooks', 'trust all') is refused before dispatch. Review
cannot be delegated to the model. Approval writes are committed before requesting
a session refresh; output explicitly says whether refresh succeeded or the user
must run /reload session while idle. Other sessions use their previous approval
snapshot until their own next prepare/reload. Config edits are not watched.
The extension owns hooks_trust in the existing daemon ledger SQLite database;
its initializer creates the new table, so no upgrade/backfill migration is needed.
This follows the extension-owned persistence rule and uses serialized transactional
writes instead of a second mutable settings file. Rows contain hash, source, and
creation timestamp. Hashes use a versioned canonical array of source path, event,
matcher, type, command, timeout, context limit, and status message. JSON key order
and omitted defaults do not change the hash. Any reviewed semantic field change
does; source path scopes approvals to a workspace rather than trusting the same
command in every repository.
Approval covers the definition, not the contents of an executable/script the command references. This is review metadata, not a sandbox against a model or process already permitted to modify the daemon's private database or referenced scripts. Old approvals persist until revoked; they never approve a changed hash.
Focused tests in test/harness/hooks_engine_test.gleam cover decoding, matching,
merging, and real concurrent shell scripts with EOF stdin, stderr and timeout.
Lifecycle scenarios live in test/e2e/hooks_test.py on the shared real-daemon
harness, including fail-open errors and the Stop continuation limit.
calls inside Python cells #
The extension installs albedo_plugins.hooks, which enables a blocking
hooks.fire host call through albedo_hooks. It adds no model namespace bindings.
Calls to run match Bash; files.read, files.edit, and files.write match
Read, Edit, and Write. This keeps Claude-style matchers useful even when
the provider exposes only the outer python tool. Outer hooks still match the
actual provider tool name (python); these are separate firings.
The route is captured in the prepared session composition and fires only this
extension's own command definitions. Its arguments are event (PreToolUse or
PostToolUse), tool_name, tool_input (object), and optional tool_response.
The firing adds tool_use_id: "". The result contains nullable block, halt,
updated_input, and ordered context/messages arrays in the standard RPC
success envelope. Malformed requests are refused, not interpreted as hook vetoes.
A pre-hook denial/halt raises PermissionError before the inner operation runs.
updatedInput replaces the inner input; Bash command rewrites are parsed as argv,
not granted shell execution. Additional context is printed into the cell output
as [PreToolUse hook] .... Post-tool denials cannot undo completed operations;
the kernel prints their reason. With hooks disabled, the kernel adapter is inert.
Python callables #
With the extension enabled the kernel has a hooks object. hooks.register(event, callback, matcher=None) adds a Python callback for "PreToolUse" or
"PostToolUse" on the tools called inside cells: run (Bash) and
files.read/edit/write (Read, Edit, Write). matcher is a regex tested
with re.search on the tool name. The callback gets the same dict a command
hook gets on stdin (hook_event_name, tool_name, tool_input, and
tool_response after) and returns None or a dict in the Claude Code output
format. It may be sync or async, and fails open if it raises (the failure is
printed into the cell output). It returns a function that removes it;
hooks.registered() and hooks.clear() list and drop them.
Callbacks run in the kernel (priv/python/albedo_hooks.py) before the daemon's
command hooks and merge with them: a callback's block or halt skips the host
call, and its updatedInput is the input the command hooks see. They die with
the kernel and are never saved. They are not trust-gated: the model that
registers one already runs arbitrary code in the kernel.
hooks.register also takes "UserPromptSubmit" (input has prompt) and
"Stop" (input has last_assistant_message and stop_hook_active; a block
continues the turn), and "PreToolUse"/"PostToolUse" fire for the model's
own outer tool calls (matcher ^python$) as well as the inner ones. The
daemon asks the kernel for those through a hidden, non-journaled cell
(runtime.python_callbacks), only while the hooks extension is on. A callback's
block or halt skips the command hooks; otherwise its answer is merged with
theirs, a callback's updatedInput winning only if the command hooks gave none
(it is not fed to them for outer calls).
run() fires PostToolUse when the job finishes (tool_response: exit_code,
timed_out, output tail). Its context and block reason are appended to the
job's own output, since the cell that started it is long over.
Loop behavior #
harness/loop.gleam fires hooks through runtime.fire, merged by
extension.hooks:
UserPromptSubmit: once per turn, before the first model call. Context is committed as[UserPromptSubmit hook] ...input. A block ends the turn cleanly with a note to the user: no model call, no error. The prompt itself was committed before any hook saw it, so it stays in the transcript.PreToolUse: before each outer tool call. A block is the tool's result ({"error": "blocked by a hook: ..."});updatedInputreplaces the call's arguments; context follows the results.PostToolUse: after the call. A block cannot undo it; the reason reaches the model as context beside the result.Stop: when the model ends without a tool call. A block or context becomes the next input and the turn continues, at most 8 times;stop_hook_activeis true after the first.continue: falsefrom any of them ends the turn.- Hook
messages(systemMessage, fail-open reports) reach the user asnotestream events prefixedHook:.
Lifecycle #
daemon/session_hooks.gleam owns first-turn notifications and bounded teardown;
session_run runs them on its worker, never during actor-side preparation.
The first model turn after kernel adoption fires SessionStart, matcher/field
source = startup for an empty transcript or resume for retained history
(daemon restart, explicit/idle release, or kernel recovery). A committed
compaction marks the next ordinary turn compact. There is no transcript-clear
entry point, so clear is recognized as a matcher but never emitted. Start
notifications do not veto or halt an admitted turn. Plain SessionStart stdout
and JSON additionalContext are durable User inputs and reach the first model
request without replacing the actual user's UserPromptSubmit prompt.
SubagentStart fires with a new child's first startup turn; SubagentStop
fires alongside Stop at that child's end-of-turn checkpoint. Their matcher
is the child's spawn name; fields include agent_id (child session id) and
agent_type (spawn name), and Stop keeps last_assistant_message and
stop_hook_active. They use the child's composition, approved configuration,
and workspace, not the parent's. Root sessions have no subagent events.
SubagentStart context is durable; a SubagentStop veto/context continues the
child, under the same eight-continuation guard as Stop.
Manual /compact fires PreCompact before preparation and PostCompact after
a newly committed compaction. Automatic compaction fires Pre just before the
strategy's first real summarizer call (once even for several summary chunks),
and Post when Prepared.compacted is true. Matchers/fields trigger are
manual or auto; custom_instructions is currently empty. These are
notifications, not vetoes. Manual additional context is committed through the
worker; automatic additional context is currently ignored. Automatic strategies
that do not call the summarizer have no Pre notification; they still get Post.
No-op preparation/reused folds do not fire Post; unrelated notes calls do not
fire Pre. Interrupt is not currently supported.
SessionEnd fires for actor close (delete/shutdown) and explicit child
close/release, not ordinary idle kernel release. A small prepared hook snapshot
survives idle release so later close still notifies; a never-prepared session has
no snapshot to run. Matcher/field reason is currently other. The command
timeout defaults to 1 second and caps at 3 seconds, regardless of the
configured value. A separate four-second host deadline bounds teardown, and
its decisions/context are ignored. Closing runs off-actor and rejects new
turns. Delete/child-close API responses can precede these asynchronous
notifications; shutdown waits for actor close. Teardown diagnostics go to the
daemon log. Configuration/trust snapshot semantics are the same as other hooks.