// GENERATED by `harn dump-protocol-artifacts` - do not edit by hand.
// Source: Harn adapter schemas and Rust wire vocabulary.

import Foundation

public enum HarnProtocolConstants {
    public static let artifactVersion = "0.8.104"
    public static let acpSchemaCompatibility = "agentclientprotocol/agent-client-protocol schema v0.12.2"
    public static let harnAgentEventMethod = "_harn/agentEvent"
    public static let harnProviderCatalogMethod = "_harn/providerCatalog"
    public static let mcpProtocolVersion = "2025-11-25"
    public static let mcpStableProtocolVersion = "2025-11-25"
    public static let mcpDraftProtocolVersion = "DRAFT-2026-v1"
    public static let mcpFinal2026ProtocolVersion = "2026-07-28"
    public static let mcpJsonSchema202012Dialect = "https://json-schema.org/draft/2020-12/schema"
    public static let mcpUnsupportedProtocolVersionErrorCode = -32004
    public static let mcpUnsupportedProtocolVersionErrorMessage = "Unsupported protocol version"
    public static let mcpProtocolVersions: [String] = [
        "DRAFT-2026-v1",
        "2025-11-25",
    ]
    public static let mcpRequiredMetadataKeys: [String] = [
        "io.modelcontextprotocol/protocolVersion",
        "io.modelcontextprotocol/clientInfo",
        "io.modelcontextprotocol/clientCapabilities",
    ]
    public static let mcpMetadataKeys: [String] = [
        "io.modelcontextprotocol/protocolVersion",
        "io.modelcontextprotocol/clientInfo",
        "io.modelcontextprotocol/clientCapabilities",
        "io.modelcontextprotocol/logLevel",
        "progressToken",
        "traceparent",
        "tracestate",
        "baggage",
    ]
    public static let mcpStandardHTTPHeaders: [String] = [
        "MCP-Protocol-Version",
        "Mcp-Method",
        "Mcp-Name",
    ]
    public static let mcpCacheResultFields: [String] = [
        "ttlMs",
        "cacheScope",
    ]
    public static let mcpOAuthClientRegistrationModes: [String] = [
        "pre_registered",
        "client_id_metadata_document",
        "dynamic_client_registration",
        "manual",
    ]
    public static let mcpOAuthAuthModes: [String] = [
        "cimd",
        "dcr",
        "static",
        "byo",
    ]
    public static let mcpOAuthApplicationTypes: [String] = [
        "native",
        "web",
    ]
    public static let acpSessionUpdateExtensions: [String] = [
        "artifact",
        "available_commands_update",
        "fs_watch",
        "handoff",
        "hitl_request",
        "hitl_resolved",
        "log",
        "progress",
        "reminder_emitted",
        "skill_activated",
        "skill_deactivated",
        "skill_narrow",
        "skill_scope_tools",
        "tool_search_query",
        "tool_search_result",
        "transcript_compacted",
        "transcript_projected",
        "worker_update",
    ]
    public static let harnAgentEventKinds: [String] = [
        "budget_circuit_breaker",
        "budget_exhausted",
        "composition_child_call",
        "composition_child_result",
        "composition_error",
        "composition_finish",
        "composition_start",
        "compass_routing_decision",
        "control_outcome",
        "daemon_watchdog_tripped",
        "feedback_injected",
        "iteration_end",
        "iteration_start",
        "judge_decision",
        "loop_control_decision",
        "loop_stuck",
        "mcp_auth_required",
        "mcp_catalog_changed",
        "mcp_notification",
        "progress_reported",
        "scope_classifier_verdict",
        "session_closed",
        "structural_validator_decision",
        "step_judge_decision",
        "tool_call_audit",
        "tool_format_override",
        "typed_checkpoint",
    ]
    public static let toolLifecycleExtensionFields: [String] = [
        "audit",
        "durationMs",
        "error",
        "errorCategory",
        "executionDurationMs",
        "executor",
        "parsing",
        "rawInputPartial",
    ]
    public static let contentExtensionFields: [String] = [
        "visible_delta",
        "visible_text",
    ]
    public static let toolCallReceiptStatuses: [String] = [
        "ok",
        "schema_violation",
        "consent_denied",
        "timeout",
        "error",
    ]
    public static let toolCallReceiptExecutors: [String] = [
        "harn",
        "host_bridge",
        "mcp_server",
        "provider_native",
    ]
}

public enum HarnACPAgentMethod: String, Codable, Sendable, CaseIterable {
    case initialize = "initialize"
    case sessionInject = "session/inject"
    case sessionNew = "session/new"
    case sessionLoad = "session/load"
    case sessionReplaceInject = "session/replace_inject"
    case sessionResume = "session/resume"
    case sessionPrompt = "session/prompt"
    case sessionRevokeInject = "session/revoke_inject"
    case sessionTruncate = "session/truncate"
    case sessionRollback = "session/rollback"
    case sessionRedo = "session/redo"
    case sessionRemind = "session/remind"
    case sessionPendingInjections = "session/pending_injections"
    case sessionRevokeReminder = "session/revoke_reminder"
    case sessionCancelToolCall = "session/cancel_tool_call"
    case sessionClose = "session/close"
    @available(*, deprecated, message: "Use session/close; session/stop will be removed after one release.")
    case sessionStop = "session/stop"

