惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
Google DeepMind News
Google DeepMind News
Hugging Face - Blog
Hugging Face - Blog
D
Docker
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
J
Java Code Geeks
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Simon Willison's Weblog
Simon Willison's Weblog
S
Security Affairs
NISL@THU
NISL@THU
T
Tor Project blog
A
About on SuperTechFans
宝玉的分享
宝玉的分享
腾讯CDC
S
Schneier on Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Privacy & Cybersecurity Law Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Stack Overflow Blog
Stack Overflow Blog
P
Privacy International News Feed
雷峰网
雷峰网
C
Cyber Attacks, Cyber Crime and Cyber Security
Vercel News
Vercel News
Cisco Talos Blog
Cisco Talos Blog
D
DataBreaches.Net
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Google Online Security Blog
Google Online Security Blog
Recorded Future
Recorded Future
L
LINUX DO - 热门话题
Microsoft Security Blog
Microsoft Security Blog
Latest news
Latest news
C
Check Point Blog
有赞技术团队
有赞技术团队
T
The Exploit Database - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
云风的 BLOG
云风的 BLOG
SecWiki News
SecWiki News
Application and Cybersecurity Blog
Application and Cybersecurity Blog
爱范儿
爱范儿
月光博客
月光博客
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
P
Palo Alto Networks Blog
T
The Blog of Author Tim Ferriss
C
Cisco Blogs
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Deep Dive into Open Agent SDK (Part 5): Session Persistence and Security
NEE · 2026-04-27 · via DEV Community

An Agent is more than a one-shot Q&A tool. A truly useful Agent must do three things: remember context (where we left off), control permissions (which operations are allowed), and audit behavior (who did what and when). Open Agent SDK uses four subsystems to cover these needs — SessionStore, PermissionPolicy, SandboxSettings, and HookRegistry.

This article analyzes the implementation details of these four subsystems, how each works individually, and how they combine to build a secure Agent.

1. Session Persistence: SessionStore

Each Agent Loop run produces a messages array. Without persistence, it's lost when the process exits. SessionStore persists this conversation history to disk for restoration on next startup.

What Is SessionStore

SessionStore is an actor — all methods require await. By default, sessions are stored in ~/.open-agent-sdk/sessions/, with one subdirectory per session containing a transcript.json file.

let sessionStore = SessionStore()  // Default path
let sessionStore = SessionStore(sessionsDir: "/custom/path")  // Custom path

Enter fullscreen mode Exit fullscreen mode

Five Core Operations

SessionStore provides five core methods covering the full session lifecycle.

save — Save a session. Serializes the messages array and metadata to JSON and writes to disk:

try await sessionStore.save(
    sessionId: "my-session",
    messages: messages,
    metadata: PartialSessionMetadata(
        cwd: "/project",
        model: "claude-sonnet-4-6",
        summary: "Code analysis session",
        tag: "analysis",
        firstPrompt: "Analyze project structure"
    )
)

Enter fullscreen mode Exit fullscreen mode

Storage structure:

~/.open-agent-sdk/sessions/
  my-session/
    transcript.json    // { "metadata": {...}, "messages": [...] }

Enter fullscreen mode Exit fullscreen mode

File permissions are 0600, directory permissions 0700 — only the current user can read/write. Each save preserves the original createdAt timestamp, updating only updatedAt.

load — Load a session. Reads transcript.json from disk and deserializes into SessionData:

if let data = try await sessionStore.load(sessionId: "my-session") {
    print("Messages: \(data.metadata.messageCount)")
    print("Model: \(data.metadata.model)")
    // data.messages is [[String: Any]] array
}

Enter fullscreen mode Exit fullscreen mode

load supports pagination parameters limit and offset for loading only the tail when full history isn't needed:

// Load only the last 50 messages
let recent = try await sessionStore.load(sessionId: "my-session", limit: 50, offset: nil)

Enter fullscreen mode Exit fullscreen mode

list — List all sessions, sorted by updatedAt descending (most recent first):

let sessions = try await sessionStore.list(limit: 10)
for session in sessions {
    print("\(session.id)\(session.summary ?? "(untitled)") [\(session.messageCount) messages]")
}

