SPB Git

Repository Public

VQGeneration.swift 9.0 KB 178 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Models/VQGeneration.swift3// Description: What backend 6 adds to generations: stream events, the execution trace, provenance (CONTRACT §2.2–2.4).4//              The apps keep decoding the v5 events themselves; this decoder never throws and hands back what it5//              does not own.6import Foundation78/// One line of provenance: a tool that really ran, for a set of symbols.9public struct VQProvenanceSource: Sendable, Equatable, VQJSONDecodable {10    public enum Provider: String, Sendable, Hashable, CaseIterable { case fmp, findata, eodhd, web, python, quantEngine = "quant-engine", other }11    public var tool: String12    public var provider: VQOpen<Provider>13    public var symbols: [String]14    public var retrievedAt: Date?15    /// At least one call succeeded.16    public var ok: Bool17    public var calls: Int18    public init(json j: VQJSON) {19        tool = j.str("tool"); provider = j.open("provider", .other); symbols = j.strings("symbols"); retrievedAt = j.date("retrievedAt")20        ok = j.flag("ok", true); calls = j.int("calls") ?? 121    }22}2324/// `{ type: "budget", kind: "cost"|"minutes", limit, spent }` — emitted once per kind when a budget is exceeded.25public struct VQBudgetEvent: Sendable, Hashable, VQJSONDecodable {26    public enum Kind: String, Sendable, Hashable, CaseIterable { case cost, minutes }27    public var kind: VQOpen<Kind>28    public var limit: Double?29    public var spent: Double?30    public init(json j: VQJSON) { kind = j.open("kind", .cost); limit = j.num("limit"); spent = j.num("spent") }31}3233/// The limits a generation runs under: the first event of every generation (`budget_applied`) and `budgetApplied`34/// in the trace and in a workspace's `generations`. The event reaches `VQGenerationEvent` as `.other("budget_applied")`35/// (no new case, for source compatibility): read it with `VQBudgetApplied(event:)`.36public struct VQBudgetApplied: Sendable, Hashable, VQJSONDecodable {37    public enum Source: String, Sendable, Hashable, CaseIterable { case request, preference, `default` }38    /// nil = no cost limit.39    public var maxCostUsd: Double?40    public var maxMinutes: Double?41    public var source: VQOpen<Source>42    public init(json j: VQJSON) { maxCostUsd = j.num("maxCostUsd"); maxMinutes = j.num("maxMinutes"); source = j.open("source", .default) }43    /// nil unless the payload is a `budget_applied` event.44    public init?(event j: VQJSON) { guard j.str("type") == "budget_applied" else { return nil }; self.init(json: j) }45}4647/// `{ type: "quant_job", tool: "run_quant_engine", toolId, agent, jobId, engine, status }` — the agent ran a Quant Lab engine; the full result is the job.48public struct VQQuantJobEvent: Sendable, Equatable, VQJSONDecodable {49    public var tool: String50    public var toolId: String?51    public var agent: String?52    public var jobId: String53    public var engine: String54    public var status: VQOpen<VQQuantJob.Status>55    public init(json j: VQJSON) {56        tool = j.str("tool"); toolId = j.optStr("toolId"); agent = j.optStr("agent"); jobId = j.str("jobId"); engine = j.str("engine")57        status = j.open("status", .done)58    }59}6061/// The events backend 6 adds to a generation stream. Everything else — the v5 events the apps already handle and any62/// event added later — comes back as `.other` with its payload: decoding never throws.63public enum VQGenerationEvent: Sendable, Equatable {64    /// Before the first token, only when `model: "auto"` was requested.65    case modelRouted(VQRouteDecision)66    case budget(VQBudgetEvent)67    case quantJob(VQQuantJobEvent)68    /// At the end of a generation.69    case provenance([VQProvenanceSource])70    /// `done`, with the `usage` backend 6 adds (nil from an older server).71    case done(sessionId: String?, usage: VQUsage?)72    case other(type: String, payload: VQJSON)7374    public init(json j: VQJSON) {75        let type = j["type"]?.stringValue ?? ""76        switch type {77        case "model_routed": self = .modelRouted(VQRouteDecision(json: j))78        case "budget": self = .budget(VQBudgetEvent(json: j))79        case "quant_job": self = .quantJob(VQQuantJobEvent(json: j))80        case "provenance": self = .provenance(j.models("sources"))81        case "done": self = .done(sessionId: j.optStr("sessionId"), usage: j.model("usage"))82        default: self = .other(type: type, payload: j)83        }84    }85    public init(_ event: VQSSEEvent) { self.init(json: event.json) }8687    /// The `role` backend 6 adds to agent events (`agent_start`, …): `market_analyst`, `quant_researcher`, …88    public static func agentRole(of payload: VQJSON) -> String? { payload.optStr("role") }8990    /// The server time every event of a generation carries (`at`, epoch ms) — nil on the `job` frame and from older servers.91    public static func time(of payload: VQJSON) -> Date? { payload.date("at") }92}9394/// `GET /api/v2/generations/:id/trace` — only real executions; nothing is simulated.95public struct VQGenerationTrace: Sendable, Equatable, VQJSONDecodable {96    public enum Status: String, Sendable, Hashable, CaseIterable { case running, done, error, cancelled }97    public var generationId: String98    public var sessionId: String?99    public var status: VQOpen<Status>100    public var startedAt: Date?101    public var finishedAt: Date?102    public var mode: String?103    public var model: String?104    public var requestedModel: String?105    public var plan: [PlanStep]106    public var agents: [Agent]107    public var budget: [VQBudgetEvent]108    public var toolCalls: [ToolCall]109    public var usage: VQUsage?110    /// The limits the generation ran under (nil from a server that does not say).111    public var budgetApplied: VQBudgetApplied?112113    public struct PlanStep: Sendable, Equatable, VQJSONDecodable {114        public var title: String115        public var status: String116        public init(json j: VQJSON) { title = j.str("title"); status = j.str("status") }117    }118    public struct Agent: Sendable, Equatable, Identifiable, VQJSONDecodable {119        public enum Status: String, Sendable, Hashable, CaseIterable { case running, done, failed }120        public var id: String121        public var name: String122        public var kind: String?123        public var role: String?124        public var status: VQOpen<Status>125        public var startedAt: Date?126        public var durationMs: Double?127        /// Number of tool calls (or their names, depending on the server version: both are read).128        public var toolCount: Int?129        public var toolNames: [String]130        public init(json j: VQJSON) {131            id = j.str("id"); name = j.str("name"); kind = j.optStr("kind"); role = j.optStr("role"); status = j.open("status", .running)132            startedAt = j.date("startedAt"); durationMs = j.num("durationMs")133            toolNames = j.strings("tools"); toolCount = j.int("tools") ?? (j["tools"]?.arrayValue?.count)134        }135    }136    public struct ToolCall: Sendable, Equatable, VQJSONDecodable {137        public var at: Date?138        public var agent: String?139        public var tool: String140        public var ok: Bool141        public var ms: Double?142        public var error: String?143        public init(json j: VQJSON) { at = j.date("at"); agent = j.optStr("agent"); tool = j.str("tool"); ok = j.flag("ok"); ms = j.num("ms"); error = j.optStr("error") }144    }145    public init(json j: VQJSON) {146        generationId = j.str("generationId"); sessionId = j.optStr("sessionId"); status = j.open("status", .running)147        startedAt = j.date("startedAt"); finishedAt = j.date("finishedAt"); mode = j.optStr("mode"); model = j.optStr("model")148        requestedModel = j.optStr("requestedModel"); plan = j.models("plan"); agents = j.models("agents"); budget = j.models("budget")149        toolCalls = j.models("toolCalls"); usage = j.model("usage"); budgetApplied = j.model("budgetApplied")150    }151}152153/// What backend 6 adds to each entry of `messages` in `GET /api/sessions/:id` (the apps keep their own decoding of154/// the rest). The legacy route returns `messages` either as an array or as a JSON string holding one: both are read.155public struct VQMessageExtras: Sendable, Equatable, VQJSONDecodable {156    public var provenance: [VQProvenanceSource]157    public var model: String?158    public var generationId: String?159    public var usage: VQUsage?160    public init(json j: VQJSON) {161        provenance = j.models("provenance"); model = j.optStr("model"); generationId = j.optStr("generationId"); usage = j.model("usage")162    }163    public var isEmpty: Bool { provenance.isEmpty && model == nil && generationId == nil && usage == nil }164165    /// One entry per message of a session payload, in order.166    public static func ofSession(_ session: VQJSON) -> [VQMessageExtras] {167        messages(of: session).map(VQMessageExtras.init(json:))168    }169    /// The raw message objects of a session payload (array, or JSON text of one).170    public static func messages(of session: VQJSON) -> [VQJSON] {171        switch session["messages"] {172        case .array(let a)?: return a173        case .string(let s)?: return (try? VQJSON.parse(s))?.arrayValue ?? []174        default: return []175        }176    }177}178
Files main
Menu

Theme