    public static let allCases: [Self] = [
        "initialize",
        "session/inject",
        "session/new",
        "session/load",
        "session/replace_inject",
        "session/resume",
        "session/prompt",
        "session/revoke_inject",
        "session/truncate",
        "session/rollback",
        "session/redo",
        "session/remind",
        "session/pending_injections",
        "session/revoke_reminder",
        "session/cancel_tool_call",
        "session/close",
        "session/stop",
    ].map { Self(rawValue: $0)! }
}

public enum HarnACPClientMethod: String, Codable, Sendable, CaseIterable {
    case fsReadTextFile = "fs/read_text_file"
    case fsWriteTextFile = "fs/write_text_file"
    case terminalCreate = "terminal/create"
    case terminalKill = "terminal/kill"
    case sessionRequestPermission = "session/request_permission"

    public static let allCases: [Self] = [
        "fs/read_text_file",
        "fs/write_text_file",
        "terminal/create",
        "terminal/kill",
        "session/request_permission",
    ].map { Self(rawValue: $0)! }
}

public enum HarnACPAgentNotification: String, Codable, Sendable, CaseIterable {
    case sessionMessage = "session/message"
    case sessionUpdate = "session/update"
    case terminalOutput = "terminal/output"

    public static let allCases: [Self] = [
        "session/message",
        "session/update",
        "terminal/output",
    ].map { Self(rawValue: $0)! }
}

public enum HarnACPSessionUpdate: String, Codable, Sendable, CaseIterable {
    case userMessage = "user_message"
    case userMessageChunk = "user_message_chunk"
    case agentMessageChunk = "agent_message_chunk"
    case agentThoughtChunk = "agent_thought_chunk"
    case toolCall = "tool_call"
    case toolCallUpdate = "tool_call_update"
    case plan = "plan"
    case availableCommandsUpdate = "available_commands_update"
    case currentModeUpdate = "current_mode_update"
    case configOptionUpdate = "config_option_update"
    case sessionInfoUpdate = "session_info_update"
    case sessionRedo = "session_redo"
    case sessionRollback = "session_rollback"
    case sessionTruncated = "session_truncated"
    case artifact = "artifact"
    case fsWatch = "fs_watch"
    case handoff = "handoff"
    case hitlRequest = "hitl_request"
    case hitlResolved = "hitl_resolved"
    case log = "log"
    case progress = "progress"
    case reminderEmitted = "reminder_emitted"
    case skillActivated = "skill_activated"
    case skillDeactivated = "skill_deactivated"
    case skillNarrow = "skill_narrow"
    case skillScopeTools = "skill_scope_tools"
    case toolSearchQuery = "tool_search_query"
    case toolSearchResult = "tool_search_result"
    case transcriptCompacted = "transcript_compacted"
    case transcriptProjected = "transcript_projected"
    case workerUpdate = "worker_update"

    public static let allCases: [Self] = [
        "user_message",
        "user_message_chunk",
        "agent_message_chunk",
        "agent_thought_chunk",
        "tool_call",
        "tool_call_update",
        "plan",
        "available_commands_update",
        "current_mode_update",
        "config_option_update",
        "session_info_update",
        "session_redo",
        "session_rollback",
        "session_truncated",
        "artifact",
        "fs_watch",
        "handoff",
        "hitl_request",
        "hitl_resolved",
        "log",
        "progress",
        "reminder_emitted",
        "skill_activated",
        "skill_deactivated",
        "skill_narrow",
        "skill_scope_tools",
        "tool_search_query",
        "tool_search_result",
        "transcript_compacted",
        "transcript_projected",
        "worker_update",
    ].map { Self(rawValue: $0)! }
}

public enum HarnACPContentBlockType: String, Codable, Sendable, CaseIterable {
    case text = "text"
    case resourceLink = "resource_link"
    case resource = "resource"
    case image = "image"
    case audio = "audio"

    public static let allCases: [Self] = [
        "text",
        "resource_link",
        "resource",
        "image",
        "audio",
    ].map { Self(rawValue: $0)! }
}

public enum HarnACPToolKind: String, Codable, Sendable, CaseIterable {
    case read = "read"
    case edit = "edit"
    case delete = "delete"
    case move = "move"
    case search = "search"
    case execute = "execute"
    case think = "think"
    case fetch = "fetch"
    case other = "other"

    public static let allCases: [Self] = [
        "read",
        "edit",
        "delete",
        "move",
        "search",
        "execute",
        "think",
        "fetch",
        "other",
    ].map { Self(rawValue: $0)! }
}

public enum HarnACPToolCallStatus: String, Codable, Sendable, CaseIterable {
    case pending = "pending"
    case inProgress = "in_progress"
    case completed = "completed"
    case failed = "failed"

    public static let allCases: [Self] = [
        "pending",
        "in_progress",
        "completed",
        "failed",
    ].map { Self(rawValue: $0)! }
}

