SPB Git

Repository Public

VQResearchAgentClient.swift 6.8 KB 109 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/ResearchAgent/VQResearchAgentClient.swift3// Description: The research REST of CONTRACT §9.6, one call each. `id` is a workspace id (`s-…`, `p-…`) or4//              `VQResearchSession.reference(sessionId:)`.5import Foundation67public struct VQResearchAgentClient: Sendable {8    public let client: VQClient9    public init(client: VQClient) { self.client = client }1011    private func base(_ id: String) -> String { "/api/v2/research/sessions/\(VQRequest.segment(id))" }1213    /// Workspaces of the signed-in person, newest first.14    public func sessions() async throws -> [VQResearchSession] { try await client.json(.get("/api/v2/research/sessions")).models("sessions") }1516    /// Creates a workspace before the first message (to upload a dataset). Chat with the returned `sessionId`.17    public func createSession(title: String? = nil, projectId: String? = nil, sessionId: String? = nil) async throws -> (session: VQResearchSession, sessionId: String) {18        var body: VQJSONObject = [:]19        if let title { body["title"] = .string(title) }20        if let projectId { body["projectId"] = .string(projectId) }21        if let sessionId { body["sessionId"] = .string(sessionId) }22        let j = try await client.json(VQRequest(.post, "/api/v2/research/sessions", body: .object(body)))23        return (VQResearchSession(json: j["session"] ?? .null), j.str("sessionId"))24    }2526    /// Everything the workspace holds: files, ledger, runs, notes, library, environment, approvals.27    public func session(_ id: String) async throws -> VQResearchSessionDetail { try await client.decode(.get(base(id), timeout: 60)) }2829    /// The file tree (flat listing; build a tree with `VQResearchFileTree`).30    public func files(_ id: String, path: String = "", recursive: Bool = true) async throws -> [VQResearchFile] {31        try await client.json(.get(base(id) + "/files", [VQQueryItem("path", path)] + (recursive ? [VQQueryItem("recursive", "1")] : []))).models("files")32    }3334    /// A text file (code, CSV, JSON, log, lockfile), by lines. `offset` is 0-based.35    public func textFile(_ id: String, path: String, offset: Int? = nil, limit: Int? = nil) async throws -> VQResearchFilePreview {36        let q = [VQQueryItem("path", path)] + VQQueryItem.optional("offset", offset.map(String.init)) + VQQueryItem.optional("limit", limit.map(String.init))37        return try await client.decode(.get(base(id) + "/file", q, timeout: 60))38    }3940    /// The bytes of a file (figures as PNG / SVG / PDF, datasets, anything to save or share).41    public func fileData(_ id: String, path: String) async throws -> Data {42        try await client.data(.get(base(id) + "/file", [VQQueryItem("path", path), VQQueryItem("download", "1")], timeout: 120))43    }4445    /// The request of `fileData`, for an app that downloads through its own (background) session.46    public func fileRequest(_ id: String, path: String) -> VQRequest {47        .get(base(id) + "/file", [VQQueryItem("path", path), VQQueryItem("download", "1")], timeout: 120)48    }4950    /// Removes a file or a directory of the workspace. 400 (`VQError.rejected`) for a path outside the workspace, an51    /// internal sandbox directory or a directory of the layout (`code`, `data`…); 404 when absent. Audited.52    @discardableResult53    public func deleteFile(_ id: String, path: String) async throws -> String {54        try await client.json(VQRequest(.delete, base(id) + "/files", query: [VQQueryItem("path", path)])).str("path", path)55    }5657    public func inspect(_ id: String, path: String) async throws -> VQDatasetInspection {58        try await client.decode(.get(base(id) + "/inspect", [VQQueryItem("path", path)], timeout: 120))59    }6061    /// The ledger, oldest first. `kind` nil = both kinds.62    public func experiments(_ id: String, kind: VQLedgerEntry.Kind? = nil) async throws -> [VQLedgerEntry] {63        try await client.json(.get(base(id) + "/experiments", VQQueryItem.optional("kind", kind?.rawValue))).models("experiments")64    }6566    /// Runs, newest first.67    public func runs(_ id: String) async throws -> [VQResearchRun] { try await client.json(.get(base(id) + "/runs")).models("runs") }6869    /// A run with the ends of its logs (`tail` characters).70    public func run(_ runId: String, tail: Int? = nil) async throws -> VQRunLogs {71        try await client.decode(.get("/api/v2/research/runs/\(VQRequest.segment(runId))", VQQueryItem.optional("tail", tail.map(String.init))))72    }7374    public func cancelRun(_ runId: String) async throws -> VQResearchRun {75        let j = try await client.json(VQRequest(.post, "/api/v2/research/runs/\(VQRequest.segment(runId))/cancel"))76        return VQResearchRun(json: j["run"] ?? j)77    }7879    /// Approvals of the person; `pendingOnly` for the ones waiting for an answer.80    public func approvals(pendingOnly: Bool = true) async throws -> [VQResearchApproval] {81        try await client.json(.get("/api/v2/research/approvals", pendingOnly ? [VQQueryItem("status", "pending")] : [])).models("approvals")82    }8384    /// Answers a request. `VQError.notFound` when it is not the person's or no longer pending (expired, answered elsewhere).85    public func answer(approval id: String, _ decision: VQResearchApproval.Decision) async throws -> VQResearchApproval {86        let j = try await client.json(VQRequest(.post, "/api/v2/research/approvals/\(VQRequest.segment(id))", body: ["decision": .string(decision.rawValue)]))87        return VQResearchApproval(json: j["approval"] ?? j)88    }8990    public func sandbox() async throws -> VQSandboxStatus { try await client.decode(.get("/api/v2/research/sandbox")) }9192    /// Whether to offer the `research` mode: it is available exactly when the sandbox route answers (the mode is not93    /// announced by `/api/config`). Returns the status to show next to the mode, nil when the server has no research agent.94    public func researchModeAvailability() async -> VQSandboxStatus? { try? await sandbox() }9596    /// Uploads a dataset into `data/`. Checks extension, size and signature first (`VQDatasetUpload.Refusal` is thrown97    /// without sending); the server checks again (415 / 413 → `VQDatasetUpload.message(for:)`).98    public func upload(_ id: String, name: String, data: Data, maxBytes: Int = VQDatasetUpload.defaultMaxBytes) async throws -> VQUploadedFile {99        if let refusal = VQDatasetUpload.validate(name: name, size: data.count, head: data.prefix(4096), maxBytes: maxBytes) { throw refusal }100        let form = VQDatasetUpload.multipart(name: name, data: data)101        return try await client.decode(.raw(.post, base(id) + "/upload", body: form.body, contentType: form.contentType, timeout: 600))102    }103}104105public extension VQuantAPI {106    /// The autonomous research agent's workspace (CONTRACT §9). `research` is the projects/reviews/memory client of §5–7.107    var researchAgent: VQResearchAgentClient { VQResearchAgentClient(client: client) }108}109
Files main
Menu

Theme