---
title: "Swift API Reference"
description: "Complete API reference for the AgentSDK Swift. A native agent execution library with typed tools, providers, and loop strategies."
sidebar:
  label: "Swift API"
seo:
  title: "Swift API Reference | Autohand Code Agent SDK"
---

## Installation

Add AgentSDK to your `Package.swift`:

```swift
dependencies: [
    .package(path: "../AgentSDK"),
]
```

## CLI 0.9.13 run options

On macOS, pass `AutohandCLIConfiguration` to `AutohandSDK(configuration:)`.

- `maxRequests`, `maxDurationSeconds` set the request budget and wall-clock limit in seconds.
- `allowedTools`, `disallowedTools` accept lists of tool patterns.
- `profile`, `settingOverrides` select a saved profile and apply ordered run-only overrides.
- `noDaemon`, `syncSettings`, `searchEngine` control background services, settings synchronization, and web search.

Use `sdk.onNotification` and the packet’s `method` and `params` properties to read original CLI notifications. See [run option semantics](/agent-sdk/concepts/cli-runtime-control#run-options) and [notification payloads](/agent-sdk/concepts/hooks-and-events#runtime-notifications).

## Core Classes

### Agent

```swift
public init(
    name: String,
    instructions: String,
    tools: [ToolName] = [],
    maxTurns: Int = 10,
    model: ModelID? = nil,
    provider: (any Provider)? = nil,
    loopType: LoopType = .react
)
public func setModel(_ model: ModelID)
public func setProvider(_ provider: any Provider)
```

### Runner

```swift
public static func run(agent: Agent, prompt: String, options: LoopOptions? = nil) async throws -> RunResult
public static func runSync(agent: Agent, prompt: String, options: LoopOptions? = nil) async throws -> String
public static func runStream(agent: Agent, prompt: String, options: LoopOptions? = nil) -> AsyncThrowingStream<StreamEvent, Error>
public static func setHookManager(_ manager: HookManager)
public static func setPermissionManager(_ manager: PermissionManager?)
```

## Providers

### Provider Protocol

```swift
public protocol Provider: Sendable {
    func modelName(_ model: String) -> String
    func chat(messages: [Message], model: String, tools: [ToolSchema]?, options: ProviderOptions?) async throws -> ChatResponse
    func chatStream(messages: [Message], model: String, tools: [ToolSchema]?, options: ProviderOptions?) -> AsyncThrowingStream<ChatChunk, Error>
}
```

### OpenAIProvider

```swift
public init(apiKey: String, baseURL: URL = URL(string: "https://api.openai.com/v1")!)
```

### ProviderFactory

```swift
public static func create(providerName: String, apiKey: String, baseURL: URL? = nil) throws -> Provider
```

Supported: `"openai"`, `"openrouter"`

## Tools

### ToolDefinition

```swift
public protocol ToolDefinition: Sendable {
    var name: String { get }
    var description: String { get }
    var annotations: ToolAnnotations { get }
    var parameters: [String: AnyCodable] { get }
    func execute(params: [String: AnyCodable]) async throws -> ToolResult
}
```

### Built-in Tools

- `ReadFileTool` - Read file contents
- `WriteFileTool` - Write content to a file
- `EditFileTool` - Exact string replacements
- `BashTool` - Execute shell commands
- `WebSearchTool` - Search the web via DuckDuckGo
- Git tools: `GitStatusTool`, `GitDiffTool`, `GitLogTool`, `GitCommitTool`, `GitAddTool`, `GitPushTool`, `GitPullTool`, `GitBranchTool`, `GitCheckoutTool`

### ToolRegistry

```swift
public class ToolRegistry {
    public func register(_ tool: ToolDefinition)
    public func execute(toolCall: ToolCall) async throws -> ToolResult
    public func getTool(name: String) -> ToolDefinition?
    public func getAllTools() -> [ToolDefinition]
}
```

## Loop Strategies [#loops]

### LoopType

```swift
public enum LoopType: String, Sendable, CaseIterable {
    case react
    case planAndExecute = "plan_and_execute"
    case parallel
    case reflexion
}
```

### Built-in Strategies

- `ReActStrategy` - General-purpose reasoning + acting
- `PlanAndExecuteStrategy` - Complex multi-step tasks
- `ParallelStrategy` - Independent operations
- `ReflexionStrategy` - Quality-critical tasks

### LoopOptions

```swift
public struct LoopOptions: Sendable {
    public let maxPlanningSteps: Int?
    public let maxParallelCalls: Int?
    public let reflectionSteps: Int?
    public let qualityThreshold: Double?
    public let callbacks: ExecutionCallbacks?
}
```

## Hooks

### HookManager

```swift
public final class HookManager {
    public func addHook(_ hook: HookDefinition)
    public func removeHook(event: HookEvent, index: Int) -> Bool
    public func getHooks(for event: HookEvent) -> [HookDefinition]
    public func execute(event: HookEvent, context: HookContext) async throws
}
```

### HookEvent

```swift
public enum HookEvent: String, CaseIterable {
    case sessionStart, sessionEnd, preClear, prePrompt
    case preTool, postTool, fileModified
    case stop, subagentStop, permissionRequest
    case beforeExecution, afterExecution, onError
}
```

## Permissions

### PermissionManager

```swift
public final class PermissionManager {
    public var permissionMode: PermissionMode
    public func requestPermission(_ request: PermissionRequest) async -> PermissionResult
}
```

### PermissionMode

```swift
public enum PermissionMode: String, Sendable, Codable {
    case yolo, ask, deny
}
```

### PermissionDecision

```swift
public enum PermissionDecision: String, Sendable {
    case allow, deny, ask, block
}
```

## Types

### ToolName

```swift
public enum ToolName: String, CaseIterable, Codable {
    case readFile, writeFile, editFile, applyPatch
    case find, glob, searchInFiles
    case bash
    case gitStatus, gitDiff, gitLog, gitCommit, gitAdd
    case webSearch
}
```

### Message

```swift
public enum Message: Sendable, Codable {
    case user(UserMessage)
    case assistant(AssistantMessage)
    case system(SystemMessage)
    case tool(ToolMessage)
}
```

### RunResult

```swift
public enum RunResult: Sendable {
    case success(finalOutput: String, session: Session, turns: Int)
    case maxTurnsReached(session: Session, turns: Int)
}
```

### StreamEvent

```swift
public struct StreamEvent: Sendable {
    public let type: StreamEventType
    public let data: String?
    public let tool: ToolName?
    public let toolID: String?
}
```

## Errors

### AgentSDKError

```swift
public enum AgentSDKError: Error, LocalizedError, Sendable {
    case timeout(message: String, timeoutMs: Int, context: [String: AnyCodable]?)
    case retryExhausted(message: String, attempts: Int, lastError: Error)
    case validation(message: String, field: String?, value: AnyCodable?)
    case provider(message: String, providerName: String)
    case toolExecution(message: String, toolName: String)
    case agentConfig(message: String)
    case notFound(message: String, resourceType: String, resourceID: String)
}
```

## See Also

- [Swift SDK Overview](/agent-sdk/swift)
- [CLI Quick Start](/guides/cli-quick-start)