public enum HarnToolCallErrorCategory: String, Codable, Sendable, CaseIterable {
    case schemaValidation = "schema_validation"
    case toolError = "tool_error"
    case mcpServerError = "mcp_server_error"
    case hostBridgeError = "host_bridge_error"
    case permissionDenied = "permission_denied"
    case rejectedLoop = "rejected_loop"
    case parseAborted = "parse_aborted"
    case timeout = "timeout"
    case network = "network"
    case cancelled = "cancelled"
    case unknown = "unknown"

    public static let allCases: [Self] = [
        "schema_validation",
        "tool_error",
        "mcp_server_error",
        "host_bridge_error",
        "permission_denied",
        "rejected_loop",
        "parse_aborted",
        "timeout",
        "network",
        "cancelled",
        "unknown",
    ].map { Self(rawValue: $0)! }
}

public enum HarnSideEffectLevel: String, Codable, Sendable, CaseIterable {
    case none = "none"
    case readOnly = "read_only"
    case workspaceWrite = "workspace_write"
    case processExec = "process_exec"
    case network = "network"

    public static let allCases: [Self] = [
        "none",
        "read_only",
        "workspace_write",
        "process_exec",
        "network",
    ].map { Self(rawValue: $0)! }
}

public enum HarnWorkerStatus: String, Codable, Sendable, CaseIterable {
    case running = "running"
    case progressed = "progressed"
    case awaitingInput = "awaiting_input"
    case suspended = "suspended"
    case completed = "completed"
    case failed = "failed"
    case stopped = "stopped"
    case cancelled = "cancelled"

    public static let allCases: [Self] = [
        "running",
        "progressed",
        "awaiting_input",
        "suspended",
        "completed",
        "failed",
        "stopped",
        "cancelled",
    ].map { Self(rawValue: $0)! }
}

public enum HarnToolCallReceiptStatus: String, Codable, Sendable, CaseIterable {
    case ok = "ok"
    case schemaViolation = "schema_violation"
    case consentDenied = "consent_denied"
    case timeout = "timeout"
    case error = "error"

    public static let allCases: [Self] = [
        "ok",
        "schema_violation",
        "consent_denied",
        "timeout",
        "error",
    ].map { Self(rawValue: $0)! }
}

public enum HarnToolCallReceiptExecutor: String, Codable, Sendable, CaseIterable {
    case harn = "harn"
    case hostBridge = "host_bridge"
    case mcpServer = "mcp_server"
    case providerNative = "provider_native"

    public static let allCases: [Self] = [
        "harn",
        "host_bridge",
        "mcp_server",
        "provider_native",
    ].map { Self(rawValue: $0)! }
}

public enum HarnA2ATaskState: String, Codable, Sendable, CaseIterable {
    case submitted = "submitted"
    case working = "working"
    case completed = "completed"
    case failed = "failed"
    case canceled = "canceled"
    case cancelled = "cancelled"
    case inputRequired = "input-required"
    case rejected = "rejected"
    case authRequired = "auth-required"

    public static let allCases: [Self] = [
        "submitted",
        "working",
        "completed",
        "failed",
        "canceled",
        "cancelled",
        "input-required",
        "rejected",
        "auth-required",
    ].map { Self(rawValue: $0)! }
}

public enum HarnA2ATaskEventType: String, Codable, Sendable, CaseIterable {
    case status = "status"
    case message = "message"
    case workerUpdate = "worker_update"

    public static let allCases: [Self] = [
        "status",
        "message",
        "worker_update",
    ].map { Self(rawValue: $0)! }
}

public enum HarnMCPMethod: String, Codable, Sendable, CaseIterable {
    case serverDiscover = "server/discover"
    case initialize = "initialize"
    case toolsList = "tools/list"
    case toolsCall = "tools/call"
    case resourcesList = "resources/list"
    case resourcesRead = "resources/read"
    case resourcesTemplatesList = "resources/templates/list"
    case promptsList = "prompts/list"
    case promptsGet = "prompts/get"
    case completionComplete = "completion/complete"
    case loggingSetLevel = "logging/setLevel"
    case samplingCreateMessage = "sampling/createMessage"
    case elicitationCreate = "elicitation/create"
    case notificationsInitialized = "notifications/initialized"
    case notificationsMessage = "notifications/message"

    public static let allCases: [Self] = [
        "server/discover",
        "initialize",
        "tools/list",
        "tools/call",
        "resources/list",
        "resources/read",
        "resources/templates/list",
        "prompts/list",
        "prompts/get",
        "completion/complete",
        "logging/setLevel",
        "sampling/createMessage",
        "elicitation/create",
        "notifications/initialized",
        "notifications/message",
    ].map { Self(rawValue: $0)! }
}

public enum HarnMCPCacheScope: String, Codable, Sendable, CaseIterable {
    case `private` = "private"
    case `public` = "public"

    public static let allCases: [Self] = [
        "private",
        "public",
    ].map { Self(rawValue: $0)! }
}

public enum HarnMCPResultType: String, Codable, Sendable, CaseIterable {
    case complete = "complete"
    case inputRequired = "input_required"

    public static let allCases: [Self] = [
        "complete",
        "input_required",
    ].map { Self(rawValue: $0)! }
}

