Guardrails I โ€” Hooks

Lesson 5: Guardrails I โ€” Hooks

Because the CLI owns the agent loop, guardrails are not something you wrap around the loop โ€” they are callbacks the loop makes into your process at precise moments. These callbacks are hooks, and they are the single most powerful surface in the SDK. This lesson covers all ten of them; Lesson 6 covers the sibling mechanism, permissions, and how the two interact.

Where hooks sit in the request lifecycle

user prompt onUserPromptSubmitted + runtime context onUserPromptTransformed model call 1 turn onPreToolUse allow / deny / ask ยท modify args tool executes built-in ยท custom ยท MCP onPostToolUse onPostToolUseFailure (on failure) onErrorOccurred ยท onAgentStop retry / skip / abort ยท block another turn loop

Hooks fire in your application's process. That is the important property: a hook can query your database, call your policy service, write an audit row, or post to Slack, because it is ordinary code in your runtime โ€” not a sandboxed function inside the CLI.

The complete hook reference

All hook inputs include sessionId, timestamp, and workingDirectory. All handlers receive invocation: { sessionId } as the second argument. Every handler may return void/null (no-op) or an output object in which all fields are optional.

HookFiresInputOutput
onUserPromptSubmittedUser sends a message prompt modifiedPrompt (replaces it) ยท additionalContext (appended hidden context)
onUserPromptTransformedAfter the runtime adds generated context, before persistence and before the model sees it prompt (post-submitted), transformedPrompt (model-facing, includes things like <current_datetime>) modifiedTransformedPrompt โ€” the replacement is persisted as the user message, so resumed sessions replay it unchanged
onPreToolUseBefore any tool executes toolName, toolArgs permissionDecision "allow" | "deny" | "ask" ยท permissionDecisionReason ยท modifiedArgs ยท additionalContext
onPostToolUseAfter a successful tool execution toolName, toolArgs, toolResult modifiedResult ยท additionalContext
onPostToolUseFailureAfter a tool whose result was "failure" toolName, toolArgs, error (string only โ€” no full result) additionalContext only
onSessionStartSession begins or resumes source: "startup" | "resume" | "new", initialPrompt? additionalContext
onSessionEndSession ends reason: "complete" | "error" | "abort" | "timeout" | "user_exit", finalMessage?, error? sessionSummary (for persistence) ยท cleanupActions (descriptions)
onErrorOccurredAn error occurs error, errorContext: "model_call" | "tool_execution" | "system" | "user_input", recoverable errorHandling: "retry" | "skip" | "abort" ยท retryCount ยท userNotification
onAgentStopTop-level agent naturally stops stopHookActive decision: "block" + reason โ†’ forces another turn
onSubagentStartBefore a sub-agent's first turn (input sessionId is the parent's) transcriptPath, agentName, agentDisplayName?, agentDescription? additionalContext โ†’ prepended to the child's initial prompt
onSubagentStopAfter a sub-agent completes a turn agentName, agentId?, agentType, stopReason, response, transcriptPath decision: "block" + reason โ†’ another child turn ยท modifiedResponse โ†’ replace what the parent sees

There is one more, narrower hook: a pre-MCP-tool-call hook that lets you set, replace, or remove meta on an MCP tool call โ€” covered in Lesson 7 where MCP is the subject.

The five guardrail patterns that do the real work

1. Tool allowlist (deny-by-default)

const ALLOWED = new Set(["read_file", "grep", "glob", "custom:orders_lookup"]);

const session = await client.createSession({
  hooks: {
    onPreToolUse: async (input) => {
      if (!ALLOWED.has(input.toolName)) {
        return {
          permissionDecision: "deny",
          permissionDecisionReason: `Tool "${input.toolName}" is not permitted in this session.`,
        };
      }
      return { permissionDecision: "allow" };
    },
  },
  onPermissionRequest: approveAll,
});
Deny-by-default beats blocklisting. A blocklist of dangerous tools (shell, bash, exec) is a guessing game against a moving surface โ€” new tools appear, MCP servers inject their own, plugins contribute more. An allowlist inverts the failure mode: the unknown case is denied, and the model receives your reason and can adapt.

