SPB Git

Repository Public

Endpoints.swift 20.2 KB 363 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/ClaudeRemoteAPI/Endpoints.swift10// Module           : ClaudeRemoteAPI11// 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 ClaudeRemoteModels89import Foundation9091private func flag(_ value: Bool?) -> String? { value.map { $0 ? "1" : "0" } }92private func seg(_ value: String) -> String { APIClient.segment(value) }9394// MARK: Health, auth, devices9596extension APIClient {97    /// `GET /health` — public liveness.98    public func health() async throws -> ServerHealth { try await send(.get, "/health", auth: .none) }99100    /// `GET /auth/status` — with the bearer when signed in; also readable anonymously (branding).101    public func authStatus() async throws -> AuthStatus { try await send(.get, "/auth/status", auth: .optionalSession) }102103    // Native session endpoints (docs/NATIVE-API-CONTRACT.md §2). Used by `AuthService`.104105    public func nativeLogin(_ request: NativeLoginRequest) async throws -> NativeLoginResponse {106        try await send(.post, "/native/auth/login", body: request, auth: .none)107    }108109    /// TOTP second step with the restricted bearer; the token is rotated.110    public func nativeTotp(code: String, token: String) async throws -> NativeLoginResponse {111        try await send(.post, "/native/auth/totp", body: ["code": code], auth: .token(token))112    }113114    /// Passkey request options. With a restricted `token`: second step (`allowCredentials`).115    /// Without: discoverable credentials + `challengeToken` (passkey-only sign-in).116    public func nativePasskeyOptions(token: String? = nil) async throws -> NativePasskeyOptionsResponse {117        try await send(.post, "/native/auth/passkey/options", auth: token.map { .token($0) } ?? .none)118    }119120    public func nativePasskeyVerify(_ request: NativePasskeyVerifyRequest, token: String? = nil) async throws -> NativeLoginResponse {121        try await send(.post, "/native/auth/passkey/verify", body: request, auth: token.map { .token($0) } ?? .none)122    }123124    public func nativeRefreshChallenge(sessionId: String) async throws -> NativeRefreshChallenge {125        try await send(.post, "/native/auth/refresh/challenge", body: ["sessionId": sessionId], auth: .none)126    }127128    /// `signature` = base64 DER ECDSA-P256-SHA256 over `cr-native-refresh:v1:<sessionId>:<challenge>`.129    public func nativeRefresh(sessionId: String, signature: String) async throws -> NativeRefreshResponse {130        try await send(.post, "/native/auth/refresh", body: ["sessionId": sessionId, "signature": signature], auth: .none)131    }132133    /// `POST /auth/logout` — revokes the current session. `token` overrides the stored bearer.134    public func logout(token: String? = nil) async throws {135        try await perform(.post, "/auth/logout", auth: token.map { .token($0) } ?? .session)136    }137138    public func changePassword(current: String, new: String) async throws {139        try await perform(.post, "/auth/password", body: ["currentPassword": current, "newPassword": new])140    }141142    /// Passkeys, browser sessions and native app sessions of the account.143    public func devices() async throws -> [Device] { try await send(.get, "/auth/devices") }144145    /// Removes a passkey or revokes a session (its WebSockets close with 4401).146    public func revokeDevice(id: String) async throws { try await perform(.delete, "/auth/devices/\(seg(id))") }147148    // Second-factor enrolment (also allowed with a restricted bearer: pass `token`).149150    public func totpEnrollStart(token: String? = nil) async throws -> TotpEnrollStart {151        try await send(.post, "/auth/totp/enroll/start", auth: token.map { .token($0) } ?? .session)152    }153154    public func totpEnrollFinish(code: String, token: String? = nil) async throws -> LoginStep {155        try await send(.post, "/auth/totp/enroll/finish", body: ["code": code], auth: token.map { .token($0) } ?? .session)156    }157158    public func removeTotp() async throws { try await perform(.delete, "/auth/totp") }159160    public func passkeyRegisterOptions(token: String? = nil) async throws -> PasskeyCreationOptions {161        try await send(.post, "/auth/passkey/register/options", auth: token.map { .token($0) } ?? .session)162    }163164    public func passkeyRegisterVerify(_ credential: PasskeyRegistrationCredential, label: String?, token: String? = nil) async throws -> LoginStep {165        struct Body: Encodable, Sendable {166            var credential: PasskeyRegistrationCredential167            var label: String?168        }169        return try await send(.post, "/auth/passkey/register/verify", body: Body(credential: credential, label: label.map { String($0.prefix(60)) }),170                              auth: token.map { .token($0) } ?? .session)171    }172173    // Push and summary (contract §3, §4).174175    public func registerPush(_ registration: PushRegistration) async throws -> PushRegistrationResult {176        try await send(.put, "/native/push", body: registration)177    }178179    public func unregisterPush() async throws { try await perform(.delete, "/native/push") }180181    /// `GET /native/info` — published builds, push status, device counts.182    public func nativeInfo() async throws -> NativeInfo { try await send(.get, "/native/info") }183184    public func summary() async throws -> NativeSummary { try await send(.get, "/native/summary") }185}186187// MARK: Projects188189extension APIClient {190    public func workspaceRoots() async throws -> [WorkspaceRoot] { try await send(.get, "/workspace/roots") }191    public func projects() async throws -> [Project] { try await send(.get, "/projects") }192    /// 201; 400 `path_not_found`, 409 `project_exists`.193    public func createProject(_ body: CreateProject) async throws -> Project { try await send(.post, "/projects", body: body, timeout: 300) }194    public func project(id: String) async throws -> Project { try await send(.get, "/projects/\(seg(id))") }195    public func updateProject(id: String, _ body: UpdateProject) async throws -> Project { try await send(.patch, "/projects/\(seg(id))", body: body) }196    /// Unregisters only: files are never deleted.197    public func deleteProject(id: String) async throws { try await perform(.delete, "/projects/\(seg(id))") }198}199200// MARK: Sessions201202extension APIClient {203    /// `archived`: nil = server default (not archived), true = archived ones.204    public func sessions(archived: Bool? = nil) async throws -> [TerminalSession] {205        try await send(.get, "/sessions", query: ["archived": flag(archived)])206    }207    /// 201; 429 `too_many_sessions`.208    public func createSession(_ body: CreateSession) async throws -> TerminalSession { try await send(.post, "/sessions", body: body) }209    public func session(id: String) async throws -> TerminalSession { try await send(.get, "/sessions/\(seg(id))") }210    /// Rename / pin / archive (409 `session_live` when archiving a live session).211    public func updateSession(id: String, _ body: UpdateSession) async throws -> TerminalSession {212        try await send(.patch, "/sessions/\(seg(id))", body: body)213    }214    /// Stops the session process (409 `invalid_state` when it cannot be stopped).215    public func terminateSession(id: String) async throws -> TerminalSession { try await send(.post, "/sessions/\(seg(id))/terminate") }216    /// Re-syncs with the runtime; `restart: true` restarts a RECOVERABLE session (new process).217    public func reconnectSession(id: String, restart: Bool = false) async throws -> TerminalSession {218        try await send(.post, "/sessions/\(seg(id))/reconnect", body: ["restart": restart])219    }220    /// Last screen lines, for an explicit user-requested preview only (409 `session_not_live`).221    public func sessionSnapshot(id: String) async throws -> SessionSnapshot { try await send(.get, "/sessions/\(seg(id))/snapshot") }222    public func conversations(projectId: String) async throws -> [AgentConversation] {223        try await send(.get, "/projects/\(seg(projectId))/conversations")224    }225    /// Terminal stream: binary PTY bytes both ways + JSON control text frames.226    public func openTerminalStream(sessionId: String, cols: Int, rows: Int) async throws -> any WebSocketConnection {227        let size = TerminalLimits.clamp(cols: cols, rows: rows)228        return try await openWebSocket("/sessions/\(seg(sessionId))/stream", query: ["cols": String(size.cols), "rows": String(size.rows)])229    }230    /// `ServerEvent` text frames.231    public func openEventStream() async throws -> any WebSocketConnection { try await openWebSocket("/events") }232}233234// MARK: Files235236extension APIClient {237    public func listFiles(projectId: String, path: String = "") async throws -> [FileEntry] {238        try await send(.get, "/projects/\(seg(projectId))/files", query: ["path": path])239    }240    /// Text files ≤ 2 MiB (413 `payload_too_large`, 415 `binary`).241    public func readFile(projectId: String, path: String) async throws -> FileContent {242        try await send(.get, "/projects/\(seg(projectId))/file", query: ["path": path])243    }244    /// Saves a text file. Pass the `sha256` you loaded as `baseSha256`: a mismatch throws245    /// `APIError` of kind `.conflict` whose `conflictSha256` is the hash now on disk.246    public func writeFile(projectId: String, _ body: WriteFile) async throws -> FileContent {247        try await send(.put, "/projects/\(seg(projectId))/file", body: body)248    }249    public func fsOp(projectId: String, _ op: FsOp) async throws { try await perform(.post, "/projects/\(seg(projectId))/fs", body: op) }250    /// Streams a local file to the project (≤ 200 MiB). 409 `exists` unless `overwrite`.251    public func upload(projectId: String, path: String, from fileURL: URL, overwrite: Bool = false,252                       progress: (@Sendable (TransferProgress) -> Void)? = nil) async throws {253        _ = try await uploadFile("/projects/\(seg(projectId))/upload", query: ["path": path, "overwrite": overwrite ? "1" : nil], from: fileURL, progress: progress)254    }255    /// Streams a project file to `destination`.256    public func download(projectId: String, path: String, to destination: URL,257                         progress: (@Sendable (TransferProgress) -> Void)? = nil) async throws {258        try await downloadFile("/projects/\(seg(projectId))/download", query: ["path": path], to: destination, progress: progress)259    }260    public func searchFiles(projectId: String, query q: String, mode: SearchMode = .name, path: String = "", limit: Int = 100) async throws -> [SearchHit] {261        try await send(.get, "/projects/\(seg(projectId))/search", query: ["q": q, "mode": mode.rawValue, "path": path.isEmpty ? nil : path, "limit": String(limit)])262    }263    public func gitStatus(projectId: String) async throws -> GitStatus { try await send(.get, "/projects/\(seg(projectId))/git/status") }264    public func gitDiff(projectId: String, path: String = "", staged: Bool = false) async throws -> GitDiff {265        try await send(.get, "/projects/\(seg(projectId))/git/diff", query: ["path": path.isEmpty ? nil : path, "staged": staged ? "1" : nil])266    }267}268269// MARK: Tasks270271extension APIClient {272    /// Newest first.273    public func tasks(limit: Int = 100, projectId: String? = nil) async throws -> [AgentTask] {274        try await send(.get, "/tasks", query: ["limit": String(limit), "projectId": projectId])275    }276    /// 201; 403 `host_not_allowed`.277    public func createTask(_ body: CreateTask) async throws -> AgentTask { try await send(.post, "/tasks", body: body) }278    public func task(id: String) async throws -> AgentTask { try await send(.get, "/tasks/\(seg(id))") }279    /// 409 `task_finished`.280    public func cancelTask(id: String) async throws -> AgentTask { try await send(.post, "/tasks/\(seg(id))/cancel") }281    /// Only for finished idempotent tasks (409 `not_idempotent` / `task_active`); returns the NEW task.282    public func retryTask(id: String) async throws -> AgentTask { try await send(.post, "/tasks/\(seg(id))/retry") }283    /// One page of the log (default 1 MiB, max 4 MiB).284    public func taskLog(id: String, offset: Int64 = 0, limit: Int = 1024 * 1024) async throws -> TaskLogChunk {285        let (data, http) = try await sendRaw(.get, "/tasks/\(seg(id))/log", query: ["offset": String(offset), "limit": String(limit)])286        return TaskLogChunk(offset: offset, data: data, totalSize: http.value(forHTTPHeaderField: "X-Log-Size").flatMap(Int64.init))287    }288    /// Live log follower: binary frames from `offset`; closes when the task ended and the log is drained.289    public func openTaskLogStream(taskId: String, offset: Int64 = 0) async throws -> any WebSocketConnection {290        try await openWebSocket("/tasks/\(seg(taskId))/log/stream", query: ["offset": String(offset)])291    }292    public func downloadArtifact(taskId: String, artifactId: String, to destination: URL,293                                 progress: (@Sendable (TransferProgress) -> Void)? = nil) async throws {294        try await downloadFile("/tasks/\(seg(taskId))/artifacts/\(seg(artifactId))", to: destination, progress: progress)295    }296}297298// MARK: Cluster299300extension APIClient {301    public func clusterOverview() async throws -> ClusterOverview { try await send(.get, "/cluster/nodes") }302    public func clusterNode(id: String) async throws -> ClusterNodeDetail { try await send(.get, "/cluster/nodes/\(seg(id))") }303    /// Recorded per-node samples; `minutes` 1…20160 (default 60).304    public func clusterMetrics(node: String? = nil, minutes: Int = 60) async throws -> ClusterMetrics {305        try await send(.get, "/cluster/metrics", query: ["node": node, "minutes": String(minutes)])306    }307    public func clusterApps() async throws -> ClusterApps { try await send(.get, "/cluster/apps") }308    public func clusterIncidents() async throws -> [ClusterIncident] { try await send(.get, "/cluster/incidents") }309    public func clusterTrend() async throws -> ClusterTrend { try await send(.get, "/cluster/trend") }310    public func localModels() async throws -> [LocalModel] { try await send(.get, "/cluster/models") }311    /// Runs a real small completion on the server side (up to 60 s).312    public func testLocalModel(id: String) async throws -> LocalModelTest {313        try await send(.post, "/cluster/models/\(seg(id))/test", timeout: 75)314    }315}316317// MARK: Skills / MCP318319extension APIClient {320    public func skills(projectId: String? = nil) async throws -> [SkillInfo] { try await send(.get, "/skills", query: ["projectId": projectId]) }321    public func skillOp(_ op: SkillOp) async throws { try await perform(.post, "/skills/op", body: op) }322    public func searchSkillRegistry(query q: String, limit: Int = 20) async throws -> SkillRegistrySearch {323        try await send(.get, "/skills/registry/search", query: ["q": q, "limit": String(limit)])324    }325    /// Configuration only by default (immediate). `live` adds real statuses (up to 45 s cold,326    /// cached 60 s by the runtime); `refresh` bypasses that cache.327    public func mcpServers(projectId: String? = nil, live: Bool = false, refresh: Bool = false) async throws -> [McpServerInfo] {328        try await send(.get, "/mcp", query: ["projectId": projectId, "live": live ? "1" : nil, "refresh": refresh ? "1" : nil], timeout: live ? 75 : nil)329    }330    /// 201. `env` and `headers` values are write-only.331    public func addMcpServer(_ body: AddMcpServer) async throws { try await perform(.post, "/mcp", body: body) }332    public func removeMcpServer(name: String, scope: McpScope = .user, projectId: String? = nil) async throws {333        try await perform(.delete, "/mcp/\(seg(name))", query: ["scope": scope.rawValue, "projectId": projectId])334    }335    public func testMcpServer(name: String, scope: McpScope = .user, projectId: String? = nil) async throws -> McpServerInfo {336        try await send(.post, "/mcp/\(seg(name))/test", query: ["scope": scope.rawValue, "projectId": projectId], timeout: 75)337    }338}339340// MARK: System, notifications, settings341342extension APIClient {343    public func systemStatus() async throws -> SystemStatus { try await send(.get, "/system/status") }344    /// Newest first; paginate with `before` = last id received.345    public func audit(limit: Int = 100, before: String? = nil, action: String? = nil) async throws -> [AuditEvent] {346        try await send(.get, "/system/audit", query: ["limit": String(limit), "before": before, "action": action])347    }348    public func notifications(limit: Int = 50, unreadOnly: Bool = false) async throws -> [ServerNotification] {349        try await send(.get, "/notifications", query: ["limit": String(limit), "unread": unreadOnly ? "1" : nil])350    }351    @discardableResult352    public func markNotificationsRead(ids: [String]) async throws -> NotificationsReadResult {353        try await send(.post, "/notifications/read", body: ["ids": ids])354    }355    @discardableResult356    public func markAllNotificationsRead() async throws -> NotificationsReadResult {357        try await send(.post, "/notifications/read", body: ["all": true])358    }359    public func settings() async throws -> UserSettings { try await send(.get, "/settings") }360    /// Replaces the user settings (the whole object).361    public func saveSettings(_ settings: UserSettings) async throws -> UserSettings { try await send(.put, "/settings", body: settings) }362}363
Files main
Menu

Theme