public enum HarnMCPLoggingLevel: String, Codable, Sendable, CaseIterable {
    case debug = "debug"
    case info = "info"
    case notice = "notice"
    case warning = "warning"
    case error = "error"
    case critical = "critical"
    case alert = "alert"
    case emergency = "emergency"

    public static let allCases: [Self] = [
        "debug",
        "info",
        "notice",
        "warning",
        "error",
        "critical",
        "alert",
        "emergency",
    ].map { Self(rawValue: $0)! }
}

public enum HarnMCPOAuthClientRegistrationMode: String, Codable, Sendable, CaseIterable {
    case preRegistered = "pre_registered"
    case clientIdMetadataDocument = "client_id_metadata_document"
    case dynamicClientRegistration = "dynamic_client_registration"
    case manual = "manual"

    public static let allCases: [Self] = [
        "pre_registered",
        "client_id_metadata_document",
        "dynamic_client_registration",
        "manual",
    ].map { Self(rawValue: $0)! }
}

public enum HarnMCPOAuthAuthMode: String, Codable, Sendable, CaseIterable {
    case cimd = "cimd"
    case dcr = "dcr"
    case `static` = "static"
    case byo = "byo"

    public static let allCases: [Self] = [
        "cimd",
        "dcr",
        "static",
        "byo",
    ].map { Self(rawValue: $0)! }
}

public enum HarnMCPOAuthApplicationType: String, Codable, Sendable, CaseIterable {
    case native = "native"
    case web = "web"

    public static let allCases: [Self] = [
        "native",
        "web",
    ].map { Self(rawValue: $0)! }
}

public enum HarnACPValue: Codable, Sendable, Equatable {
    case null
    case bool(Bool)
    case int(Int)
    case double(Double)
    case string(String)
    case array([HarnACPValue])
    case object([String: HarnACPValue])

    public init?(jsonEncodable value: Encodable) {
        let encoder = JSONEncoder()
        guard let data = try? encoder.encode(HarnAnyEncodable(value)),
              let object = try? JSONSerialization.jsonObject(with: data),
              let converted = HarnACPValue(jsonObject: object) else {
            return nil
        }
        self = converted
    }

    public init?(jsonObject: Any) {
        if let scalar = Self.jsonScalar(jsonObject) {
            self = scalar
        } else if let values = jsonObject as? [Any] {
            guard let array = Self.jsonArray(values) else { return nil }
            self = array
        } else if let values = jsonObject as? [String: Any] {
            guard let object = Self.jsonDictionary(values) else { return nil }
            self = object
        } else {
            return nil
        }
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if container.decodeNil() {
            self = .null
        } else if let value = try? container.decode(Bool.self) {
            self = .bool(value)
        } else if let value = try? container.decode(Int.self) {
            self = .int(value)
        } else if let value = try? container.decode(Double.self) {
            self = .double(value)
        } else if let value = try? container.decode(String.self) {
            self = .string(value)
        } else if let value = try? container.decode([HarnACPValue].self) {
            self = .array(value)
        } else if let value = try? container.decode([String: HarnACPValue].self) {
            self = .object(value)
        } else {
            self = .null
        }
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .null: try container.encodeNil()
        case .bool(let value): try container.encode(value)
        case .int(let value): try container.encode(value)
        case .double(let value): try container.encode(value)
        case .string(let value): try container.encode(value)
        case .array(let value): try container.encode(value)
        case .object(let value): try container.encode(value)
        }
    }

    public var displayString: String {
        switch self {
        case .null: return "nil"
        case .bool(let value): return value ? "true" : "false"
        case .int(let value): return "\(value)"
        case .double(let value): return "\(value)"
        case .string(let value): return value
        case .array(let value): return "[\(value.map(\.displayString).joined(separator: ", "))]"
        case .object(let value):
            let pairs = value.sorted(by: { $0.key < $1.key })
                .map { "\($0.key): \($0.value.displayString)" }
            return "{\(pairs.joined(separator: ", "))}"
        }
    }

    public var stringValue: String? {
        if case .string(let value) = self { return value }
        return nil
    }

    public var intValue: Int? {
        if case .int(let value) = self { return value }
        if case .double(let value) = self, value.rounded() == value { return Int(value) }
        return nil
    }

    public var boolValue: Bool? {
        if case .bool(let value) = self { return value }
        return nil
    }

    public var arrayValue: [HarnACPValue]? {
        if case .array(let value) = self { return value }
        return nil
    }

    public var objectValue: [String: HarnACPValue]? {
        if case .object(let value) = self { return value }
        return nil
    }

    public subscript(_ key: String) -> HarnACPValue? {
        objectValue?[key]
    }

    private static func jsonScalar(_ jsonObject: Any) -> HarnACPValue? {
        switch jsonObject {
        case _ as NSNull: return .null
        case let value as NSNumber: return jsonNumber(value)
        case let value as String: return .string(value)
        default: return nil
        }
    }

    private static func jsonSignedInteger(_ value: Int64) -> HarnACPValue? {
        guard value <= Int64(Int.max), value >= Int64(Int.min) else { return nil }
        return .int(Int(value))
    }

    private static func jsonUnsignedInteger(_ value: UInt64) -> HarnACPValue {
        value <= UInt64(Int.max) ? .int(Int(value)) : .double(Double(value))
    }

    private static func jsonNumber(_ value: NSNumber) -> HarnACPValue? {
        #if canImport(Darwin)
        if CFGetTypeID(value) == CFBooleanGetTypeID() {
            return .bool(value.boolValue)
        }
        if CFNumberIsFloatType(value) {
            return .double(value.doubleValue)
        }
        #endif
        let objCType = String(cString: value.objCType)
        #if !canImport(Darwin)
        if objCType == "c" || objCType == "B" {
            return .bool(value.boolValue)
        }
        #endif
        if objCType == "f" || objCType == "d" {
            return .double(value.doubleValue)
        }
        if ["q", "l", "i", "s"].contains(objCType) {
            return jsonSignedInteger(value.int64Value)
        }
        if ["Q", "L", "I", "S"].contains(objCType) {
            return jsonUnsignedInteger(value.uint64Value)
        }
        return jsonSignedInteger(value.int64Value)
    }

    private static func jsonArray(_ values: [Any]) -> HarnACPValue? {
        var items: [HarnACPValue] = []
        items.reserveCapacity(values.count)
        for value in values {
            guard let item = HarnACPValue(jsonObject: value) else { return nil }
            items.append(item)
        }
        return .array(items)
    }

    private static func jsonDictionary(_ values: [String: Any]) -> HarnACPValue? {
        var fields: [String: HarnACPValue] = [:]
        fields.reserveCapacity(values.count)
        for (key, value) in values {
            guard let item = HarnACPValue(jsonObject: value) else { return nil }
            fields[key] = item
        }
        return .object(fields)
    }
}

