1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
//
// AtircClient.swift
// AT-IRC
//
// XRPC calls to the atirc server: chat.atirc.mint, chat.atirc.post,
// chat.atirc.list, plus the live chat.atirc.subscribe WebSocket.
//
import Foundation
struct AtircHTTPError: LocalizedError {
let status: Int
let name: String
let message: String
var errorDescription: String? { "\(name) (HTTP \(status)): \(message)" }
var isUnauthorized: Bool { status == 401 }
}
@MainActor
final class AtircClient {
private let oauth = OAuthClient()
private let session: URLSession
init() {
let configuration = URLSessionConfiguration.ephemeral
configuration.timeoutIntervalForRequest = 30
configuration.waitsForConnectivity = true
session = URLSession(configuration: configuration)
}
// MARK: - Mint
/// Exchange a short-lived PDS service-auth JWT for a long-lived atirc token.
func mint(oauthSession: OAuthSession, subhandle: String) async throws -> (MintResult, OAuthSession) {
let (serviceToken, updatedSession) = try await oauth.serviceAuth(
session: oauthSession,
lxm: "chat.atirc.mint",
aud: AtircService.serviceRef
)
var request = URLRequest(url: endpoint("/xrpc/chat.atirc.mint"))
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(serviceToken)", forHTTPHeaderField: "Authorization")
request.httpBody = try JSONSerialization.data(withJSONObject: ["subhandle": subhandle])
let (data, response) = try await session.data(for: request)
try Self.check(response: response, data: data)
let mint = try JSONDecoder().decode(MintResult.self, from: data)
return (mint, updatedSession)
}
// MARK: - Post
func post(text: String, channel: String?, token: String, baseURL: String = AtircService.defaultBaseURL) async throws -> AtircMessage {
var body: [String: Any] = ["text": text]
if let channel, !channel.isEmpty {
body["channel"] = channel
}
var request = URLRequest(url: endpoint("/xrpc/chat.atirc.post", baseURL: baseURL))
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let (data, response) = try await session.data(for: request)
try Self.check(response: response, data: data)
return try JSONDecoder().decode(AtircMessage.self, from: data)
}
// MARK: - List (public backfill)
func list(channel: String?, cursor: Int64 = 0, limit: Int = 50, baseURL: String = AtircService.defaultBaseURL) async throws -> AtircListResponse {
var components = URLComponents(url: endpoint("/xrpc/chat.atirc.list", baseURL: baseURL), resolvingAgainstBaseURL: false)!
var items = [URLQueryItem(name: "cursor", value: String(cursor)),
URLQueryItem(name: "limit", value: String(limit))]
if let channel, !channel.isEmpty {
items.append(URLQueryItem(name: "channel", value: channel))
}
components.queryItems = items
guard let url = components.url else {
throw AtircHTTPError(status: 0, name: "InvalidRequest", message: "Bad list URL")
}
let (data, response) = try await session.data(from: url)
try Self.check(response: response, data: data)
return try JSONDecoder().decode(AtircListResponse.self, from: data)
}
// MARK: - Owner questions
/// Pending questions addressed to the owner (or every question with
/// `status = "all"`). Always carries the current owner mode.
func questions(token: String, status: String = "all", baseURL: String = AtircService.defaultBaseURL) async throws -> AskQuestionsResponse {
var components = URLComponents(url: endpoint("/xrpc/chat.atirc.questions", baseURL: baseURL), resolvingAgainstBaseURL: false)!
components.queryItems = [URLQueryItem(name: "status", value: status)]
guard let url = components.url else {
throw AtircHTTPError(status: 0, name: "InvalidRequest", message: "Bad questions URL")
}
var request = URLRequest(url: url)
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let (data, response) = try await session.data(for: request)
try Self.check(response: response, data: data)
return try JSONDecoder().decode(AskQuestionsResponse.self, from: data)
}
/// Answer a question. `answer` is the option text (with its 0-based
/// `choice` index) or free-form text (no choice).
func answer(questionID: String, answer: String, choice: Int?, token: String, baseURL: String = AtircService.defaultBaseURL) async throws -> AskQuestion {
var body: [String: Any] = ["id": questionID]
if !answer.isEmpty {
body["answer"] = answer
}
if let choice {
body["choice"] = choice
}
let data = try await sendJSON("/xrpc/chat.atirc.answer", body: body, token: token, baseURL: baseURL)
return try JSONDecoder().decode(AskQuestion.self, from: data)
}
func ownerMode(token: String, baseURL: String = AtircService.defaultBaseURL) async throws -> OwnerModeResponse {
var request = URLRequest(url: endpoint("/xrpc/chat.atirc.ownerMode", baseURL: baseURL))
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let (data, response) = try await session.data(for: request)
try Self.check(response: response, data: data)
return try JSONDecoder().decode(OwnerModeResponse.self, from: data)
}
/// `mode` is `available` (questions wait for the owner) or `autonomous`
/// (agents research and decide, recording an ADR). The response body is
/// not needed; the next questions poll returns the authoritative mode.
func setOwnerMode(_ mode: String, token: String, baseURL: String = AtircService.defaultBaseURL) async throws {
_ = try await sendJSON("/xrpc/chat.atirc.ownerMode", body: ["mode": mode], token: token, baseURL: baseURL)
}
// MARK: - Helpers
private func sendJSON(_ path: String, body: [String: Any], token: String, baseURL: String) async throws -> Data {
var request = URLRequest(url: endpoint(path, baseURL: baseURL))
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let (data, response) = try await session.data(for: request)
try Self.check(response: response, data: data)
return data
}
func endpoint(_ path: String, baseURL: String = AtircService.defaultBaseURL) -> URL {
URL(string: baseURL.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + path)!
}
static func check(response: URLResponse, data: Data) throws {
guard let http = response as? HTTPURLResponse else {
throw AtircHTTPError(status: 0, name: "BadResponse", message: "Not an HTTP response")
}
guard (200..<300).contains(http.statusCode) else {
var name = "HTTP\(http.statusCode)"
var message = String(data: data, encoding: .utf8) ?? ""
if let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
name = object["error"] as? String ?? name
message = object["message"] as? String ?? message
}
throw AtircHTTPError(status: http.statusCode, name: name, message: message)
}
}
}
// MARK: - Subscription
/// Live chat.atirc.subscribe client.
///
/// atirc uses Event Stream v0 framing: each binary WebSocket message is two
/// concatenated CBOR objects — a header (`{"op":1,"t":"#message"}`) and a body
/// with the message object.
@MainActor
final class AtircWebSocket: NSObject, URLSessionWebSocketDelegate {
private var session: URLSession?
private var task: URLSessionWebSocketTask?
private var isClosed = false
private var pingTask: Task<Void, Never>?
private var watchdogTask: Task<Void, Never>?
private var lastActivity = Date()
var onFrame: ((AtircFrame) -> Void)?
var onStatus: ((String) -> Void)?
func connect(url: URL, token: String) {
disconnect()
isClosed = false
// URLSessionWebSocketTask issues a proper HTTP Upgrade request for the
// full URL (path + query), unlike NWConnection's WebSocket options.
var request = URLRequest(url: url)
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("atirc/xrpc/1", forHTTPHeaderField: "Sec-WebSocket-Protocol")
let configuration = URLSessionConfiguration.ephemeral
configuration.waitsForConnectivity = true
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
self.session = session
let task = session.webSocketTask(with: request)
self.task = task
task.resume()
onStatus?("connecting")
receiveLoop()
startPing()
}
func disconnect() {
isClosed = true
pingTask?.cancel()
pingTask = nil
watchdogTask?.cancel()
watchdogTask = nil
task?.cancel(with: .goingAway, reason: nil)
task = nil
session?.invalidateAndCancel()
session = nil
}
/// A server exec-upgrade can leave the client socket hung with no FIN or
/// Close frame. A ping every 25s and a 60s receive watchdog surface that
/// promptly so ChatStore can reconnect with backoff.
private func startPing() {
pingTask?.cancel()
watchdogTask?.cancel()
lastActivity = Date()
pingTask = Task { @MainActor [weak self] in
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(25))
guard let self, !self.isClosed, let task = self.task else { return }
task.sendPing { [weak self] error in
Task { @MainActor in
guard let self, !self.isClosed else { return }
if let error {
let nsError = error as NSError
self.onStatus?("error: ping failed: \(error.localizedDescription) [\(nsError.domain):\(nsError.code)]")
} else {
self.lastActivity = Date()
}
}
}
}
}
watchdogTask = Task { @MainActor [weak self] in
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(5))
guard let self, !self.isClosed else { return }
if Date().timeIntervalSince(self.lastActivity) > 60 {
self.onStatus?("error: receive watchdog timeout (60s)")
return
}
}
}
}
// MARK: URLSessionWebSocketDelegate
nonisolated func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
Task { @MainActor in
guard !self.isClosed else { return }
self.lastActivity = Date()
self.onStatus?("connected")
}
}
nonisolated func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
Task { @MainActor in
guard !self.isClosed else { return }
var status = "closed (\(closeCode.rawValue))"
if let reason, let text = String(data: reason, encoding: .utf8), !text.isEmpty {
status += ": \(text)"
}
self.onStatus?(status)
}
}
nonisolated func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) {
guard let error else { return }
Task { @MainActor in
guard !self.isClosed else { return }
let nsError = error as NSError
self.onStatus?("error: \(error.localizedDescription) [\(nsError.domain):\(nsError.code)]")
}
}
// MARK: Frame decoding
private func receiveLoop() {
guard let task, !isClosed else { return }
task.receive { [weak self] result in
Task { @MainActor in
guard let self, !self.isClosed else { return }
switch result {
case .success(let message):
switch message {
case .data(let data):
self.handle(data: data)
case .string(let text):
if let data = text.data(using: .utf8) {
self.handle(data: data)
}
@unknown default:
break
}
self.receiveLoop()
case .failure(let error):
self.onStatus?("error: \(error.localizedDescription)")
}
}
}
}
private func handle(data: Data) {
lastActivity = Date()
if let frame = try? AtircFrame.decode(data) {
onFrame?(frame)
} else {
onStatus?("undecodable frame (\(data.count) bytes)")
}
}
}