Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Research/VQResearch.swift3// Description: Research Studio (projects, reviews — CONTRACT §5), memory (§6) and the audit trail (§7).4import Foundation56// MARK: projects78/// `GET /api/v2/projects/:id/bundle`9public struct VQProjectBundle: Sendable, Equatable, VQJSONDecodable {10 public var project: VQObjectEnvelope11 public var items: [Item]12 public var data: VQProject { VQProject(json: project.data) }1314 public struct Item: Sendable, Equatable, Identifiable, VQJSONDecodable {15 public var item: VQProject.Item16 /// nil when the target does not exist, is not the person's, or has no server-side store (`notebook`, `dataset`).17 public var resolved: Resolved?18 public var id: String { item.id }19 public init(json j: VQJSON) { item = VQProject.Item(json: j); resolved = j.model("resolved") }20 }21 public struct Resolved: Sendable, Equatable, VQJSONDecodable {22 public var title: String?23 /// `running|done` for a conversation, the job status for a quant job, the review status, `"shared"` for a report, else nil.24 public var status: String?25 public var updatedAt: Date?26 public var summary: String?27 public init(json j: VQJSON) { title = j.optStr("title"); status = j.optStr("status"); updatedAt = j.date("updatedAt"); summary = j.optStr("summary") }28 }29 public init(json j: VQJSON) { project = VQObjectEnvelope(json: j["project"] ?? .null); items = j.models("items") }30}3132/// `POST /api/v2/projects/:id/run` → 20233public struct VQProjectRun: Sendable, Equatable, VQJSONDecodable {34 public var generationId: String35 public var sessionId: String36 public init(json j: VQJSON) { generationId = j.str("generationId"); sessionId = j.str("sessionId") }37}3839public enum VQExportFormat: String, Sendable, Hashable, CaseIterable { case pdf, md, tex, zip }4041/// `POST /api/v2/projects/:id/export`42public struct VQProjectExport: Sendable, Equatable, VQJSONDecodable {43 public var filename: String44 /// Server path of the file (`/api/download/<filename>`); files are removed after 7 days.45 public var url: String46 public var format: String47 public var bytes: Int?48 public var items: Int?49 /// false for `tex` and `zip`: the LaTeX source is not compiled by the server.50 public var compiled: Bool?51 public init(json j: VQJSON) {52 filename = j.str("filename"); url = j.str("url"); format = j.str("format"); bytes = j.int("bytes"); items = j.int("items"); compiled = j.optFlag("compiled")53 }54}5556/// Per-generation limits (`budget` of `/api/chat` and of a project run).57public struct VQBudget: Sendable, Equatable {58 public var maxCostUsd: Double?59 public var maxMinutes: Double?60 public init(maxCostUsd: Double? = nil, maxMinutes: Double? = nil) { self.maxCostUsd = maxCostUsd; self.maxMinutes = maxMinutes }61 public var json: VQJSON {62 var o: VQJSONObject = [:]63 if let maxCostUsd { o["maxCostUsd"] = .number(maxCostUsd) }64 if let maxMinutes { o["maxMinutes"] = .number(maxMinutes) }65 return .object(o)66 }67}6869// MARK: memory7071public struct VQMemory: Sendable, Equatable, Identifiable, VQJSONDecodable {72 public enum Kind: String, Sendable, Hashable, CaseIterable { case preference, project, knowledge, summary, dataset }73 public enum Source: String, Sendable, Hashable, CaseIterable { case agent, user }74 public var id: String75 public var content: String76 public var category: String?77 public var createdAt: Date?78 public var scope: VQMemoryScope79 public var kind: VQOpen<Kind>?80 public var expiresAt: Date?81 public var pinned: Bool82 public var source: VQOpen<Source>?83 public init(json j: VQJSON) {84 id = j["id"]?.displayString ?? ""; content = j.str("content"); category = j.optStr("category"); createdAt = j.date("createdAt")85 scope = VQMemoryScope(j.str("scope", "user")); kind = j.optOpen("kind"); expiresAt = j.date("expiresAt"); pinned = j.flag("pinned"); source = j.optOpen("source")86 }87}8889/// `user` or `project:<id>`.90public enum VQMemoryScope: Sendable, Hashable {91 case user92 case project(String)93 case other(String)94 public init(_ raw: String) {95 if raw == "user" { self = .user }96 else if raw.hasPrefix("project:") { self = .project(String(raw.dropFirst(8))) }97 else { self = .other(raw) }98 }99 public var rawValue: String {100 switch self {101 case .user: return "user"102 case .project(let id): return "project:\(id)"103 case .other(let s): return s104 }105 }106}107108public struct VQMemorySettings: Sendable, Equatable, VQJSONDecodable {109 /// false: nothing is injected into conversations and the agent's `memory_save` is refused.110 public var enabled: Bool111 /// nil = kept until deleted.112 public var retentionDays: Int?113 public init(enabled: Bool, retentionDays: Int?) { self.enabled = enabled; self.retentionDays = retentionDays }114 public init(json j: VQJSON) { enabled = j.flag("enabled", true); retentionDays = j.int("retentionDays") }115}116117/// `GET /api/v2/memory`118public struct VQMemoryOverview: Sendable, Equatable, VQJSONDecodable {119 public var settings: VQMemorySettings120 /// The `user` group first, always present.121 public var groups: [Group]122 public var count: Int123 public struct Group: Sendable, Equatable, Identifiable, VQJSONDecodable {124 public var scope: VQMemoryScope125 public var projectId: String?126 public var projectTitle: String?127 public var memories: [VQMemory]128 public var id: String { scope.rawValue }129 public init(json j: VQJSON) {130 scope = VQMemoryScope(j.str("scope", "user")); projectId = j["project"]?.optStr("id"); projectTitle = j["project"]?.optStr("title"); memories = j.models("memories")131 }132 }133 public init(json j: VQJSON) { settings = VQMemorySettings(json: j["settings"] ?? .null); groups = j.models("groups"); count = j.int("count") ?? 0 }134}135136/// Fields of `PATCH /api/workspace/memories/:id` and of the additive part of `POST /api/workspace/memories`.137public struct VQMemoryChange: Sendable, Equatable {138 public var content: String?139 public var category: String?140 public var kind: VQMemory.Kind?141 public var scope: VQMemoryScope?142 public var pinned: Bool?143 /// `.some(nil)` clears the expiry.144 public var expiresAt: Date??145 public init(content: String? = nil, category: String? = nil, kind: VQMemory.Kind? = nil, scope: VQMemoryScope? = nil, pinned: Bool? = nil, expiresAt: Date?? = nil) {146 self.content = content; self.category = category; self.kind = kind; self.scope = scope; self.pinned = pinned; self.expiresAt = expiresAt147 }148 var json: VQJSON {149 var o: VQJSONObject = [:]150 if let content { o["content"] = .string(content) }151 if let category { o["category"] = .string(category) }152 if let kind { o["kind"] = .string(kind.rawValue) }153 if let scope { o["scope"] = .string(scope.rawValue) }154 if let pinned { o["pinned"] = .bool(pinned) }155 if let expiresAt { o["expiresAt"] = expiresAt.map { .number(($0.timeIntervalSince1970 * 1000).rounded()) } ?? .null }156 return .object(o)157 }158}159160// MARK: audit161162public struct VQAuditEvent: Sendable, Equatable, Identifiable, VQJSONDecodable {163 public var id: Int164 public var at: Date?165 public var device: String?166 /// `signin.web`, `signin.native`, `device.revoke`, `object.delete`, `project.export`, `memory.bulk_delete`, … (open list)167 public var action: String168 /// e.g. `<kind>/<id>` for `object.delete`.169 public var target: String?170 public var ip: String?171 /// Never carries a secret or a download file name.172 public var detail: VQJSON?173 public init(json j: VQJSON) {174 id = j.int("id") ?? 0; at = j.date("at"); device = j.optStr("device"); action = j.str("action"); target = j.optStr("target"); ip = j.optStr("ip")175 detail = j["detail"].flatMap { $0.isNull ? nil : $0 }176 }177}178179// MARK: client180181public struct VQResearchClient: Sendable {182 public let client: VQClient183 public init(client: VQClient) { self.client = client }184185 public func bundle(project id: String) async throws -> VQProjectBundle {186 try await client.decode(.get("/api/v2/projects/\(VQRequest.segment(id))/bundle"))187 }188189 /// Starts an analysis inside the project (202). Follow it with the app's generation stream190 /// (`/api/generations/:id/stream`); the conversation is appended to `project.items` at once.191 public func run(project id: String, prompt: String, mode: String? = nil, model: String? = nil, budget: VQBudget? = nil) async throws -> VQProjectRun {192 var body: VQJSONObject = ["prompt": .string(prompt)]193 if let mode { body["mode"] = .string(mode) }194 if let model { body["model"] = .string(model) }195 if let budget { body["budget"] = budget.json }196 return try await client.decode(VQRequest(.post, "/api/v2/projects/\(VQRequest.segment(id))/run", body: .object(body)))197 }198199 /// Builds the export document; download `url` with the app's own client. `include` nil = every item.200 /// `pdf` answers 502 (`VQError.unavailable`) with a plain sentence when the renderer is not available.201 public func export(project id: String, format: VQExportFormat, include: [String]? = nil) async throws -> VQProjectExport {202 var body: VQJSONObject = ["format": .string(format.rawValue)]203 if let include { body["include"] = VQJSON(include) }204 return try await client.decode(VQRequest(.post, "/api/v2/projects/\(VQRequest.segment(id))/export", body: .object(body), timeout: 180))205 }206207 /// Starts an automated review (202) and returns the id of the `review` object that will hold it — it arrives208 /// through sync (`VQSyncedCollection<VQReview>`), first with the deterministic checks, then with the reviewer's.209 public func startReview(of target: VQReview.Target, projectId: String? = nil) async throws -> String {210 var body: VQJSONObject = ["target": target.json]211 if let projectId { body["projectId"] = .string(projectId) }212 return try await client.json(VQRequest(.post, "/api/v2/reviews", body: .object(body))).str("reviewId")213 }214215 // memory216217 public func memory() async throws -> VQMemoryOverview { try await client.decode(.get("/api/v2/memory")) }218219 public func setMemorySettings(enabled: Bool? = nil, retentionDays: Int?? = nil) async throws -> VQMemorySettings {220 var body: VQJSONObject = [:]221 if let enabled { body["enabled"] = .bool(enabled) }222 if let retentionDays { body["retentionDays"] = retentionDays.map { .number(Double($0)) } ?? .null }223 let j = try await client.json(VQRequest(.put, "/api/v2/memory/settings", body: .object(body)))224 return VQMemorySettings(json: j["settings"] ?? j)225 }226227 public func addMemory(content: String, change: VQMemoryChange = VQMemoryChange()) async throws -> VQMemory {228 var body = change.json.objectValue ?? [:]229 body["content"] = .string(content)230 let j = try await client.json(VQRequest(.post, "/api/workspace/memories", body: .object(body)))231 return VQMemory(json: j["memory"] ?? j)232 }233234 public func updateMemory(_ id: String, _ change: VQMemoryChange) async throws -> VQMemory {235 let j = try await client.json(VQRequest(.patch, "/api/workspace/memories/\(VQRequest.segment(id))", body: change.json))236 return VQMemory(json: j["memory"] ?? j)237 }238239 /// Bulk deletion — explicit by design: pass `.user`, `.project(id)` or `nil` for **all**. Returns the count. Audited.240 public func deleteMemories(scope: VQMemoryScope?) async throws -> Int {241 try await client.json(VQRequest(.delete, "/api/v2/memory", query: [VQQueryItem("scope", scope?.rawValue ?? "all")])).int("deleted") ?? 0242 }243244 /// The JSON export (`{ exportedAt, settings, memories }`) as bytes to save. Audited.245 public func exportMemories() async throws -> Data { try await client.data(.get("/api/v2/memory/export")) }246247 // audit248249 /// Own events, newest first; `before` = id of the last event of the previous page.250 public func audit(limit: Int = 100, before: Int? = nil) async throws -> [VQAuditEvent] {251 let q = [VQQueryItem("limit", String(min(500, max(1, limit))))] + VQQueryItem.optional("before", before.map(String.init))252 return try await client.json(.get("/api/v2/audit", q)).models("events")253 }254}255