agent-host-protocol / swift
AGENTS.md386 starsChanged 2 months agoMITView on GitHub
This directory contains two Swift packages for the Agent Host Protocol (AHP): The AgentHostProtocolClient library also ships a multi-host MultiHostClient actor on top of the per-host AHPClient. Single-host consumers can use MultiHostClient.single(_:) to get the same observability surface (event streams, generation-checked handles, persistent client ids) without thinking about a registry. See Sources/AgentHostProtocolClient/Hosts/. Types in AgentHostProtocol/Sources/AgentHostProtocol/Generated/ are auto-generated from the TypeScript definitions in types/. Do not edit these files directly. Generated files are committed to source control so the package is…
- Commits and pushes
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository10 other files it gives its agents.
- AGENTS.mdAGENTS.md
- clients/dotnet/AGENTS.mdAGENTS.md
- clients/go/AGENTS.mdAGENTS.md
- clients/kotlin/AGENTS.mdAGENTS.md
- docs/guide/agents.mdAGENTS.md
- channels-migrationSkill
- ahp-clientSkill
- session-metadata-migrationSkill
- groom-backlogSkill
- release-ahpSkill
The file
We split this AGENTS.md into the rules it gives an agent
4 rules. About 0 are common, 1 is distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 32
Update clients/swift/VERSION to the new bare semver string.
- Very specific: line 33
Run npm run generate:metadata and commit the regenerated clients/swift/release-metadata.json.
- Very specific: line 43
Add it as a dependency in your Package.swift:
- Distinctive: line 114
When the phone wakes from background or the WebSocket drops unexpectedly:
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Swift Examples — Agent Guide
Overview
This directory contains two Swift packages for the Agent Host Protocol (AHP):
- AgentHostProtocol — A pure Swift library (no external dependencies) providing auto-generated types, actions, and reducers for the protocol. Targets iOS 16+, macOS 13+, Swift 5.9+. The Swift sources live in
clients/swift/AgentHostProtocol/, but thePackage.swiftmanifest lives at the repository root (/Package.swift) so that external consumers can pull this in via.package(url:). SwiftPM only resolves manifests at the root of a remote git repository. - AHPApp — An example iOS app (Xcode project) demonstrating a full AHP client with WebSocket transport, state synchronization, reconnection, and a SwiftUI chat UI. Uses dev-tunnels-swift (remote Swift Package) for tunnel discovery, authentication, and relay connections.
The AgentHostProtocolClient library also ships a multi-host MultiHostClient actor on top of the per-host AHPClient. Single-host consumers can use MultiHostClient.single(_:) to get the same observability surface (event streams, generation-checked handles, persistent client ids) without thinking about a registry. See Sources/AgentHostProtocolClient/Hosts/.
Code Generation
Types in AgentHostProtocol/Sources/AgentHostProtocol/Generated/ are auto-generated from the TypeScript definitions in types/. Do not edit these files directly. Generated files are committed to source control so the package is consumable via SwiftPM without a code-generation toolchain.
To regenerate after protocol changes:
npm run generate:swift # runs: tsx scripts/generate.ts --swiftGenerated files: State, Commands, Actions, Errors, Messages, Notifications — all suffixed .generated.swift.
CI verifies that the committed generated files match the output of npm run generate:swift and fails on drift.
Releasing
The Swift package is consumed via SwiftPM by git-tag resolution against this repository. Bare vX.Y.Z tags at the repo root are reserved for Swift releases because SwiftPM cannot resolve path-prefixed tags like swift/v0.2.0; see RELEASING.md for the tag-namespace rationale and the full release flow.
Summary, scoped to Swift:
- Update
clients/swift/VERSIONto the new bare semver string. - Run
npm run generate:metadataand commit the regeneratedclients/swift/release-metadata.json. - Rotate the
## [Unreleased]section ofclients/swift/CHANGELOG.md. The publish workflow fails if no## [X.Y.Z]heading exists for the tag version. - Merge to
main. - Tag:
git tag v0.X.Y && git push origin v0.X.Y(note: bare semver, no prefix). .github/workflows/publish-swift.ymlvalidates the tag againstclients/swift/VERSION, re-runs the Swift generator drift check, builds and tests the Swift package on macOS, then publishes a GitHub Release.
AgentHostProtocol Library
Installing via Swift Package Manager
Add it as a dependency in your Package.swift:
.package(url: "https://github.com/microsoft/agent-host-protocol.git", from: "0.1.0")…and reference the AgentHostProtocol product from your target:
.target(
name: "MyApp",
dependencies: [
.product(name: "AgentHostProtocol", package: "agent-host-protocol"),
]
),In Xcode: File ▸ Add Package Dependencies… and enter https://github.com/microsoft/agent-host-protocol.
Key Types
RootState— Top-level state: agents list + active sessions.SessionState— Per-session conversation state (turns, tool calls, lifecycle).AgentInfo/SessionModelInfo— Agent capabilities and available models.ActionEnvelope— Server-sent action withserverSeq(global monotonic counter) and resource URI.- Command params/results —
InitializeParams,ReconnectParams,CreateSessionParams,SubscribeParams, etc.
Reducer Pattern
Inspired by Swift Composable Architecture (TCA). Key abstractions:
Reducerprotocol — Pure function:reduce(into state: inout State, action: Action).AHPRootReducer— Handles root-level actions (agents changed, session added/removed).AHPSessionReducer— Handles per-session actions (deltas, tool calls, turn lifecycle).- Composable via
CombinedReducerandAnyReducertype erasure.
Reducers are pure functions — replaying actions in serverSeq order on any prior state snapshot produces identical results. This is critical for the reconnection protocol.
AHPApp
Architecture
AHPAppMain (@main, scenePhase monitoring)
└─ AppStore (@Observable, @MainActor)
├─ AHPConnection (actor — WebSocket JSON-RPC transport)
├─ RootState + [SessionState] (protocol state, mutated by reducers)
├─ ServerStorage (persisted server configs)
└─ Views (SwiftUI)AppStore
Central state container. All mutations flow through reducer functions (applySnapshot, handleAction). Key responsibilities:
- Connection lifecycle —
connect(),disconnect(),reconnect(),reconnectIfNeeded() - Session management —
createSession(),disposeSession(),selectSession() - State sync — Receives
ActionEnvelopes from the connection, applies via reducers - Reconnection — Tracks
lastSeenServerSeqand subscribed URIs; sendsreconnectcommand on resume. Server responds with either replay (missed actions) or snapshot (fresh state).
AHPConnection
An actor wrapping URLSessionWebSocketTask for thread-safe JSON-RPC over WebSocket:
- Request/response correlation via sequential message IDs and
CheckedContinuation onActioncallback deliversActionEnvelopes to AppStore on@MainActoronUnexpectedDisconnectfires when the receive loop breaks on errorcanReconnect— true when a prior connection establishedserverSeq+ subscriptions
Reconnection Flow
When the phone wakes from background or the WebSocket drops unexpectedly:
scenePhase → .activetriggersreconnectIfNeeded()(oronUnexpectedDisconnect)- Client sends
reconnect(clientId, lastSeenServerSeq, subscriptions)to server - Server responds with Replay (array of missed
ActionEnvelopes) or Snapshot (full state per subscribed URI if gap is too large) AppStoreapplies the result via reducers, bringing local state up to date- A floating progress bar shows "Reconnecting…" in the active chat view
serverSeq is a global monotonic counter across all sessions. The server filters replays to only the client's subscribed URIs.
UI Structure
- ContentView — NavigationStack root, routes to sidebar or chat.
- SidebarView — Session list with
.searchable()(iOS 26 liquid glass bottom bar), grouped by time or working directory.NewSessionButtonopensAgentPickermodal. - ChatView — VStack-based message list with bottom-anchored scroll, scroll-to-bottom button (glass effect on iOS 26), reconnect progress bar, and unified input bar (send/stop).
- AgentPicker — Form with
Pickercontrols for agent, model, and a working directory text field. - ResponsePartView — Renders markdown (via
AttributedString), tool call cards (tap → detail modal with inputs/outputs), reasoning blocks, and content references.
iOS 26 Adaptations
The app uses #available(iOS 26.0, *) checks for:
.glassEffect()on the scroll-to-bottom button.searchable()with.toolbarplacement +DefaultToolbarItem(kind: .search, placement: .bottomBar)- New Session button in
.bottomBartoolbar - Fallbacks to
.ultraThinMaterialand.navigationBarDraweron older iOS
Testing
- AHPAppTests — Reconnection state tests: snapshot restore, replay ordering, empty replay, multi-resource snapshot, live action application.
- AgentHostProtocol Tests — Reducer unit tests (root reducer, session reducer, native reducer).
Build & Run
Open AHPApp/AHPApp.xcodeproj in Xcode. The project references AgentHostProtocol as a local Swift package whose manifest lives at the repository root (../../.. relative to the Xcode project), and DevTunnelsClient as a remote Swift package from rebornix/dev-tunnels-swift. Code signing requires a Signing.local.xcconfig file (see Config/Signing.local.xcconfig.example).
Dev Tunnels integration: TunnelListView.swift uses the DevTunnelsClient library directly — TunnelManagementClient for tunnel listing/details, DeviceCodeAuth for GitHub OAuth, and TunnelConnection helpers for relay URIs and connect tokens. All calls are async — no shim layer or Rust FFI needed.
For development, AHPApp uses a native NWConnection WebSocket transport instead of URLSessionWebSocketTask, avoiding URLSession ATS enforcement for direct ws:// development targets such as local LAN addresses or Tailscale tailnet IPs. Public or internet-exposed deployments should still prefer wss://.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