public typealias HarnACPObject = [String: HarnACPValue]

private struct HarnAnyEncodable: Encodable {
    let value: Encodable

    init(_ value: Encodable) {
        self.value = value
    }

    func encode(to encoder: Encoder) throws {
        try value.encode(to: encoder)
    }
}

public enum HarnJsonRpcId: Codable, Sendable, Hashable, ExpressibleByIntegerLiteral, ExpressibleByStringLiteral {
    case null
    case int(Int)
    case string(String)

    public init(integerLiteral value: Int) {
        self = .int(value)
    }

    public init(stringLiteral value: String) {
        self = .string(value)
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if container.decodeNil() {
            self = .null
        } else if let value = try? container.decode(Int.self) {
            self = .int(value)
        } else if let value = try? container.decode(String.self) {
            self = .string(value)
        } else {
            throw DecodingError.typeMismatch(
                HarnJsonRpcId.self,
                DecodingError.Context(
                    codingPath: decoder.codingPath,
                    debugDescription: "JSON-RPC id must be an integer, string, or null"
                )
            )
        }
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .null: try container.encodeNil()
        case .int(let value): try container.encode(value)
        case .string(let value): try container.encode(value)
        }
    }

    public var intValue: Int? {
        if case .int(let value) = self { return value }
        return nil
    }

    public var stringValue: String? {
        if case .string(let value) = self { return value }
        return nil
    }
}

public struct HarnACPRequest: Codable, Sendable, Equatable {
    public let jsonrpc: String
    public var id: HarnJsonRpcId
    public var method: String
    public var params: HarnACPValue?

    public init(id: HarnJsonRpcId, method: String, params: HarnACPValue? = nil) {
        self.jsonrpc = "2.0"
        self.id = id
        self.method = method
        self.params = params
    }

    public init(id: Int, method: String, params: HarnACPValue? = nil) {
        self.init(id: .int(id), method: method, params: params)
    }

    public init(id: String, method: String, params: HarnACPValue? = nil) {
        self.init(id: .string(id), method: method, params: params)
    }
}

public struct HarnACPError: Codable, Sendable, Equatable {
    public var code: Int
    public var message: String
    public var data: HarnACPValue?

    public init(code: Int, message: String, data: HarnACPValue? = nil) {
        self.code = code
        self.message = message
        self.data = data
    }
}

public struct HarnACPResponse: Codable, Sendable, Equatable {
    public let jsonrpc: String
    public var id: HarnJsonRpcId
    public var result: HarnACPValue?
    public var error: HarnACPError?

    public init(
        jsonrpc: String = "2.0",
        id: HarnJsonRpcId,
        result: HarnACPValue? = nil,
        error: HarnACPError? = nil
    ) {
        self.jsonrpc = jsonrpc
        self.id = id
        self.result = result
        self.error = error
    }

    public static func success(id: HarnJsonRpcId, result: HarnACPValue) -> HarnACPResponse {
        HarnACPResponse(id: id, result: result)
    }

    public static func success(id: Int, result: HarnACPValue) -> HarnACPResponse {
        success(id: .int(id), result: result)
    }

    public static func error(
        id: HarnJsonRpcId,
        code: Int,
        message: String,
        data: HarnACPValue? = nil
    ) -> HarnACPResponse {
        HarnACPResponse(id: id, error: HarnACPError(code: code, message: message, data: data))
    }