Enter fullscreen mode Exit fullscreen mode

SessionMetadata includes id, cwd, model, createdAt, updatedAt, messageCount, and optional summary, tag, firstPrompt, gitBranch, fileSize.

fork — Fork a session. Copies messages from an existing session to a new one, optionally specifying a truncation point:

// Full copy
let newId = try await sessionStore.fork(sourceSessionId: "my-session")

// Copy only the first 10 messages
let truncatedId = try await sessionStore.fork(
    sourceSessionId: "my-session",
    upToMessageIndex: 10
)

// Specify new session ID
let customId = try await sessionStore.fork(
    sourceSessionId: "my-session",
    newSessionId: "forked-session"
)

Enter fullscreen mode Exit fullscreen mode

delete — Delete an entire session directory:

let deleted = try await sessionStore.delete(sessionId: "my-session")

Enter fullscreen mode Exit fullscreen mode

Additional helper methods include rename (change title) and tag (add tags).

Three Session Recovery Modes

When SessionStore is injected into an Agent, the SDK provides three recovery strategies:

1. Specified sessionId Recovery

The most direct approach: given a session ID, the Agent loads historical messages at startup, prepending them to the messages array:

let agent = createAgent(options: AgentOptions(
    apiKey: apiKey,
    model: "claude-sonnet-4-6",
    sessionStore: sessionStore,
    sessionId: "my-session"      // Specify which session to restore
))

Enter fullscreen mode Exit fullscreen mode

2. continueRecentSession — Auto-Continue Most Recent

When you don't know the session ID, let the SDK automatically find the most recent one:

let agent = createAgent(options: AgentOptions(
    apiKey: apiKey,
    model: "claude-sonnet-4-6",
    sessionStore: sessionStore,
    continueRecentSession: true   // Auto-load most recent session
))

Enter fullscreen mode Exit fullscreen mode

Internally calls sessionStore.list() and takes the first result (already sorted by updatedAt descending).

3. forkSession + resumeSessionAt — Fork and Truncate

Fork a new branch from an existing session, optionally truncating at a specific message:

let agent = createAgent(options: AgentOptions(
    apiKey: apiKey,
    model: "claude-sonnet-4-6",
    sessionStore: sessionStore,
    sessionId: "my-session",
    forkSession: true,                     // Copy to new session
    resumeSessionAt: "msg-uuid-123"        // Truncate at this message
))

Enter fullscreen mode Exit fullscreen mode

SDK parsing order: continueRecentSession determines session ID first, then forkSession creates a fork, then resumeSessionAt truncates history. These three options work independently or in combination.

SessionStore Security Details

SessionStore includes path traversal prevention in session ID validation:

