Hooks
Hooks let an agent spec run setup and teardown logic around the sandbox lifecycle.
Use hooks when you need to:
- Install Python packages before first execution.
- Seed sandbox state (variables, files, context).
- Perform cleanup or write final markers at shutdown.
Supported Hook Fieldsโ
Hooks are defined in agent specs under these fields:
pre_hooks.packages (list of strings)โ
Install Python packages before the runtime starts serving requests.
pre_hooks:
packages:
- rich
- pandas
pre_hooks.sandbox (list of Python blocks)โ
Run Python setup code in the sandbox after startup and before the agent handles user requests.
pre_hooks:
sandbox:
- |
from pathlib import Path
Path('/tmp/startup.txt').write_text('ready\n', encoding='utf-8')
post_hooks.sandbox (list of Python blocks)โ
Run Python teardown/finalization code when the agent is shutting down.
post_hooks:
sandbox:
- |
from pathlib import Path
Path('/tmp/shutdown.txt').write_text('done\n', encoding='utf-8')
Execution Orderโ
For an agent with hooks enabled:
- Sandbox is created (
evalorjupyter, depending onsandbox_variant). pre_hooks.packagesare installed.pre_hooks.sandboxscripts run.- Agent starts handling prompts/tools.
- During shutdown,
post_hooks.sandboxscripts run.
If multiple scripts are defined in the same hook list, they run in list order.
Parameters and Templatingโ
Hooks support runtime templating with {{parameter_name}} values from the
agent spec parameters schema.
parameters:
type: object
properties:
demo_params:
type: string
default: hello
pre_hooks:
sandbox:
- |
demo_params = """{{demo_params}}"""
print(f"demo_params initialized: {demo_params!r}")
Complete Exampleโ
id: demo-hooks
version: 0.0.1
sandbox_variant: eval
pre_hooks:
packages:
- rich
sandbox:
- |
import datetime
import os
from pathlib import Path
hook_name = "demo-hooks:pre"
hook_ran_at = datetime.datetime.now().isoformat()
hook_env = {
k: os.environ[k]
for k in ("PATH", "HOME", "DATALAYER_CODE_SANDBOX_VARIANT")
if k in os.environ
}
Path('/tmp/agent_runtimes_pre_hook_demo.txt').write_text(
f'pre-hook executed at {hook_ran_at}\n',
encoding='utf-8',
)
post_hooks:
sandbox:
- |
import datetime
from pathlib import Path
post_ran_at = datetime.datetime.now().isoformat()
Path('/tmp/agent_runtimes_post_hook_demo.txt').write_text(
f'post-hook executed at {post_ran_at}\n',
encoding='utf-8',
)
Best Practicesโ
- Keep hooks idempotent where possible.
- Keep setup fast; install only necessary packages.
- Prefer deterministic file paths and explicit UTF-8 writes.
- Validate critical hook outputs with a follow-up suggestion/tool call.
- Use
pre_hooksfor initialization andpost_hooksfor finalization only.