    public static func error(
        id: Int,
        code: Int,
        message: String,
        data: HarnACPValue? = nil
    ) -> HarnACPResponse {
        error(id: .int(id), code: code, message: message, data: data)
    }
}

public struct HarnACPNotification: Codable, Sendable, Equatable {
    public let jsonrpc: String
    public var method: String
    public var params: HarnACPValue?

    public init(method: String, params: HarnACPValue? = nil) {
        self.jsonrpc = "2.0"
        self.method = method
        self.params = params
    }
}

public struct HarnACPExtensionMeta: Codable, Sendable, Equatable {
    public var harn: HarnACPObject?
}

public struct HarnACPContentBlock: Codable, Sendable, Equatable {
    public var type: String
    public var text: String?
    public var meta: HarnACPExtensionMeta?

    enum CodingKeys: String, CodingKey {
        case type
        case text
        case meta = "_meta"
    }
}

public enum HarnACPToolExecutor: Codable, Sendable, Equatable {
    case harnBuiltin
    case hostBridge
    case providerNative
    case mcpServer(name: String)
    case unknown(String)

    enum ObjectKey: String, CodingKey {
        case kind
        case serverName
    }

    public init(from decoder: Decoder) throws {
        if let raw = try? decoder.singleValueContainer().decode(String.self) {
            switch raw {
            case "harn_builtin": self = .harnBuiltin
            case "host_bridge": self = .hostBridge
            case "provider_native": self = .providerNative
            default: self = .unknown(raw)
            }
            return
        }
        let object = try decoder.container(keyedBy: ObjectKey.self)
        let kind = try object.decode(String.self, forKey: .kind)
        if kind == "mcp_server" {
            self = .mcpServer(name: try object.decode(String.self, forKey: .serverName))
        } else {
            self = .unknown(kind)
        }
    }

    public func encode(to encoder: Encoder) throws {
        switch self {
        case .harnBuiltin:
            var container = encoder.singleValueContainer()
            try container.encode("harn_builtin")
        case .hostBridge:
            var container = encoder.singleValueContainer()
            try container.encode("host_bridge")
        case .providerNative:
            var container = encoder.singleValueContainer()
            try container.encode("provider_native")
        case .mcpServer(let name):
            var container = encoder.container(keyedBy: ObjectKey.self)
            try container.encode("mcp_server", forKey: .kind)
            try container.encode(name, forKey: .serverName)
        case .unknown(let raw):
            var container = encoder.singleValueContainer()
            try container.encode(raw)
        }
    }

    public var displayLabel: String {
        switch self {
        case .harnBuiltin: return "harn_builtin"
        case .hostBridge: return "host_bridge"
        case .providerNative: return "provider_native"
        case .mcpServer(let name): return "mcp:\(name)"
        case .unknown(let raw): return raw
        }
    }
}

public struct HarnToolLifecycleMeta: Codable, Sendable, Equatable {
    public var audit: HarnACPValue?
    public var durationMs: Double?
    public var error: String?
    public var errorCategory: HarnToolCallErrorCategory?
    public var executionDurationMs: Double?
    public var executor: HarnACPToolExecutor?
    public var parsing: Bool?
    public var rawInputPartial: String?
}

public struct HarnToolCallReceipt: Codable, Sendable, Equatable {
    public var schemaVersion: Int
    public var sessionId: String
    public var runId: String?
    public var toolCallId: String
    public var toolName: String
    public var iteration: Int
    public var turnIndex: Int?
    public var emitOrder: Int
    public var reason: String?
    public var kind: String?
    public var executor: HarnToolCallReceiptExecutor?
    public var status: HarnToolCallReceiptStatus
    public var errorCategory: String?
    public var durationMs: Int
    public var argsHash: String
    public var resultHash: String?
    public var audit: HarnACPValue
    public var emittedAt: String
    public var model: String?
    public var provider: String?

    enum CodingKeys: String, CodingKey {
        case schemaVersion = "schema_version"
        case sessionId = "session_id"
        case runId = "run_id"
        case toolCallId = "tool_call_id"
        case toolName = "tool_name"
        case iteration
        case turnIndex = "turn_index"
        case emitOrder = "emit_order"
        case reason
        case kind
        case executor
        case status
        case errorCategory = "error_category"
        case durationMs = "duration_ms"
        case argsHash = "args_hash"
        case resultHash = "result_hash"
        case audit
        case emittedAt = "emitted_at"
        case model
        case provider
    }
}

public struct HarnACPToolCall: Codable, Sendable, Equatable {
    public var sessionUpdate: HarnACPSessionUpdate
    public var toolCallId: String
    public var title: String
    public var kind: HarnACPToolKind?
    public var status: HarnACPToolCallStatus?
    public var content: [HarnACPContentBlock]?
    public var locations: [HarnACPValue]?
    public var rawInput: HarnACPValue?
    public var rawOutput: HarnACPValue?
    public var meta: HarnACPExtensionMeta?

    enum CodingKeys: String, CodingKey {
        case sessionUpdate
        case toolCallId
        case title
        case kind
        case status
        case content
        case locations
        case rawInput
        case rawOutput
        case meta = "_meta"
    }
}

