### OpenCode Discovery Probe Setup Source: https://github.com/afollestad/agentclikit/blob/main/docs/examples.md Creates a DefaultAgentHarnessDiscoveryService with a shared OpenCodeDiscoveryProbe. Use the selected AgentModelOption.model unchanged and pass a native variant's value as AgentSpawnConfig.effort. Check supportsReadOnlyOneShotPrompts before offering utility generation; OpenCode requires an exact provider/model and uses a disposable profile with native read-only tools. ```swift import AgentCLIKit func openCodeDiscovery() -> DefaultAgentHarnessDiscoveryService { let probe = OpenCodeDiscoveryProbe() return DefaultAgentHarnessDiscoveryService( harnessSetups: [OpenCodeHarnessSetup(probe: probe)], modelOptionSource: DefaultAgentModelOptionSource( openCodeSource: OpenCodeModelOptionSource(probe: probe) ) ) } ``` -------------------------------- ### Start a one-off runtime conversation with DefaultAgentRuntime Source: https://github.com/afollestad/agentclikit/blob/main/docs/examples.md Use this to start a single harness conversation, send one message, and print common events (message, delta, reasoning, tool call, tool result, lifecycle). It also marks events as persisted. The example uses the .claude harness; change to .codex to run through Codex App Server. ```swift import AgentCLIKit import Foundation func runOneOffConversation(projectURL: URL) async throws { let runtime = DefaultAgentRuntime() let conversationId = AgentConversationID(rawValue: "one-off-\(UUID().uuidString)") let subscription = await runtime.subscribe(conversationId: conversationId, afterIndex: nil) let eventTask = Task { for await envelope in subscription.events { switch envelope.event { case .message(let message): print("\(message.role.rawValue): \(message.text)") case .messageDelta(let delta): print(delta.text, terminator: "") case .reasoning(let reasoning): print("Reasoning: \(reasoning.text)") case .toolCall(let toolCall): print("Tool call: \(toolCall.name)") case .toolResult(let result): print("Tool result: \(result.content)") case .lifecycle(let lifecycle): print("Lifecycle: \(lifecycle.state.rawValue)") default: break } await runtime.markPersisted( conversationId: conversationId, generation: envelope.generation, upTo: envelope.index ) } } try await runtime.spawn( conversationId: conversationId, config: AgentSpawnConfig( harnessId: .claude, workingDirectory: projectURL ) ) try await runtime.send( .userMessage(AgentMessageInput(text: "List the main modules in this package.")), conversationId: conversationId ) try await Task.sleep(nanoseconds: 2_000_000_000) eventTask.cancel() await runtime.shutdown() } ``` -------------------------------- ### Run agent conversation with AgentCLIKit runtime Source: https://github.com/afollestad/agentclikit/blob/main/README.md Complete example that subscribes before spawning, starts a harness, sends one message, handles common events, acknowledges persisted event indexes, and shuts down runtime resources. In a real app, keep event/status tasks alive for the conversation lifetime, persist envelopes before calling markPersisted, and resolve interaction events from your UI. ```swift import AgentCLIKit import Foundation func runAgentConversation( projectURL: URL, harnessId: AgentHarnessID = .claude ) async throws { let sessionsURL = projectURL.appendingPathComponent(".agentclikit-sessions.json") let runtime = DefaultAgentRuntime( sessionStore: JSONFileAgentSessionStore(fileURL: sessionsURL) ) let conversationId = AgentConversationID(rawValue: "readme-\(UUID().uuidString)") let subscription = await runtime.subscribe( conversationId: conversationId, afterIndex: nil ) let eventTask = Task { for await envelope in subscription.events { switch envelope.event { case .message(let message): print("\(message.role.rawValue): \(message.text)") case .messageDelta(let delta): print(delta.text, terminator: "") case .toolCall(let toolCall): print("Tool: \(toolCall.name)") case .contextCompaction(let compaction): print("Compaction \(compaction.id): \(compaction.phase.rawValue)") case .subAgent(let subAgent): print("Sub-agent: \(subAgent.phase.rawValue) \(subAgent.description ?? subAgent.id)") case .sessionMetadata(let metadata): if let name = metadata.name { print("Session name: \(name)") } else if let preview = metadata.preview { print("Session preview: \(preview)") } case .interaction(let interaction): print("Waiting for \(interaction.kind.rawValue): \(interaction.prompt)") case .lifecycle(let lifecycle): print("Lifecycle: \(lifecycle.state.rawValue)") default: break } await runtime.markPersisted( conversationId: conversationId, generation: envelope.generation, upTo: envelope.index ) } } try await runtime.spawn( conversationId: conversationId, config: AgentSpawnConfig( harnessId: harnessId, workingDirectory: projectURL ) ) try await runtime.send( .userMessage(AgentMessageInput(text: "Summarize this project.")), conversationId: conversationId ) try await Task.sleep(nanoseconds: 2_000_000_000) eventTask.cancel() await runtime.shutdown() } ``` -------------------------------- ### Build Harness Picker Model from Discovery Status Source: https://github.com/afollestad/agentclikit/blob/main/docs/examples.md Use this snippet to load harness choices for a project. It creates harness setups, discovers statuses and ordering, then maps them into a HarnessChoice struct. Use the selected AgentModelOption.model and effort option value in AgentSpawnConfig.model and AgentSpawnConfig.effort. If a model has no supportedEffortOptions, hide effort controls; use supportsSpeedMode before showing a Fast speed control. ```swift import AgentCLIKit import Foundation struct HarnessChoice { let harnessId: AgentHarnessID let displayName: String let isReady: Bool let supportsSpeedMode: Bool let modelLabels: [String] let defaultEffort: String? } func loadHarnessChoices(projectURL: URL) async -> [HarnessChoice] { let setups: [any AgentHarnessSetup] = [ ClaudeHarnessSetup(configStore: ClaudeConfigStore()), CodexHarnessSetup() ] let discovery = DefaultAgentHarnessDiscoveryService( harnessSetups: setups, modelOptionSource: DefaultAgentModelOptionSource( codexSource: CodexAppServerModelOptionSource() ) ) let statuses = await discovery.harnessStatuses(projectURL: projectURL) let ordering = await discovery.stableHarnessOrdering() return ordering.compactMap { harnessId in guard let status = statuses[harnessId] else { return nil } return HarnessChoice( harnessId: harnessId, displayName: status.definition?.displayName ?? harnessId.rawValue, isReady: status.isReadyInProject, supportsSpeedMode: status.definition?.capabilities.supportsSpeedMode ?? false, modelLabels: status.modelOptions.map(\.label), defaultEffort: status.modelOptions.first(where: \.isDefault)? .defaultEffortOption? .value ) } } ``` -------------------------------- ### Initialize DefaultAgentModelOptionSource with Codex source Source: https://github.com/afollestad/agentclikit/blob/main/docs/harness-reference.md Creates a DefaultAgentModelOptionSource with a CodexAppServerModelOptionSource for Codex. The Codex source queries App Server model/list on demand, caches results briefly, and falls back to static options when live listing fails or returns no models. It starts a temporary App Server transport only when called with a missing or expired cache. ```swift let source = DefaultAgentModelOptionSource( codexSource: CodexAppServerModelOptionSource() ) ``` -------------------------------- ### Run a sessionless one-shot prompt with DefaultAgentOneShotPromptRunner Source: https://github.com/afollestad/agentclikit/blob/main/docs/examples.md Use this to run a single harness prompt without creating a runtime conversation or persisted session. The result is the final assistant text. The example uses the .codex harness; switch to .claude for Claude Code or .opencode with an explicit model for OpenCode. One-shot prompts are read-only and cannot answer approval or prompt requests. ```swift import AgentCLIKit import Foundation func runSessionlessPrompt(projectURL: URL) async throws -> String { let runner = DefaultAgentOneShotPromptRunner() let result = try await runner.generate(AgentOneShotPromptRequest( harnessId: .codex, workingDirectory: projectURL, prompt: "Summarize the current Git diff in one paragraph.", timeout: 120 )) return result.text } ``` -------------------------------- ### Trust a project with DefaultAgentProjectTrustService Source: https://github.com/afollestad/agentclikit/blob/main/README.md Use when the user chooses to trust a project. Creates a DefaultAgentProjectTrustService with the harness setups and calls trustProject for the .codex harness and project URL. ```swift let trustService = DefaultAgentProjectTrustService(setups: setups) try await trustService.trustProject(harnessId: .codex, projectURL: projectURL) ``` -------------------------------- ### Run validation scripts Source: https://github.com/afollestad/agentclikit/blob/main/README.md Runs the build, test, lint, and package consumer validation scripts from the repository root. The build and test scripts pipe xcodebuild through xcsift when installed, and the package consumer script builds a temporary package that imports the library product. ```sh ./scripts/build.sh ./scripts/test.sh ./scripts/lint.sh ./scripts/validate-package-consumer.sh ``` -------------------------------- ### Check and Update Project Trust State Source: https://github.com/afollestad/agentclikit/blob/main/docs/examples.md Uses DefaultAgentProjectTrustService with Claude and Codex harness setups to check trust status and trust the project if not trusted. Trust writes to .claude.json for Claude and Codex's user-level config.toml for Codex. ```swift import AgentCLIKit import Foundation func trustProjectIfNeeded(harnessId: AgentHarnessID, projectURL: URL) async throws -> AgentProjectTrustStatus { let setups: [any AgentHarnessSetup] = [ ClaudeHarnessSetup(configStore: ClaudeConfigStore()), CodexHarnessSetup() ] let trustService = DefaultAgentProjectTrustService(setups: setups) let status = await trustService.status(harnessId: harnessId, projectURL: projectURL) guard status == .notTrusted else { return status } try await trustService.trustProject(harnessId: harnessId, projectURL: projectURL) return await trustService.status(harnessId: harnessId, projectURL: projectURL) } ``` -------------------------------- ### Create runtime with host tool and additional roots Source: https://github.com/afollestad/agentclikit/blob/main/docs/examples.md Use this snippet to set up a DefaultAgentRuntime with a read-only host tool and additional workspace roots. The handler returns a bounded text/structured response and defers reconfiguration with .nextTurnRequired during an active turn. Production handlers should strictly decode the advertised schema and apply product authorization. ```swift import AgentCLIKit import Foundation func makeRuntimeWithHostTools() -> (DefaultAgentRuntime, AgentSpawnConfig) { let tool = AgentHostToolDefinition( name: "list_jobs", description: "Lists jobs owned by this host application when the user asks about them.", inputSchema: .object([ "type": .string("object"), "properties": .object([:]), "additionalProperties": .bool(false) ]), annotations: AgentHostToolAnnotations( readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false ) ) let runtime = DefaultAgentRuntime(hostToolHandling: AgentHostToolHandling { context, call in guard call.name == "list_jobs" else { return AgentHostToolResult(text: "Unknown tool.", isError: true) } return AgentHostToolResult( text: "No jobs are configured for \(context.conversationId.rawValue).", structuredContent: .object(["jobs": .array([])]) ) }) let config = AgentSpawnConfig( harnessId: .claude, workingDirectory: URL(fileURLWithPath: "/tmp/agent-workspace"), additionalWorkspaceRoots: [URL(fileURLWithPath: "/tmp/shared-input")], hostToolServer: AgentHostToolServerMetadata( name: "example_host", instructions: "Use these tools only for jobs owned by the example host." ), hostTools: [tool] ) return (runtime, config) } ``` -------------------------------- ### Run Swift adapter integration tests Source: https://github.com/afollestad/agentclikit/blob/main/scripts/opencode-live-validation.md Runs the Swift adapter integration checks against the same OpenCode executable. Covers typed events, lifecycle, and native HTTP behavior using the same isolated local fixture provider. ```sh AGENTCLIKIT_OPENCODE_BINARY=/absolute/path/to/opencode swift test --filter OpenCodeLiveAdapterTests ``` -------------------------------- ### Run macOS demo Source: https://github.com/afollestad/agentclikit/blob/main/README.md Executes the demo app script from the repository root. The demo builds and launches AgentCLIKitDemo, showcasing harness readiness, model/effort/speed selection, session records, live output, status snapshots, cancellation, Claude prompt handling, and Codex live model loading. ```sh ./scripts/run-demo.sh ``` -------------------------------- ### Set Fast Mode with AgentSpawnConfig Source: https://github.com/afollestad/agentclikit/blob/main/docs/examples.md Enables Codex fast mode by setting speedMode to .fast or .standard. First checks harnessStatus.definition?.capabilities.supportsSpeedMode before updating. Requires a concrete AgentSpawnConfig.model for Codex plan mode. ```swift func setFastMode( enabled: Bool, currentConfig: AgentSpawnConfig, conversationId: AgentConversationID, runtime: any AgentRuntime, harnessStatus: AgentHarnessStatus ) async throws { guard harnessStatus.definition?.capabilities.supportsSpeedMode == true else { return } let updatedConfig = AgentSpawnConfig( harnessId: currentConfig.harnessId, workingDirectory: currentConfig.workingDirectory, arguments: currentConfig.arguments, environment: currentConfig.environment, model: currentConfig.model, effort: currentConfig.effort, permissionMode: currentConfig.permissionMode, collaborationMode: currentConfig.collaborationMode, speedMode: enabled ? .fast : .standard, sessionFork: currentConfig.sessionFork, forkSession: currentConfig.forkSession, initialPrompt: nil ) let result = try await runtime.reconfigure(conversationId: conversationId, config: updatedConfig) handleReconfigureResult(result, updatedConfig) } ``` -------------------------------- ### Set Plan Mode with AgentSpawnConfig Source: https://github.com/afollestad/agentclikit/blob/main/docs/examples.md Updates collaborationMode to .plan or .default while preserving other settings. Requires a concrete AgentSpawnConfig.model for Codex plan mode. Keep initialPrompt nil for settings-only reconfigure. ```swift func setPlanMode( enabled: Bool, currentConfig: AgentSpawnConfig, conversationId: AgentConversationID, runtime: any AgentRuntime ) async throws { let updatedConfig = AgentSpawnConfig( harnessId: currentConfig.harnessId, workingDirectory: currentConfig.workingDirectory, arguments: currentConfig.arguments, environment: currentConfig.environment, model: currentConfig.model, effort: currentConfig.effort, permissionMode: currentConfig.permissionMode, collaborationMode: enabled ? .plan : .default, sessionFork: currentConfig.sessionFork, forkSession: currentConfig.forkSession, initialPrompt: nil ) let result = try await runtime.reconfigure( conversationId: conversationId, config: updatedConfig ) switch result { case .appliedInPlace, .restarted: rememberCurrentConfig(updatedConfig) case .nextTurnRequired: stageConfigForNextTurn(updatedConfig) } } ``` -------------------------------- ### Run OpenCode live validation script Source: https://github.com/afollestad/agentclikit/blob/main/scripts/opencode-live-validation.md Runs the pinned OpenCode executable (version 1.18.31) against a deterministic local model. Creates an isolated home and XDG trees and uses temporary Git worktrees; never reads user credentials or calls a paid model. Use --record PATH to write sanitized HTTP responses and source-session SSE events. ```sh python3 scripts/validate-opencode-live.py --binary /absolute/path/to/opencode ``` -------------------------------- ### Use path dependency for local development Source: https://github.com/afollestad/agentclikit/blob/main/README.md For local app development, prefer a path dependency pointed at the AgentCLIKit checkout. This allows you to use the local version of the package. ```swift .package(path: "../AgentCLIKit") ``` -------------------------------- ### Add AgentCLIKit library product to target Source: https://github.com/afollestad/agentclikit/blob/main/README.md Adds the AgentCLIKit library product to a macOS target's dependencies. This is required to link against the package. ```swift .product(name: "AgentCLIKit", package: "AgentCLIKit") ``` -------------------------------- ### Persist and Resume Sessions with JSONFileAgentSessionStore Source: https://github.com/afollestad/agentclikit/blob/main/docs/examples.md Use this snippet to persist harness session IDs across app launches. It creates a JSONFileAgentSessionStore, subscribes to events, and sends a message. The runtime records session IDs and hosts should persist their latest event cursor to pass as afterIndex after restart. ```swift import AgentCLIKit import Foundation func sendWithPersistedSession(projectURL: URL, lastPersistedIndex: Int?) async throws { let sessionsURL = projectURL.appendingPathComponent(".agentclikit-sessions.json") let sessionStore = JSONFileAgentSessionStore(fileURL: sessionsURL) let runtime = DefaultAgentRuntime(sessionStore: sessionStore) let conversationId = AgentConversationID(rawValue: "workspace-main") let subscription = await runtime.subscribe( conversationId: conversationId, afterIndex: lastPersistedIndex ) let eventTask = Task { for await envelope in subscription.events { if case .message(let message) = envelope.event { print(message.text) } await runtime.markPersisted( conversationId: envelope.conversationId, generation: envelope.generation, upTo: envelope.index ) } } try await runtime.spawn( conversationId: conversationId, config: AgentSpawnConfig( harnessId: .claude, workingDirectory: projectURL ) ) try await runtime.send( .userMessage(AgentMessageInput(text: "Continue from the previous session.")), conversationId: conversationId ) try await Task.sleep(nanoseconds: 2_000_000_000) eventTask.cancel() await runtime.shutdown() } ``` -------------------------------- ### Handle Runtime Interaction Events Source: https://github.com/afollestad/agentclikit/blob/main/docs/examples.md Handles AgentInteractionEvent by resolving approvals, prompts, and plan mode exits through the runtime. Uses AgentInteractionResolution with appropriate outcomes and response text. ```swift func handleInteraction( _ interaction: AgentInteractionEvent, conversationId: AgentConversationID, runtime: any AgentRuntime ) async throws { switch interaction.kind { case .approval: let approved = await askUserToApprove(interaction.prompt) try await runtime.resolveInteraction( AgentInteractionResolution( id: interaction.id, outcome: approved ? .approved : .denied ), conversationId: conversationId ) case .prompt: let answer = await askUserForText(interaction.prompt, options: interaction.promptOptions) try await runtime.resolveInteraction( AgentInteractionResolution( id: interaction.id, outcome: .answered, responseText: answer ), conversationId: conversationId ) case .planModeExit: let approved = await askUserToApprovePlan(interaction.prompt) try await runtime.resolveInteraction( AgentInteractionResolution( id: interaction.id, outcome: approved ? .approved : .denied ), conversationId: conversationId ) } } ``` -------------------------------- ### Add AgentCLIKit package dependency Source: https://github.com/afollestad/agentclikit/blob/main/README.md Adds the AgentCLIKit package to a Swift package manifest, using the 'main' branch since no version tags are published. Requires Swift 6.1 or newer. ```swift .package(url: "https://github.com/afollestad/AgentCLIKit.git", branch: "main") ``` -------------------------------- ### Observe status updates and cancel a conversation in Swift Source: https://github.com/afollestad/agentclikit/blob/main/docs/examples.md Use observeStatus to subscribe to runtime status updates and update UI based on input availability, cancellation, and waiting state. Use cancelConversation to request cancellation. The status includes isTurnActive for mid-turn steering and liveBackgroundTaskCount for background tasks that outlive the turn. ```swift func observeStatus( conversationId: AgentConversationID, runtime: any AgentRuntime ) async { let statuses = await runtime.statusUpdates(conversationId: conversationId) for await status in statuses { updateSendButton(enabled: status.inputAvailability == .available) updateCancelButton(enabled: status.canCancel) switch status.waitingState { case .idle: showWaitingMessage(nil) case .approval: showWaitingMessage("Waiting for approval") case .prompt: showWaitingMessage("Waiting for an answer") case .planModeExit: showWaitingMessage("Waiting for plan approval") } } } func cancelConversation( conversationId: AgentConversationID, runtime: any AgentRuntime ) async { await runtime.cancel(conversationId: conversationId) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.