2. Path jail โ€” reject traversal on write operations

import path from "node:path";

const WORKSPACE = path.resolve("/srv/agent-workspace");

const session = await client.createSession({
  hooks: {
    onPreToolUse: async (input) => {
      if (input.toolName !== "write_file") {
        return { permissionDecision: "allow" };
      }
      const target = String((input.toolArgs as any)?.path ?? "");
      const resolved = path.resolve(WORKSPACE, target);

      // Must stay inside the workspace, and must not escape via .. or symlink-style paths
      if (resolved !== WORKSPACE && !resolved.startsWith(WORKSPACE + path.sep)) {
        return {
          permissionDecision: "deny",
          permissionDecisionReason:
            "Writes are confined to the agent workspace. Choose a path inside it.",
        };
      }
      return { permissionDecision: "allow" };
    },
  },
  onPermissionRequest: approveAll,
});
Resolve, then compare โ€” never compare unresolved strings. Checking target.startsWith("/srv/agent-workspace") on the raw argument passes for /srv/agent-workspace/../../etc/passwd and for a sibling directory named /srv/agent-workspace-evil. The + path.sep suffix matters for exactly that second case. Where the runtime offers its own containment (workspace-relative file APIs, workspacePath), prefer it over hand-rolled string work.

3. Escalate to a human instead of deciding

const DESTRUCTIVE = /^(rm|drop|truncate|delete|force-push|reset --hard)/i;

const session = await client.createSession({
  hooks: {
    onPreToolUse: async (input) => {
      if (input.toolName === "shell") {
        const cmd = String((input.toolArgs as any)?.command ?? "");
        if (DESTRUCTIVE.test(cmd.trim())) {
          return { permissionDecision: "ask" };   // hand off to onPermissionRequest
        }
      }
      return { permissionDecision: "allow" };
    },
  },
  onPermissionRequest: async (request) => {
    // Only "ask"-ed operations reach here in this design
    return await humanApproval(request);
  },
});

"ask" is the third decision and the one most people miss. It defers the call to the session's onPermissionRequest handler โ€” the clean seam between "my policy can decide" and "a person must decide". Lesson 6 covers that handler properly.

4. Redact secrets from tool results (output-side guardrail)

Input guardrails get all the attention, but tools leak. A cat .env, a config dump, an API response with a bearer token โ€” all of it flows straight into conversation history, which is persisted and replayed on every subsequent model call.