public struct HarnACPSessionUpdateEnvelope: Codable, Sendable, Equatable {
    public var sessionUpdate: HarnACPSessionUpdate
    public var content: HarnACPValue?
    public var messageId: String?
    public var entries: [HarnACPValue]?
    public var keptTurnCount: Int?
    public var removedTurnCount: Int?
    public var newTipTurnId: String?
    public var reason: String?
    public var toolCallId: String?
    public var title: String?
    public var kind: HarnACPToolKind?
    public var status: HarnACPToolCallStatus?
    public var rawInput: HarnACPValue?
    public var rawOutput: HarnACPValue?
    public var meta: HarnACPExtensionMeta?

    enum CodingKeys: String, CodingKey {
        case sessionUpdate
        case content
        case messageId
        case entries
        case keptTurnCount
        case removedTurnCount
        case newTipTurnId
        case reason
        case toolCallId
        case title
        case kind
        case status
        case rawInput
        case rawOutput
        case meta = "_meta"
    }
}

public struct HarnACPSessionUpdateParams: Codable, Sendable, Equatable {
    public var sessionId: String
    public var update: HarnACPSessionUpdateEnvelope
}

public struct HarnACPSessionUpdateNotification: Codable, Sendable, Equatable {
    public let jsonrpc: String
    public var method: String
    public var params: HarnACPSessionUpdateParams
}

public struct HarnAgentEventNotification: Codable, Sendable, Equatable {
    public let jsonrpc: String
    public var method: String
    public var params: HarnACPObject
}

public struct HarnPromptCapabilities: Codable, Sendable, Equatable {
    public var image: Bool?
    public var audio: Bool?
    public var embeddedContext: Bool?
}

public struct HarnACPAgentCapabilities: Codable, Sendable, Equatable {
    public var meta: HarnACPExtensionMeta?
    public var loadSession: Bool?
    public var session: HarnACPObject?
    public var promptCapabilities: HarnPromptCapabilities?
    public var mcpCapabilities: HarnACPObject?
    public var sessionCapabilities: HarnACPObject?

    enum CodingKeys: String, CodingKey {
        case meta = "_meta"
        case loadSession
        case session
        case promptCapabilities
        case mcpCapabilities
        case sessionCapabilities
    }
}

public struct HarnToolArgSchema: Codable, Sendable, Equatable {
    public var pathParams: [String]
    public var argAliases: [String: String]
    public var required: [String]

    enum CodingKeys: String, CodingKey {
        case pathParams = "path_params"
        case argAliases = "arg_aliases"
        case required
    }
}

public struct HarnToolAnnotations: Codable, Sendable, Equatable {
    public var kind: HarnACPToolKind
    public var sideEffectLevel: HarnSideEffectLevel
    public var argSchema: HarnToolArgSchema
    public var capabilities: [String: [String]]
    public var emitsArtifacts: Bool
    public var resultReaders: [String]
    public var inlineResult: Bool

    enum CodingKeys: String, CodingKey {
        case kind
        case sideEffectLevel = "side_effect_level"
        case argSchema = "arg_schema"
        case capabilities
        case emitsArtifacts = "emits_artifacts"
        case resultReaders = "result_readers"
        case inlineResult = "inline_result"
    }
}

public struct HarnA2ATaskStatus: Codable, Sendable, Equatable {
    public var state: HarnA2ATaskState
    public var message: HarnACPValue?
    public var timestamp: String?
}

public struct HarnA2ATask: Codable, Sendable, Equatable {
    public var id: String
    public var contextId: String?
    public var status: HarnA2ATaskStatus
    public var history: [HarnACPValue]?
    public var artifacts: [HarnACPValue]?
    public var metadata: HarnACPObject?
}

public typealias HarnMCPJsonSchema202012 = HarnACPObject

public struct HarnMCPImplementation: Codable, Sendable, Equatable {
    public var name: String
    public var version: String
    public var title: String?
    public var description: String?
    public var websiteUrl: String?
}

public struct HarnMCPRequestMeta: Codable, Sendable, Equatable {
    public var protocolVersion: String
    public var clientInfo: HarnMCPImplementation
    public var clientCapabilities: HarnACPObject
    public var logLevel: HarnMCPLoggingLevel?
    public var progressToken: HarnACPValue?
    public var traceparent: String?
    public var tracestate: String?
    public var baggage: String?

    enum CodingKeys: String, CodingKey {
        case protocolVersion = "io.modelcontextprotocol/protocolVersion"
        case clientInfo = "io.modelcontextprotocol/clientInfo"
        case clientCapabilities = "io.modelcontextprotocol/clientCapabilities"
        case logLevel = "io.modelcontextprotocol/logLevel"
        case progressToken
        case traceparent
        case tracestate
        case baggage
    }
}

public struct HarnMCPHTTPHeaders: Codable, Sendable, Equatable {
    public var protocolVersion: String
    public var method: String
    public var name: String?

    enum CodingKeys: String, CodingKey {
        case protocolVersion = "MCP-Protocol-Version"
        case method = "Mcp-Method"
        case name = "Mcp-Name"
    }
}

public struct HarnMCPCacheHints: Codable, Sendable, Equatable {
    public var ttlMs: Int
    public var cacheScope: HarnMCPCacheScope
}

