Integrate AgentKit
The Swift package, from install to shutdown
AgentKit embeds a native AI conversation in a macOS app, backed by a locally installed Claude Code or Codex CLI, or by Antigravity, Gemini CLI, OpenCode, Grok, Kiro or another Agent Client Protocol agent. It includes the conversation UI, provider runtime, application tool calls and persistent session management extracted from Tab.
Requirements
AgentKit requires macOS 14 or later on Apple silicon. Build with Xcode 26 or later and Swift 6; the package uses Swift 5 language mode.
The runtime launches installed provider executables. Install and sign in to the provider CLI before using a real conversation; the runtime can check, install and update supported CLIs, but sign-in stays with each CLI. AgentKit does not bundle a model.
Modules
One Swift package, three library products:
| Module | Use it for |
|---|---|
AgentCore |
Conversation models, commands, attachments, and the transport interface. |
AgentRuntime |
Running local CLI providers and persisting conversations. No AppKit dependency. |
AgentUI |
The native AppKit transcript and composer, with an optional SwiftUI wrapper. No runtime dependency. |
@hugocxl/icons is the package's only external Swift dependency. Rendering uses AppKit rather than a web transcript.
Install
Add https://github.com/hugocxl/agentkit.git in Xcode's package dependencies, or add:
.package(url: "https://github.com/hugocxl/agentkit.git", from: "1.20.1")Select the products your target needs:
.product(name: "AgentCore", package: "agentkit"),
.product(name: "AgentRuntime", package: "agentkit"),
.product(name: "AgentUI", package: "agentkit"),Build an AI-first app
Your app provides its domain tools and their handlers. AgentKit supplies the native conversation, streaming, local CLI connection, model selection, tool results, and session lifecycle. The same tool definitions work with both providers.
import AgentCore
import AgentRuntime
import AgentUI
let tools = AgentToolConfiguration([
AgentToolDefinition(
name: "add_title",
description: "Add a title to the current video project.",
inputSchema: [
"type": "object",
"properties": ["text": ["type": "string"]],
"required": ["text"]
]
)
]) { @MainActor call in
guard let text = call.arguments["text"]?.string else {
return .failure("A title is required.")
}
guard let context = AgentToolExecutionContext.current else { return .failure("Not a tool call.") }
do {
// The edit lands only while this call may still change the project.
try context.withCommit { editor.addTitle(text) } // Your app's normal editing and undo path.
} catch {
return .failure("The call was cancelled before the title was added.")
}
return AgentToolResult(text: "Added the title.")
}
// Persist this ID with the workspace; reuse it on subsequent launches.
let workspace = try AgentWorkspace(
workingDirectory: projectDirectory,
storageDirectory: applicationSupport.appendingPathComponent("my-workspace"),
project: savedProjectID,
instructions: "Help edit this video using the application's tools.",
tools: tools
)
// Retain both objects. Persist the session ID to reopen the conversation.
let connection = workspace.connect(provider: .codex, session: savedSessionID)
let conversation = AgentConversationViewController(connection: connection)Create UI objects on the main actor. Initialize a workspace off the main actor when loading persisted state. Creating a connection does not start a turn; the first submitted prompt starts the CLI. Use .claude to use Claude Code.
Embed the controller directly in AppKit or retain it in your SwiftUI model and use:
AgentConversationView(controller: conversation)AgentConversationView takes the room its container proposes, so it reflows to an inspector or split-view column. Give it .id(...) per conversation so a new conversation replaces the view.
executables, environment, and instructions customize provider launches. Use a dedicated storage directory for each workspace; an ownership record and exclusive lock prevent accidental reuse or simultaneous writers. The working directory and storage directory are independent.
Embed in a document or folder app
A host with one agent per document needs no records of its own: ProjectId(stableFor:) gives a folder the same ID on every launch, resume(fallback:) reopens the conversation shown last (or starts one), startNew() starts the next one with the last composer choices, and remember(_:) records those choices. A host that saved its own conversation ID before can hand it over once with remember(session:), so moving to resume keeps the person's conversation.
let workspace = try AgentWorkspace(workingDirectory: documentFolder,
storageDirectory: support.appendingPathComponent("Agents/\(ProjectId(stableFor: documentFolder))"),
project: ProjectId(stableFor: documentFolder), tools: tools)
let theme = AgentTheme()
theme.useSystemAppearance() // system colors, accent, light or dark, glass over your background
let conversation = AgentConversationViewController(connection: workspace.resume(), theme: theme, host: host)
conversation.onChange = { [weak conversation] in
if let conversation { workspace.remember(conversation.newConversationPreferences) }
}
// New Conversation: build the next controller from `workspace.startNew()`.Application tools
Application tools default to .applicationOnly access: Claude's built-in tools are disabled; Codex runs read-only with shell execution disabled and no approvals. The host remains responsible for validating arguments, authorizing operations, and committing undoable edits.
Handlers run in order per conversation and should honor cancellation before committing changes. AgentKit deduplicates retried call IDs, displays results, and returns AgentToolResult.images to both the model and UI.
Application mode omits coding-specific commands, plan mode, provider-history import, and file-checkpoint rollback. Use your app's own undo tool. For a coding workspace, omit tools; to combine application and provider tools explicitly, pass access: .providerTools to AgentToolConfiguration.
Filmatte, a native macOS video editor, and the SuperRoutine Mac planner use it this way: their tool catalogs and handlers remain in each app, while AgentKit supplies the UI and the CLI transports. Filmatte's integration tests exercise real text-overlay and timeline edits through each installed provider.
What the conversation includes
- Streaming replies, native Markdown, syntax-highlighted code, tables, math, and diagrams.
- An editable composer with attachments, model and reasoning selection, and plan mode.
- Tool activity, approvals, structured questions, prompt queues, and interruption.
- Search, prompt navigation, context usage, citations, and subagent activity.
- Persistent transcripts and drafts, provider-history import, and supported conversation forks.
- Recorded file changes, Git checkpoints, diff review, and guarded revert operations.
- Local file and media previews, including revision-checked ranged reads.
Provider features vary. The adapters retain each provider's behavior rather than simulating unsupported operations. AgentConnection.capabilities controls optional UI features; .steering offers Send Now, which hands a queued prompt or a draft, through the sendAgentPromptNow shortcut, to the running turn instead of queueing it. The composer shows one action at a time: Send while there is a draft, Stop while the agent works, else Dictate. Host-specific actions such as opening another conversation, launching a terminal, or previewing a pull request require host services.
How much of the agent's work shows is the person's choice, from the conversation's context menu under Tool Calls: Show All, Hide Successful (a call shows while it runs and stays only if it fails), Hide All, or Zen (each prompt, then the turn's final reply). Approvals, questions, failures, plans and task lists always show, and Find shows everything while it is open. The choice is remembered for the app; set AgentToolCallVisibility.current to choose it for the person.
Connect your app
Pass AgentHostServices when constructing the controller to connect its actions to your application. File paths are resolved against the conversation's working directory.
var host = AgentHostServices(
directory: { workingDirectory.path },
isLocal: { true }
)
host.openFile = { path, line, column in
editor.open(path: path, line: line, column: column)
}
host.openBrowser = { url in browser.open(url) }
host.runCommand = { command in terminal.run(command) }
host.remoteImages = { .clickToLoad }
host.showNotice = { message, style in notices.show(message, isError: style == .error) }
let conversation = AgentConversationViewController(connection: connection, host: host)Local connections supply file reads and file suggestions automatically. Remote hosts can supply their own asynchronous file service. Navigation, repository metadata, pull request previews, workspace labels and notices are optional callbacks; without showNotice, notices appear in an AgentKit notice stack in the window, if it has one.
Repository metadata is read once per connection: an error with an AgentCodedError code, such as a folder outside Git, holds until connectionChanged(), while an uncoded failure is retried. Bind menus and shortcuts by passing an AgentShortcut to conversation.perform(_:); map your own command identifiers explicitly, since AgentShortcut's raw values are AgentKit's.
Choose providers
Each AgentChatProvider kind describes its CLI through spec: executable, wire protocol, install and sign-in commands. Claude Code and Codex use their own streaming protocols; the other kinds speak the Agent Client Protocol, and .acp runs any ACP agent you name.
workspace.providers, an AgentProviderStore, keeps the configured providers in the storage directory's agent-providers.json. It lists only the providers the person added; a file older builds filled with every built-in kind keeps just the ones they changed. write adds providers, such as a second Claude account with its own home folder, or changes executables, arguments, environment, accent colors and model preferences. check() and refreshingState() report whether each CLI is installed, its version and sign-in, and maintain installs or updates it. Pass a provider's ID to start a conversation on it:
let connection = workspace.connect(provider: .claude, providerID: "claude-work", session: savedSessionID)The model menu chooses the model and its reasoning effort, nothing else: each enabled provider's logo with its models in a submenu, then an Effort submenu. A provider that can't run says why on its row; it is fixed in agent settings, not from the menu. Models reload when the menu opens after a minute, and whenever Notification.Name.agentProviderSettingsDidChange is posted: AgentKit's settings post it after a change or a model refresh, and a host posts it after changing providers elsewhere. When the host supplies AgentHostServices.openAgentSettings, a new conversation with no provider added offers to add one in place of its composer; without it, a backend with no providers keeps offering the built-in kinds. Choosing another provider for a conversation that has begun hands it over: after the person confirms, the next message sends the new provider the conversation so far, because one provider can't resume another's. workspace.usageLimits() reads Claude and Codex plan limits; a custom transport offers both through AgentConnection.providers and usageLimits.
Agent settings
Agent settings come in two layers, so an app can use AgentKit's or draw its own:
AgentProvidersModelis the settings without views: anObservableObjectover anAgentProviderManagementwith the providers, their checks, installs and models, and every change settings make —add,update,remove,install,updateCLI,signIn,setArguments,setVariable,loadModels,setFavorite,setShown,move,addCustomModeland more. Changes show at once and save in order; a failed one puts the reason inerrors[field].presentAddProvider(on:)shows AgentKit's Add Provider form for any view.AgentSettingsView(SwiftUI) andAgentSettingsWindowControllerdraw it as AgentKit's settings: the providers with each one's status, a page per provider with its version and install or update, sign-in, name, accent color, executable, folders, launch arguments, Claude's auto-compact size, variables and models, which can be favorited, reordered, hidden, refreshed or added by ID, and the Add Provider form in three steps — the kind of agent, its label, ID and accent color, then how it runs and signs in — which checks the CLI and sign-in as it is filled in and keeps a second account in a folder of its own.
AgentSettingsWindowController.show(workspace.providerManagement) // AgentKit's window
conversation.showAgentSettings() // the conversation's backend
let providers = AgentProvidersModel(workspace.providerManagement) // your own views
providers.startMonitoring()
providers.update("claude-work", .name) { $0.name = "Work" }A conversation whose connection has providerManagement opens AgentKit's window when no provider is added; AgentWorkspace supplies one. Pass one AgentProviderStore as providers to every AgentWorkspace so the person adds providers once for the app rather than once per workspace. A host with its own settings sets AgentHostServices.openAgentSettings and addAgentProvider instead, and a remote backend supplies its own AgentProviderManagement, naming its computer. Sign-in runs through AgentHostServices.runCommand, or in Terminal without it.
Conversation history
AgentConversationHistory lists the conversations a new one can continue: those kept in the library, archived or cleared, then those a provider's CLI saved for the folder. load() reads them, search(_:) filters, continue(_:in:) reopens or imports one, and delete(_:) removes a kept one for good.
conversation.showHistory(), like /resume, shows AgentKit's history picker. To draw your own, set AgentHostServices.presentHistory; it receives the history and a closure that continues the chosen entry as the picker would — taking over an unused conversation, else opening beside it through onShowConversation. conversation.makeHistory() gives the history for a view outside any conversation's flow.
host.presentHistory = { history, choose in
Task { try await history.load(); myHistoryView.show(history.entries, onPick: choose) }
}New conversations
An empty conversation is AgentKit's new-conversation screen: the composer with the model menu, starting with the provider, model and effort it is given. conversation.newConversationPreferences holds those of an open one, so /new and a New Conversation command can start the next one the same way:
conversation.onNewConversation = { [weak conversation] in
let start = conversation?.newConversationPreferences
let next = AgentConversationViewController(connection: workspace.connect(provider: start?.provider ?? .claude, providerID: start?.providerID))
if let start { next.restorePreferences(defaults: nil, draft: start) { _ in } }
// show `next` in a window, tab or pane of your own
}AgentNewConversation chooses outside a conversation, such as in a toolbar: it reads the enabled providers and their models from an AgentProviderManagement or a connection, keeps the chosen preferences, and makeMenu() builds the same model and effort menu for a button of your own.
Themes
Use AgentTheme to select light/dark palettes and appearance. Each controller can receive its own theme, and its provider marks, link icons and controls follow it; followSystem() observes appearance changes without polling. An application with one theme can apply it to AgentTheme.shared and pass that to every controller.
Match your app's style
AgentStyle adapts the conversation to the app around it: font families and sizes, spacing, corner radii, control sizes and color overrides. Apply it with setStyle(_:) before building controllers:
var style = AgentStyle()
style.typography.fontFamily = "Inter" // nil keeps SF; a missing family falls back to it
style.typography.monospacedFontFamily = "JetBrains Mono"
style.typography.fontSize = 13 // chrome body; other chrome sizes scale with it
style.typography.conversationFontSize = 15 // message body; headings and code scale with it
style.spacing.message = 20 // between turns
style.spacing.readableWidth = 720 // widest conversation column
style.radii.composer = 12 // or .uniform(0) for square corners
style.colors = .init(
light: ChromePaletteOverrides(background: ChromeColor(hex: 0xFFFFFF), accent: ChromeColor(hex: 0x4F46E5)),
dark: ChromePaletteOverrides(accent: ChromeColor(hex: 0x818CF8))
)
theme.setStyle(style)To draw exactly as a native Mac app does, call theme.useSystemAppearance(): it sets .system colors, draws diffs and terminal output with the system's red, green and yellow, follows the light or dark appearance and lets your background show through glass panes, keeping your style's typography and spacing. For the chrome colors alone, set style.colors = .system: the conversation draws with the system's semantic colors (window background, label colors, separators, red, orange and green) and the user's accent color, resolved for the theme's light or dark appearance, and recolors when the user changes the accent. Light and dark overrides still apply on top, such as colors.dark.accent.
Overriding a base color (background, foreground or accent) derives its tints again (muted text, borders, hover, the accent's soft fill and the text drawn on it) unless you override those too. Light overrides apply while the theme in use is light, and dark ones while it is dark.
Typography, spacing and radii are app-wide: the last style set wins, so give every theme the same one. Color overrides belong to the theme they are set on. Conversation text, spacing and colors update live; chrome fonts and radii apply to views built after the change.
Own the lifecycle
Hiding a view does not cancel the agent. This allows multiple conversations and background work. For an explicit close, first ask canClose(), then call closeConversation() and dispose() after the host commits to closing it.
Before application termination:
- Await
conversation.flushDraft()for each controller. - Dispose the conversation controllers.
- Run
workspace.shutdown()off the main actor and wait for it to return.
While any conversation works or runs agents, the workspace keeps the Mac from idle-sleeping, though its display may sleep; set keepsMacAwakeWhileWorking to false to leave sleep to the system. A provider process idle for 20 minutes stops, and the next message starts it again on the same provider conversation where the provider can resume one. A retry scheduled for a usage limit's reset keeps wall-clock time, so a Mac that slept through the reset sends it as it wakes, and it survives a restart.
Shutdown interrupts running work, saves state, finishes observers, and releases the workspace lock. It is idempotent. A turn it cut short carries on by itself the next time the workspace opens, as one cut short by a crash does, unless the person was stopping it or three such resumes in a row made no progress. The example demonstrates an AppKit termination handler that keeps the main run loop available while the draft is saved. An agent cannot outlive its host process without an application-owned helper or daemon.
Use your own transport
AgentUI depends only on AgentCore. Construct an AgentConnection with a request closure and an observation-stream factory, plus whichever optional services your backend supports. Each observer must receive its own stream. Revision notifications can coalesce; the UI reconciles authoritative snapshots and deltas.
This lets a desktop UI talk to a separate local helper or remote server while the helper alone links AgentRuntime. The package has no dependency on Tab's daemon, sockets, workspace layout, terminal engine, or application model.
For an application-owned transport, build an AgentConnection and provide host navigation through AgentHostServices. Implement AgentCodedError on transport errors so the UI can distinguish unsupported services and missing conversations, and set backendAdvice to tell people how to update your server when it predates a service, such as "Update Tab on it, then restart it."
Serve multiple projects
AgentRuntimeService owns a shared conversation store for hosts with multiple projects or a socket/SSH transport. Supply a project-to-directory resolver and optional AgentLaunchContext for application instructions and environment values. Route agent requests through handle, conversation, attachment, checkpoint, modelCatalog, composerContext, history, and importHistory. Forward revision notifications from changed to remote clients, or use independent observe streams. AgentWorkspace uses this same runtime with a single project resolver.
The service accepts an existing conversation directory directly. It preserves snapshot, transcript, attachment, checkpoint, and queue formats; clearing archives prior resources before resetting the original session.
The service locks its store; a second owner fails with FileLock.Failure.held, and other lock failures throw. A host that already owns the store exclusively, such as a server holding its own profile lock, passes hostOwnsStore: true to serve a store it can't lock, such as a read-only folder. Runtime errors go to unified logging; AgentRuntimeLog.setErrorHandler also sends them to your own log.
Call refuseNewRequests before host shutdown, then shutdown off the main thread: it waits until every provider it started has exited, including model and command discovery, and every checkpoint being taken and revert under way is written, then flushes and releases the store, which can be opened again once it returns. It needs no free Swift task worker, so tasks may call it together. tryRefuseIfIdle reserves shutdown atomically only when no conversation is live.
A client-server host can use all three products this way: AgentCore on its wire, AgentRuntime in its server, and AgentUI in its desktop adapter.
Conversation commands
Use /help for the supported commands and /skills to refresh installed skills. /clear resets the current conversation and archives its history; /new opens a conversation through the host. /compact uses provider compaction, /fork requires a host that can open another conversation, and /copy and /export include retained paginated history.
Return executes commands; Tab completes them. Commands unavailable in the host preserve the draft and explain the limitation. The command reference lists every command and how it is routed.
Run the example
swift run AgentKitExampleThe default is an offline, streaming UI demo. It does not use a provider account or make model requests. To use a real CLI:
swift run AgentKitExample --provider codex --directory /path/to/project --storage /path/to/agent-state
swift run AgentKitExample --provider claude --directory /path/to/project --storage /path/to/agent-state
# Application-tool example: ask it to change the window title.
swift run AgentKitExample --provider codex --app-tools --directory /tmp --storage /tmp/agentkit-app-demoThe example persists the workspace and conversation identities. To build a native app bundle:
scripts/bundle-example.sh
open 'build/AgentKit Example.app'Validate
scripts/validate.shValidation builds with warnings as errors, runs the XCTest suites, bundles the standalone example, and verifies its ad-hoc signature. Provider tests exercise real local fixture subprocesses without credentials or model usage.
Tests cover streaming, protocol normalization, interruption, queues, persistence, file safety, native rendering, application-tool registration, retry deduplication, and cancellation. Live provider compatibility should also be checked when upgrading a CLI; integration verification records the last live run.
License and notices
AgentKit is MIT licensed. Code and artwork adapted from other projects keep their own licenses, listed in the third-party notices. Every release is described in the changelog.