Skip to main content
Extend & Customize›Lifecycle hooks

Hooks

Hooks let you run custom shell commands or scripts automatically whenever key events happen in TalkOps—such as when a session starts, when a tool is about to run, when a deployment finishes, or when an incoming webhook investigation completes.

You can use hooks to enforce team guardrails (like auto-formatting Terraform files or blocking hardcoded secrets), stream audit logs to an external SIEM, or trigger custom notifications.

Hooks run shell commands on your machine using your user account permissions. Only enable hooks from scripts and repositories you trust.


How Hooks Work​

TalkOps supports two complementary hook styles in ~/.talkops/hooks.json (as well as hooks bundled inside installed plugins under <plugin>/hooks/hooks.json):

  1. Event Notification & Audit Hooks — Fire-and-forget or awaited scripts that receive a JSON event payload over stdin whenever operational events occur (such as session.start, tool.use, terraform.apply, or webhook.completed).
  2. Lifecycle & Tool Interception Hooks — Targeted matchers that run before or after agent lifecycle steps (such as PreToolUse, PostToolUse, UserPromptSubmit, or SubagentStart) and can allow, block, or add context to a tool call.

Built-In Environment Sanitization​

Before TalkOps spawns any hook subprocess, it automatically strips environment variables whose names contain KEY, TOKEN, SECRET, PASSWORD, APIKEY, or CREDENTIAL (such as OPENAI_API_KEY or AWS_SECRET_ACCESS_KEY). This prevents external hook scripts from accidentally leaking your ambient cloud or LLM credentials.


1. Event Notification & Audit Hooks (~/.talkops/hooks.json)​

To run a script whenever operational events occur, add a "hooks" array to ~/.talkops/hooks.json. Each entry specifies:

  • command — The executable and arguments as a JSON array of strings (for example, ["/usr/local/bin/audit-log.sh"] or ["jq", "-c", "."]).
  • events — A list of event names to listen for (leave empty [] to run on every event).
{
"hooks": [
{
"command": ["/usr/local/bin/talkops-audit.sh"],
"events": [
"session.start",
"session.end",
"tool.use",
"webhook.received",
"webhook.completed"
]
}
]
}

How Your Script Receives Event Data​

When a matching event fires, TalkOps runs your command (with a 5-second timeout) and passes:

  • TALKOPS_HOOK_EVENT — An environment variable set to the event name (for example, webhook.completed).
  • stdin — A single-line JSON object containing the event details (with tool_output truncated to 2,000 characters to keep payloads lightweight).

Supported Notification Events​

CategoryEvent NameWhen It FiresPayload Fields Passed on stdin
Sessionsession.startA new session startssession_id, model
Sessionsession.endA session endssession_id, duration_s
Sessionuser.promptA user submits a promptPrompt metadata
Sessioncontext.compactConversation history is compactedCompaction summary metadata
Tools & Taskstool.useA tool is invokedtool_name, tool_id, tool_args
Tools & Taskstool.resultA tool finishestool_name, tool_status, tool_output
Tools & Taskstool.errorA tool raises an errortool_name, error
Tools & Taskspermission.requestA tool awaits human approvalTool call details
Tools & Taskstask.completeA background or delegated task finishessummary
DevOps & Cloudterraform.plan / terraform.applyTerraform plan or apply runsOperation details
DevOps & Cloudhelm.install / kubectl.applyHelm or Kubernetes rollout runsCluster & release details
DevOps & Clouddeploy.start / deploy.completeDeployment workflow starts or finishesDeployment details
DevOps & Cloudaws.resource.create / update / deleteAWS resource mutation eventResource details
Webhookswebhook.receivedAn incoming alert/webhook is accepted (202 Accepted)delivery_id, thread_id, provider, event_type, severity, title, incident_id
Webhookswebhook.completedA background webhook investigation finishesdelivery_id, thread_id, provider, event_type, severity, title, incident_id, status

2. Lifecycle & Tool Interception Hooks​

For fine-grained control over agent execution, lifecycle hooks let you match specific tools and block or enrich actions before they happen.

Lifecycle Events​

Event NameWhen It FiresWhat Your Hook Can Do
SessionStartWhen a session starts, resumes, clears, or compactsInject initial context into the session
UserPromptSubmitWhen you submit a prompt before the agent runsBlock the prompt or attach additional instructions
PreToolUseImmediately before a tool executesAllow, deny (cancel the tool call and return a message to the agent), or attach context
PermissionRequestWhen a tool triggers an approval promptProgrammatically allow or deny the approval request
PostToolUseImmediately after a tool succeedsAppend follow-up notes or validation output
PostToolUseFailureWhen a tool failsProvide troubleshooting hints back to the agent
SubagentStartWhen a specialized subagent is launchedInject instructions for the subagent
SubagentStopWhen a subagent completes its taskValidate the subagent's findings
PreCompactRight before /compact or auto-compactionPreserve key context
StopWhen the main agent finishes a turnRequest continuation if a required check was missed
NotificationWhen TalkOps sends a status notificationObserve notifications externally
SessionEndWhen the session closes or logs outRun cleanup or logging scripts

Standardized Tool Names for Matchers​

When writing a matcher pattern for PreToolUse, PostToolUse, or PermissionRequest, you can match against these standardized tool names (using an exact name, wildcard, or regex like Write|Edit):

Matcher NameBuilt-In ActionInput Fields
BashShell command (execute)command, timeout
WriteCreate/overwrite file (write_file)file_path, content
EditEdit existing file (edit_file)file_path, old_string, new_string, replace_all
ReadRead file (read_file)file_path, offset, limit
GlobFind files by pattern (glob)pattern, path
GrepSearch file contents (grep)pattern, path, glob, output_mode
LSList directory (ls)path
WebSearchWeb search (web_search)query, max_results
WebFetchFetch URL (fetch_url)url, timeout
mcp__<server>__<tool>External MCP server toolTool-specific arguments

Practical Examples​

Example 1: Log All Webhook Investigations to an Audit File​

Save the following in ~/.talkops/hooks.json to append every incoming and completed webhook investigation to a local JSON Lines log file:

{
"hooks": [
{
"command": [
"sh",
"-c",
"cat >> ~/.talkops/webhook-audit.jsonl && echo '' >> ~/.talkops/webhook-audit.jsonl"
],
"events": ["webhook.received", "webhook.completed"]
}
]
}

Example 2: Send a Desktop or Slack Alert When a Long Task Completes​

{
"hooks": [
{
"command": [
"sh",
"-c",
" SUMMARY=$(jq -r '.summary // \"Task finished\"'); osascript -e \"display notification \\\"$SUMMARY\\\" with title \\\"TalkOps\\\"\""
],
"events": ["task.complete"]
}
]
}

Example 3: Lifecycle Matcher Configuration (PreToolUse & PostToolUse)​

When configuring lifecycle matcher groups, group handlers under the lifecycle event name and specify a matcher pattern:

{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "tofu fmt -recursive || true",
"statusMessage": "Formatting Terraform files"
}
]
}
]
}
}

See Also​