75 lines
2.5 KiB
Swift
Raw Permalink Normal View History

import Foundation
import OSLog
struct ControlRequestParams: @unchecked Sendable {
2025-12-12 16:09:31 +00:00
/// Heterogeneous JSON-ish params (Bool/String/Int/Double/[...]/[String:...]).
/// `@unchecked Sendable` is intentional: values are treated as immutable payloads.
let raw: [String: Any]
}
actor AgentRPC {
static let shared = AgentRPC()
2025-12-09 14:41:41 +01:00
private let logger = Logger(subsystem: "com.steipete.clawdis", category: "agent.rpc")
2025-12-09 14:41:41 +01:00
func shutdown() async {
// no-op; socket managed by GatewayConnection
2025-12-09 14:41:41 +01:00
}
2025-12-09 14:41:41 +01:00
func setHeartbeatsEnabled(_ enabled: Bool) async -> Bool {
do {
_ = try await self.controlRequest(
method: "set-heartbeats",
2025-12-12 16:09:31 +00:00
params: ControlRequestParams(raw: ["enabled": enabled]))
2025-12-09 14:41:41 +01:00
return true
} catch {
self.logger.error("setHeartbeatsEnabled failed \(error.localizedDescription, privacy: .public)")
2025-12-09 14:41:41 +01:00
return false
}
2025-12-09 14:41:41 +01:00
}
2025-12-09 14:41:41 +01:00
func status() async -> (ok: Bool, error: String?) {
do {
let data = try await controlRequest(method: "status")
if let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
(obj["ok"] as? Bool) ?? true
{
2025-12-09 14:41:41 +01:00
return (true, nil)
}
2025-12-09 14:41:41 +01:00
return (false, "status error")
} catch {
return (false, error.localizedDescription)
}
}
2025-12-08 20:18:54 +01:00
func send(
text: String,
thinking: String?,
sessionKey: String,
deliver: Bool,
to: String?,
channel: String? = nil) async -> (ok: Bool, text: String?, error: String?)
{
do {
2025-12-12 16:09:31 +00:00
let params: [String: Any] = [
"message": text,
"sessionKey": sessionKey,
2025-12-12 16:09:31 +00:00
"thinking": thinking ?? "default",
"deliver": deliver,
"to": to ?? "",
"channel": channel ?? "",
2025-12-12 16:09:31 +00:00
"idempotencyKey": UUID().uuidString,
]
_ = try await self.controlRequest(method: "agent", params: ControlRequestParams(raw: params))
2025-12-09 14:41:41 +01:00
return (true, nil, nil)
} catch {
return (false, nil, error.localizedDescription)
}
}
func controlRequest(method: String, params: ControlRequestParams? = nil) async throws -> Data {
let rawParams = params?.raw.reduce(into: [String: AnyCodable]()) { $0[$1.key] = AnyCodable($1.value) }
return try await GatewayConnection.shared.request(method: method, params: rawParams)
}
}