SPB Git

Repository Public

Wire.swift 8.9 KB 207 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Claude Remote / Codex Remote9// File             : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteModels/Wire.swift10// Module           : ClaudeRemoteModels11// Repository       : https://git.spboucher.ai/claude-remote-apple12// Project Website  : https://claude.spboucher.ai13// Created          : 2026-11-2914// Last Modified    : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation8990// WebSocket wire formats (wire.ts).91//92// Terminal stream  /api/v1/sessions/:id/stream?cols=&rows=93//   - BINARY frames: raw PTY bytes (server→client output, client→server input). Never JSON.94//   - TEXT frames: JSON control messages below.95// Event stream     /api/v1/events — TEXT JSON `ServerEvent` only.96// Task log stream  /api/v1/tasks/:id/log/stream?offset= — BINARY log bytes, server→client only.9798/// Limits enforced by the server on the terminal size.99public enum TerminalLimits {100    public static let cols = 20...500101    public static let rows = 5...200102    /// Inbound frames above 1 MiB are rejected; the clients chunk at 64 KiB like the web app.103    public static let inputChunkBytes = 64 * 1024104105    public static func clamp(cols: Int, rows: Int) -> (cols: Int, rows: Int) {106        (min(max(cols, self.cols.lowerBound), self.cols.upperBound), min(max(rows, self.rows.lowerBound), self.rows.upperBound))107    }108}109110/// Control message sent by the client on the terminal stream.111public enum TermClientMessage: Hashable, Sendable, Codable {112    case resize(cols: Int, rows: Int)113    case ping(n: Int)114115    private enum Keys: String, CodingKey { case t, cols, rows, n }116    public func encode(to encoder: Encoder) throws {117        var c = encoder.container(keyedBy: Keys.self)118        switch self {119        case .resize(let cols, let rows):120            try c.encode("resize", forKey: .t); try c.encode(cols, forKey: .cols); try c.encode(rows, forKey: .rows)121        case .ping(let n):122            try c.encode("ping", forKey: .t); try c.encode(n, forKey: .n)123        }124    }125    public init(from decoder: Decoder) throws {126        let c = try decoder.container(keyedBy: Keys.self)127        switch try c.decode(String.self, forKey: .t) {128        case "resize": self = .resize(cols: try c.decode(Int.self, forKey: .cols), rows: try c.decode(Int.self, forKey: .rows))129        case "ping": self = .ping(n: try c.decode(Int.self, forKey: .n))130        case let other: throw DecodingError.dataCorruptedError(forKey: .t, in: c, debugDescription: "unknown client message \(other)")131        }132    }133    /// The JSON text frame.134    public var text: String { (try? String(decoding: JSONEncoder().encode(self), as: UTF8.self)) ?? "{}" }135}136137/// Control message received on the terminal stream.138public enum TermServerMessage: Hashable, Sendable, Decodable {139    case ready(sessionId: String, cols: Int, rows: Int)140    case pong(n: Int)141    /// The session process ended.142    case exit(code: Int?)143    case error(code: String, message: String)144    /// A message type introduced by a newer server; ignore it.145    case unknown(type: String)146147    private enum Keys: String, CodingKey { case t, sessionId, cols, rows, n, code, message }148    public init(from decoder: Decoder) throws {149        let c = try decoder.container(keyedBy: Keys.self)150        let t = try c.decode(String.self, forKey: .t)151        switch t {152        case "ready":153            self = .ready(sessionId: try c.decode(String.self, forKey: .sessionId),154                          cols: try c.decode(Int.self, forKey: .cols), rows: try c.decode(Int.self, forKey: .rows))155        case "pong": self = .pong(n: try c.decode(Int.self, forKey: .n))156        case "exit": self = .exit(code: try c.decodeIfPresent(Int.self, forKey: .code))157        case "error": self = .error(code: try c.decode(String.self, forKey: .code), message: try c.decode(String.self, forKey: .message))158        default: self = .unknown(type: t)159        }160    }161    public init?(text: String) {162        guard let v = try? JSONDecoder().decode(TermServerMessage.self, from: Data(text.utf8)) else { return nil }163        self = v164    }165}166167/// Application close codes of the WebSockets.168public enum WSCloseCode: Int, Sendable, CaseIterable {169    case unauthorized = 4401170    case forbidden = 4403171    case notFound = 4404172    case sessionEnded = 4410173    case backpressure = 4429174    case runtimeUnavailable = 4503175}176177/// Event pushed on `/events`.178public enum ServerEvent: Hashable, Sendable, Decodable {179    case hello(serverTime: Date)180    case sessionUpdated(TerminalSession)181    case sessionRemoved(id: String)182    case taskUpdated(AgentTask)183    case notification(ServerNotification)184    /// The auth session ended: return to sign-in.185    case authExpired186    case unknown(type: String)187188    private enum Keys: String, CodingKey { case type, serverTime, session, id, task, notification }189    public init(from decoder: Decoder) throws {190        let c = try decoder.container(keyedBy: Keys.self)191        let type = try c.decode(String.self, forKey: .type)192        switch type {193        case "hello": self = .hello(serverTime: try c.decode(Date.self, forKey: .serverTime))194        case "session.updated": self = .sessionUpdated(try c.decode(TerminalSession.self, forKey: .session))195        case "session.removed": self = .sessionRemoved(id: try c.decode(String.self, forKey: .id))196        case "task.updated": self = .taskUpdated(try c.decode(AgentTask.self, forKey: .task))197        case "notification": self = .notification(try c.decode(ServerNotification.self, forKey: .notification))198        case "auth.expired": self = .authExpired199        default: self = .unknown(type: type)200        }201    }202    public init?(text: String) {203        guard let v = try? CRJSON.decoder().decode(ServerEvent.self, from: Data(text.utf8)) else { return nil }204        self = v205    }206}207
Files main
Menu

Theme