const SECRET_PATTERNS = [
  /(?:api[_-]?key|token|secret|password)\s*[:=]\s*["']?[\w\-.]+["']?/gi,
  /gh[pousr]_[A-Za-z0-9]{20,}/g,
  /sk-[A-Za-z0-9]{20,}/g,
];

const session = await client.createSession({
  hooks: {
    onPostToolUse: async (input) => {
      if (typeof input.toolResult !== "string") return null;

      let redacted = input.toolResult;
      for (const pattern of SECRET_PATTERNS) {
        redacted = redacted.replace(pattern, "[REDACTED]");
      }

      return redacted !== input.toolResult ? { modifiedResult: redacted } : null;
    },
  },
  onPermissionRequest: approveAll,
});
Redact on egress, not just ingress. Once a secret is in conversation history it is in the checkpoints on disk and in every future prompt for that session. onPostToolUse is your last cheap interception point โ€” after it, the value is durable. Note the guard: return null when nothing changed, which preserves the runtime's defaults.

5. Deterministic completion โ€” force another turn when the work isn't done

const session = await client.createSession({
  hooks: {
    onAgentStop: async (input) => {
      // stopHookActive prevents an infinite block loop
      if (input.stopHookActive) return null;

      const ok = await runAcceptanceChecks();   // your real gate: tests, lint, schema check
      if (!ok.passed) {
        return {
          decision: "block",
          reason: `Not done yet. Fix these and re-run: ${ok.failures.join("; ")}`,
        };
      }
      return null;
    },
  },
  onPermissionRequest: approveAll,
});
Token angle โ€” and a real hazard. onAgentStop can turn "the agent said it finished" into "the agent actually finished", which is the difference between an autonomous workflow that ships and one that reports success on broken output. But each block costs at least one more full turn. Always check stopHookActive, always bound your retries (a counter keyed on invocation.sessionId), and make the acceptance check cheap and deterministic. An unbounded agent-stop loop is how you discover your per-session budget the hard way.

Hooks compose โ€” and this is the intended design

const session = await client.createSession({
  hooks: {
    onSessionStart: async (input) => {
      audit(`session started in ${input.workingDirectory}`);
      return { additionalContext: "Project uses TypeScript and Vitest." };
    },
    onPreToolUse: async (input) => {
      audit(`tool requested: ${input.toolName}`);
      return input.toolName === "shell"
        ? { permissionDecision: "ask" }
        : { permissionDecision: "allow" };
    },
    onPostToolUse: async (input) => {
      audit(`tool completed: ${input.toolName}`);
      return null;
    },
    onErrorOccurred: async (input) => {
      alert(`${input.errorContext}: ${input.error}`);
      return null;
    },
    onSessionEnd: async (input, invocation) => {
      audit(`session ${invocation.sessionId.slice(0, 8)} ended: ${input.reason}`);
      return null;
    },
  },
  onPermissionRequest: approveAll,
});

Permissions, auditing, notifications, and enrichment coexist in one hooks object without conflict. Hooks also fire for sub-agent tool calls โ€” the runtime emits preToolUse, postToolUse, subagentStart, and subagentStop correctly for sub-agent activity, so a single hook set guards the whole tree.

Hook best practices

PracticeReason
Keep hooks fastThey run inline. A 2-second hook adds 2 seconds to the conversation, every time it fires.
Offload heavy work to a background queueAudit writes, webhooks, and analytics should not block the loop
Return null when you change nothingSignals "proceed with defaults" and avoids needless allocation
Be explicit with permission decisions{ permissionDecision: "allow" } documents intent; a bare null makes the policy invisible in review
Don't swallow unrecoverable errorsSuppressing a recoverable tool error is fine; suppressing a fatal one hides it from everyone
Prefer additionalContext over modifiedPromptAppending preserves the user's original intent while still steering the model
Scope state by invocation.sessionId, clean up in onSessionEndHooks are per-process and long-lived; leaked per-session maps become memory bugs
One hook to avoid in SDK-based agents: do not call session.send() synchronously from onUserPromptSubmitted. It re-enters the agent from inside the agent and can loop forever. If you genuinely must, defer it โ€” setTimeout(() => session.send(...), 0).

Choosing between a hook and a schema

Before writing a hook, ask whether a declaration would do. Hooks are code that runs on every tool call; some constraints are better expressed as configuration the runtime enforces natively.

ConstraintCheapest expression
Only these tools exist at allavailableTools allowlist (session config)
These tools are blocked for everyoneexcludedTools blocklist (session config)
The main agent must not call this heavy tooldefaultAgent.excludedTools (Lesson 8)
This specific tool is safe, never promptskipPermission: true on the tool definition
No ambient OS access at allmode: "empty" (Lesson 6)
Conditional logic on arguments, paths, or contentHook โ€” only code can evaluate this

๐Ÿง  Knowledge Check

1. A tool returns resultType: "failure". Which hook can observe it, and what is one thing it cannot do?

2. Which onPreToolUse decision hands the call off to onPermissionRequest rather than deciding immediately?

3. Why is onPostToolUse the right place to redact secrets, and what is the correct return when nothing matched?

Further Reading