private func validateSessionId(_ sessionId: String) throws {
    guard !sessionId.isEmpty else {
        throw SDKError.sessionError(message: "Session ID must not be empty")
    }
    let forbidden = ["/", "\\", ".."]
    for component in forbidden {
        if sessionId.contains(component) {
            throw SDKError.sessionError(message: "Session ID contains invalid character: '\(component)'")
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Session IDs cannot contain /, \, or .. — preventing attackers from crafting IDs to read/write unexpected paths.

2. Permission Control: PermissionPolicy

Session persistence solves "remembering." Permission control solves "what's allowed."

Six PermissionModes

The SDK defines 6 permission modes:

Mode Behavior
default Ask user before each tool execution
plan Read-only tools execute directly; write operations require confirmation
auto Automatically execute all tools except dangerous operations
acceptEdits File edits auto-execute; other operations require confirmation
dontAsk Don't ask user; auto-judge based on context
bypassPermissions Skip all permission checks
let agent = createAgent(options: AgentOptions(
    apiKey: apiKey,
    model: "claude-sonnet-4-6",
    permissionMode: .plan  // Read-only tools run directly; writes need confirmation
))

Enter fullscreen mode Exit fullscreen mode

canUseTool Callback: More Granular Than PermissionMode

permissionMode is a global switch with coarse granularity. For fine-grained control by tool name or properties, use the canUseTool callback:

let agent = createAgent(options: AgentOptions(
    apiKey: apiKey,
    model: "claude-sonnet-4-6",
    permissionMode: .bypassPermissions,
    canUseTool: { tool, input, context in
        if tool.name == "Bash" {
            return CanUseToolResult.deny("Bash is not allowed")
        }
        return nil  // nil means "no opinion, defer to permissionMode"
    }
))

Enter fullscreen mode Exit fullscreen mode

canUseTool returns CanUseToolResult?. Returning nil means the callback has no opinion, passing to the next check. Non-nil results use the callback's decision, ignoring permissionMode.

CanUseToolResult has three factory methods:

CanUseToolResult.allow()                              // Allow
CanUseToolResult.deny("reason")                          // Deny
CanUseToolResult.allowWithInput(modifiedInput)         // Allow but modify input parameters

Enter fullscreen mode Exit fullscreen mode

allowWithInput is rare but practical — you can modify tool input parameters during permission checks, such as redirecting file write paths to a safe directory.

Policy Pattern: Composable Permission Rules

Writing closures is flexible but not reusable. The SDK provides a PermissionPolicy protocol, encapsulating permission judgments as composable policies:

public protocol PermissionPolicy: Sendable {
    func evaluate(
        tool: ToolProtocol,
        input: Any,
        context: ToolContext
    ) async -> CanUseToolResult?
}

Enter fullscreen mode Exit fullscreen mode

Four built-in policies:

ToolNameAllowlistPolicy — Allowlist, only permits specified tools:

let policy = ToolNameAllowlistPolicy(allowedToolNames: ["Read", "Glob", "Grep"])
// Write, Edit, Bash etc. all denied

Enter fullscreen mode Exit fullscreen mode

ToolNameDenylistPolicy — Denylist, rejects specified tools:

let policy = ToolNameDenylistPolicy(deniedToolNames: ["Bash", "Write"])
// Other tools execute normally

Enter fullscreen mode Exit fullscreen mode

ReadOnlyPolicy — Only allows read-only tools (isReadOnly == true):

let policy = ReadOnlyPolicy()
// Read, Glob, Grep, WebSearch etc. allowed
// Write, Edit, Bash etc. denied

Enter fullscreen mode Exit fullscreen mode

CompositePolicy — Combines multiple policies, evaluated in order:

let policy = CompositePolicy(policies: [
    ToolNameDenylistPolicy(deniedToolNames: ["Bash"]),
    ReadOnlyPolicy()
])
// Denylist checked first (Bash denied), then read-only policy

Enter fullscreen mode Exit fullscreen mode

CompositePolicy evaluation rules:

  • Any sub-policy returning deny causes overall deny (short-circuit)
  • Sub-policy returning nil (no opinion) is skipped
  • All sub-policies allow or no opinion results in overall allow

Bridge policies to callbacks with canUseTool(policy:):

let policy = CompositePolicy(policies: [
    ToolNameDenylistPolicy(deniedToolNames: ["Bash"]),
    ReadOnlyPolicy()
])

let agent = createAgent(options: AgentOptions(
    apiKey: apiKey,
    model: "claude-sonnet-4-6",
    permissionMode: .bypassPermissions,
    canUseTool: canUseTool(policy: policy)
))

Enter fullscreen mode Exit fullscreen mode

3. Sandbox Mechanism: SandboxSettings + SandboxChecker

Permission control manages "can this tool execute." Sandbox manages "is this operation within allowed bounds." For example, the Bash tool passes permission checks, but you still need to ensure it won't run rm -rf /.

SandboxSettings Configuration

let sandbox = SandboxSettings(
    // Path control
    allowedReadPaths: ["/project/"],
    allowedWritePaths: ["/project/build/"],
    deniedPaths: ["/etc/", "/var/"],

    // Command control
    deniedCommands: ["rm", "sudo"],           // Denylist
    // allowedCommands: ["git", "swift"],     // Allowlist (choose one with denylist)

    // Behavior control
    allowNestedSandbox: false,
    autoAllowBashIfSandboxed: false,          // Auto-approve Bash when sandbox is active
    allowUnsandboxedCommands: false,
    enableWeakerNestedSandbox: false,

    // Network control
    network: SandboxNetworkConfig(
        allowedDomains: ["api.example.com"],
        allowLocalBinding: false
    )
)

Enter fullscreen mode Exit fullscreen mode

Paths and commands each have two modes:

  • Paths: allowedReadPaths/allowedWritePaths are allowlists (empty = allow all); deniedPaths is a denylist (higher priority)
  • Commands: allowedCommands is an allowlist (non-nil restricts to listed commands); deniedCommands is a denylist. allowedCommands takes priority over deniedCommands

SandboxChecker Execution Logic

SandboxChecker is a stateless enum providing isPathAllowed, checkPath, isCommandAllowed, checkCommand static methods. isXxx returns Bool; checkXxx throws SDKError.permissionDenied on failure.

Path checking uses prefix matching with segment boundary guarantees:

// /project/ matches /project/src/file.swift
// /project/ does NOT match /project-backup/file.swift
SandboxChecker.isPathAllowed("/project/src/main.swift", for: .read, settings: sandbox)
// -> true

SandboxChecker.isPathAllowed("/project-backup/old.swift", for: .read, settings: sandbox)
// -> false (segment boundary mismatch)

Enter fullscreen mode Exit fullscreen mode

The key is SandboxPathNormalizer — normalizes paths first (resolving .., ., symlinks), then ensures trailing / for segment boundaries during prefix comparison:

// Path traversal attacks get normalized away
let normalized = SandboxPathNormalizer.normalize("/project/src/../../etc/passwd")
// -> "/etc/passwd", then caught by deniedPaths

Enter fullscreen mode Exit fullscreen mode

Command checking has three phases:

  1. Shell metacharacter detection — identifying bypass patterns like bash -c "cmd", $(cmd), `cmd`
  2. Basename extraction — extracting rm from /usr/bin/rm -rf /tmp
  3. Allowlist/denylist matching
// Denylist has "rm"
SandboxChecker.isCommandAllowed("rm -rf /tmp", settings: blocklist)
// -> false

// Path-form commands are recognized
SandboxChecker.isCommandAllowed("/usr/bin/rm -rf /tmp", settings: blocklist)
// -> false (basename extracted as "rm")

// Backslash bypass
SandboxChecker.isCommandAllowed("\\rm -rf /tmp", settings: blocklist)
// -> false (leading \ removed, gets "rm")

// Quote bypass
SandboxChecker.isCommandAllowed("\"rm\" -rf /tmp", settings: blocklist)
// -> false (quotes removed, gets "rm")

// Subshell bypass
SandboxChecker.isCommandAllowed("bash -c \"rm -rf /tmp\"", settings: blocklist)
// -> false (recursive check of inner command)

Enter fullscreen mode Exit fullscreen mode

Commands that can't be reliably parsed default to denied.

File paths in command arguments are also extracted and checked — if a command references a path in deniedPaths, the command is rejected.

autoAllowBashIfSandboxed

This option bridges sandbox and permission systems. When autoAllowBashIfSandboxed = true, the Bash tool skips canUseTool permission callback checks but still undergoes SandboxChecker.checkCommand() filtering.

The design rationale: if you've configured comprehensive sandbox rules, what Bash can do is already constrained. No need for an additional permission confirmation.

4. Hook System: 20+ Lifecycle Events

The first three systems solve "can it be done." The Hook system solves "know when it's done" and "intervene before it happens."

20+ HookEvents

The SDK defines 24 lifecycle events:

Event Trigger Timing
preToolUse Before tool execution
postToolUse After successful tool execution
postToolUseFailure After failed tool execution
sessionStart Agent session starts
sessionEnd Agent session ends
stop Agent Loop stops
subagentStart Sub-agent launches
subagentStop Sub-agent completes
userPromptSubmit User submits prompt
permissionRequest Permission check occurs
permissionDenied Permission denied
taskCreated Task created
taskCompleted Task completed
configChange Configuration change
cwdChanged Working directory change
fileChanged File change
notification Notification event
preCompact Before conversation compaction
postCompact After conversation compaction
teammateIdle Team member idle
setup Agent initialization
worktreeCreate Worktree created
worktreeRemove Worktree removed

Function Hooks vs Shell Hooks

Hooks have two implementation approaches: function callbacks and shell commands.

Function Hook — Swift closure, suitable for in-process logic:

await registry.register(.preToolUse, definition: HookDefinition(
    handler: { input in
        // input is HookInput with event, toolName, toolInput, sessionId, etc.
        return HookOutput(message: "Intercepted", block: true)
    }
))

Enter fullscreen mode Exit fullscreen mode

Shell Hook — External command, suitable for integrating non-Swift scripts:

await registry.register(.preToolUse, definition: HookDefinition(
    command: "python3 /path/to/check.py"  // HookInput passed via stdin JSON
))

Enter fullscreen mode Exit fullscreen mode

Shell Hooks execute via ShellHookExecutor: using /bin/bash -c to launch a process, serializing HookInput as JSON to stdin, reading HookOutput JSON from stdout. If stdout isn't valid JSON, it's wrapped as HookOutput(message: stdout).

Shell Hook environment variables include HOOK_EVENT, HOOK_TOOL_NAME, HOOK_SESSION_ID, HOOK_CWD for easy context detection in scripts.

HookRegistry Registration and Execution

HookRegistry is an actor, internally maintaining [HookEvent: [HookDefinition]] mappings:

let registry = HookRegistry()

// Register function Hook
await registry.register(.preToolUse, definition: HookDefinition(
    handler: { input in
        return HookOutput(message: "Bash blocked", block: true)
    },
    matcher: "Bash"  // Only match Bash tool
))

// Register Shell Hook
await registry.register(.postToolUse, definition: HookDefinition(
    command: "/usr/bin/logger 'Tool executed'",
    timeout: 5000  // 5 second timeout
))

// Execute all Hooks registered on an event
let results = await registry.execute(.preToolUse, input: hookInput)
// results: [HookOutput], containing return values from all matching Hooks

Enter fullscreen mode Exit fullscreen mode

matcher filtering: Each HookDefinition can have a matcher (regex). During execution, input.toolName is checked against the matcher; non-matching Hooks are skipped. nil matcher matches all tools.

Timeout handling: Function Hooks use withThrowingTaskGroup for timeout — placing actual execution and Task.sleep in the same TaskGroup, using whichever completes first. Timed-out Hooks don't affect other Hooks. Shell Hooks use DispatchQueue.asyncAfter for timeout, terminating the process when time's up.

Execution order: Hooks on the same event execute serially in registration order.

HookOutput Capabilities

HookOutput can do all of this:

HookOutput(
    message: "Log message",                          // Attached info
    block: true,                                      // Intercept operation
    notification: HookNotification(               // Send notification
        title: "Warning",
        body: "Dangerous operation detected",
        level: .warning
    ),
    permissionUpdate: PermissionUpdate(           // Dynamically modify permissions
        tool: "Bash",
        behavior: .deny
    ),
    systemMessage: "Please operate within sandbox",  // Inject system message
    reason: "Security policy",                         // Interception reason
    updatedInput: ["command": "echo safe"],            // Modify tool input
    decision: .block                                   // Explicit approve/block
)

Enter fullscreen mode Exit fullscreen mode

block: true prevents tool execution, returning an error result to the LLM. permissionUpdate dynamically modifies tool permissions during Hook execution. updatedInput replaces tool input parameters.

5. Practical Combination: Building a Secure Agent

Four subsystems, each with its own role:

  • SessionStore — Remember conversation history
  • PermissionPolicy — Control whether tools can execute
  • SandboxSettings — Limit operational scope
  • HookRegistry — Audit and intercept

Here's a complete example showing how to combine them:

import Foundation
import OpenAgentSDK

// 1. Create SessionStore
let sessionStore = SessionStore()

// 2. Create HookRegistry, register audit and security interception
let hookRegistry = HookRegistry()

// Log all tool executions
await hookRegistry.register(.postToolUse, definition: HookDefinition(
    handler: { input in
        if let toolName = input.toolName {
            print("[Audit] Tool \(toolName) completed")
        }
        return nil
    }
))

// Intercept dangerous Bash commands
await hookRegistry.register(.preToolUse, definition: HookDefinition(
    handler: { input in
        return HookOutput(
            message: "Bash blocked by security policy",
            block: true,
            decision: .block
        )
    },
    matcher: "Bash"
))

// Log permission denial events
await hookRegistry.register(.permissionDenied, definition: HookDefinition(
    handler: { input in
        print("[Security Alert] Permission denied: \(input.error ?? "unknown")")
        return nil
    }
))

// Session lifecycle tracking
await hookRegistry.register(.sessionStart, definition: HookDefinition(
    handler: { _ in print("[Session] Started"); return nil }
))
await hookRegistry.register(.sessionEnd, definition: HookDefinition(
    handler: { _ in print("[Session] Ended"); return nil }
))

// 3. Configure sandbox: restrict paths and commands
let sandbox = SandboxSettings(
    allowedReadPaths: ["/project/"],
    allowedWritePaths: ["/project/src/", "/project/tests/"],
    deniedPaths: ["/etc/", "/var/", "/tmp/"],
    deniedCommands: ["rm", "sudo", "chmod", "chown"],
    autoAllowBashIfSandboxed: false,
    allowNestedSandbox: false
)

// 4. Configure permission policy: read-only + exclude Bash
let policy = CompositePolicy(policies: [
    ToolNameDenylistPolicy(deniedToolNames: ["Bash"]),
    ReadOnlyPolicy()
])

// 5. Create Agent, inject all components
let agent = createAgent(options: AgentOptions(
    apiKey: "sk-...",
    model: "claude-sonnet-4-6",
    systemPrompt: "You are a code analysis assistant. Read-only, no modifications.",
    maxTurns: 10,
    permissionMode: .bypassPermissions,
    canUseTool: canUseTool(policy: policy),
    sessionStore: sessionStore,
    sessionId: "analysis-session",
    hookRegistry: hookRegistry,
    sandbox: sandbox
))

// 6. Execute query
let result = await agent.prompt("Analyze the Swift source file structure in the project")
print(result.text)

// 7. Resume session later
let resumedAgent = createAgent(options: AgentOptions(
    apiKey: "sk-...",
    model: "claude-sonnet-4-6",
    permissionMode: .bypassPermissions,
    canUseTool: canUseTool(policy: policy),
    sessionStore: sessionStore,
    sessionId: "analysis-session",  // Same session ID, auto-restores history
    hookRegistry: hookRegistry,
    sandbox: sandbox
))

let continued = await resumedAgent.prompt("Continue analyzing test files")
print(continued.text)

Enter fullscreen mode Exit fullscreen mode

This Agent's security features:

  • Permission layer: CompositePolicy ensures only read-only tools execute, with Bash denied by denylist
  • Sandbox layer: Even if tools pass permission checks, they're restricted by path — only reading files under /project/, unable to touch /etc/ or /var/
  • Hook layer: All tool executions are logged (audit), and Bash calls are secondarily intercepted by the preToolUse Hook
  • Session layer: Conversations auto-saved and restored, continuing previous work after restart

Multi-layer defense benefit: even if one layer has a configuration gap, others provide backup. For example, if you accidentally add Bash to the allowlist, the Hook's matcher still intercepts it. Even if the Hook misses it, the sandbox's command filtering still blocks it.

Summary

SessionStore, PermissionPolicy, SandboxSettings, and HookRegistry — four systems each managing one concern, but combined they form a complete security framework:

  • SessionStore's actor isolation and session ID validation ensure storage security
  • PermissionPolicy's composable policies provide flexible permission management
  • SandboxChecker's path normalization and segment boundary matching prevent directory traversal
  • HookRegistry's matcher filtering and timeout mechanisms ensure Hook system reliability

The next article covers the SDK's multi-LLM providers: how to simultaneously support Anthropic, OpenAI, and other LLMs, the Provider protocol design, and runtime model switching mechanisms.


Deep Dive into Open Agent SDK (Swift) Series:

GitHub: terryso/open-agent-sdk-swift