public struct HarnMCPDiscoverResult: Codable, Sendable, Equatable {
    public var resultType: HarnMCPResultType
    public var supportedVersions: [String]
    public var capabilities: HarnACPObject
    public var serverInfo: HarnMCPImplementation
    public var instructions: String?
    public var meta: HarnACPObject?

    enum CodingKeys: String, CodingKey {
        case resultType
        case supportedVersions
        case capabilities
        case serverInfo
        case instructions
        case meta = "_meta"
    }
}

public struct HarnMCPInputRequiredResult: Codable, Sendable, Equatable {
    public var resultType: HarnMCPResultType
    public var inputRequests: HarnACPObject?
    public var requestState: String?
    public var meta: HarnACPObject?

    enum CodingKeys: String, CodingKey {
        case resultType
        case inputRequests
        case requestState
        case meta = "_meta"
    }
}

public struct HarnMCPUnsupportedProtocolVersionErrorData: Codable, Sendable, Equatable {
    public var requested: String
    public var supported: [String]
}

public struct HarnMCPUnsupportedProtocolVersionError: Codable, Sendable, Equatable {
    public var jsonrpc: String
    public var id: HarnJsonRpcId?
    public var error: HarnACPError
}

public struct HarnMCPTool: Codable, Sendable, Equatable {
    public var name: String
    public var title: String?
    public var description: String?
    public var inputSchema: HarnMCPJsonSchema202012
    public var outputSchema: HarnMCPJsonSchema202012?
    public var annotations: HarnACPObject?
}

public struct HarnMCPResource: Codable, Sendable, Equatable {
    public var uri: String
    public var name: String
    public var title: String?
    public var description: String?
    public var mimeType: String?
}

public struct HarnMCPResourceTemplate: Codable, Sendable, Equatable {
    public var uriTemplate: String
    public var name: String
    public var title: String?
    public var description: String?
    public var mimeType: String?
}

public struct HarnMCPPrompt: Codable, Sendable, Equatable {
    public var name: String
    public var title: String?
    public var description: String?
    public var arguments: [HarnACPObject]?
}

public struct HarnMCPOAuthProtectedResourceMetadata: Codable, Sendable, Equatable {
    public var resource: String?
    public var authorizationServers: [String]
    public var scopesSupported: [String]?
    public var bearerMethodsSupported: [String]?

    enum CodingKeys: String, CodingKey {
        case resource
        case authorizationServers = "authorization_servers"
        case scopesSupported = "scopes_supported"
        case bearerMethodsSupported = "bearer_methods_supported"
    }
}

public struct HarnMCPOAuthAuthorizationServerMetadata: Codable, Sendable, Equatable {
    public var issuer: String
    public var authorizationEndpoint: String
    public var tokenEndpoint: String
    public var registrationEndpoint: String?
    public var tokenEndpointAuthMethodsSupported: [String]?
    public var codeChallengeMethodsSupported: [String]?
    public var scopesSupported: [String]?
    public var clientIdMetadataDocumentSupported: Bool?
    public var authorizationResponseIssParameterSupported: Bool?

    enum CodingKeys: String, CodingKey {
        case issuer
        case authorizationEndpoint = "authorization_endpoint"
        case tokenEndpoint = "token_endpoint"
        case registrationEndpoint = "registration_endpoint"
        case tokenEndpointAuthMethodsSupported = "token_endpoint_auth_methods_supported"
        case codeChallengeMethodsSupported = "code_challenge_methods_supported"
        case scopesSupported = "scopes_supported"
        case clientIdMetadataDocumentSupported = "client_id_metadata_document_supported"
        case authorizationResponseIssParameterSupported = "authorization_response_iss_parameter_supported"
    }
}

public struct HarnMCPOAuthWwwAuthenticateChallenge: Codable, Sendable, Equatable {
    public var scheme: String
    public var params: [String: String]
}

public struct HarnMCPOAuthDiscoveryResult: Codable, Sendable, Equatable {
    public var protectedResourceMetadataUrl: String
    public var protectedResourceMetadata: HarnMCPOAuthProtectedResourceMetadata
    public var authorizationServerIssuer: String
    public var authorizationServerMetadataUrl: String
    public var authorizationServerMetadataKind: String
    public var authorizationServerMetadata: HarnMCPOAuthAuthorizationServerMetadata
    public var challenge: HarnMCPOAuthWwwAuthenticateChallenge?
    public var scopes: [String]
}

public struct HarnMCPOAuthDynamicClientRegistrationRequest: Codable, Sendable, Equatable {
    public var clientName: String
    public var redirectUris: [String]
    public var grantTypes: [String]
    public var responseTypes: [String]
    public var tokenEndpointAuthMethod: String
    public var applicationType: HarnMCPOAuthApplicationType
    public var scope: String?

    enum CodingKeys: String, CodingKey {
        case clientName = "client_name"
        case redirectUris = "redirect_uris"
        case grantTypes = "grant_types"
        case responseTypes = "response_types"
        case tokenEndpointAuthMethod = "token_endpoint_auth_method"
        case applicationType = "application_type"
        case scope
    }
}
