Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Agents/AgentsModels.swift3// Description: Models of the trading agents (services/api/src/agents/routes.ts, strategies.ts, runtime-routes.ts, agent-runtime/store.ts):4// the three modes as distinct values, agents and their vault, withdrawals back to the owner, the strategy library,5// backtest reports (always typed as simulation), the agent panel (summary, journal, orders, performance, jobs,6// workers, kill-switch state). A figure of one mode can never be read without that mode.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112// MARK: modes1314/**15 The mode a record belongs to. The server writes it in two vocabularies (`research|paper|live` in the agent panel, `RESEARCH|PAPER|LIVE`16 in the historical views); both decode here. `research` produces backtests and decisions, never an order; `paper` is an explicit17 simulation; only `live` touches a venue or a chain. A value this code does not know is `.unknown` and is never treated as any of them.18 */19public enum AgentMode: String, Codable, Sendable, CaseIterable, Hashable {20 case research, paper, live21 case unknown2223 public init(from decoder: Decoder) throws { self = AgentMode(server: try decoder.singleValueContainer().decode(String.self)) }24 public init(server s: String) {25 switch s { case "research", "RESEARCH": self = .research; case "paper", "PAPER": self = .paper; case "live", "LIVE": self = .live; default: self = .unknown }26 }27 /** True only for `live`: orders reached a venue or a chain. (A live perp agent on the venue's TEST network still trades test money: see `Agent.liveNetwork`.) */28 public var isLive: Bool { self == .live }29 /** True for research and paper: nothing was signed, no money moved. False for `unknown` too: an unknown mode is not asserted to be a simulation. */30 public var isSimulation: Bool { self == .research || self == .paper }31 /** The query value of the mode-scoped reads. */32 var query: String? { self == .unknown ? nil : rawValue }33}3435/** A value read for exactly ONE mode. There is no way to obtain `value` without the mode next to it. */36public struct ModeScoped<Value: Sendable>: Sendable {37 public let mode: AgentMode38 public let value: Value39 public init(mode: AgentMode, value: Value) { self.mode = mode; self.value = value }40}41extension ModeScoped: Equatable where Value: Equatable {}4243/** `active | paused | stopped`: the projection of the historical `agents.state` the agent panel uses. */44public enum AgentLifecycle: String, Codable, Sendable, CaseIterable {45 case active, paused, stopped46 case unknown47 public init(from decoder: Decoder) throws { self = AgentLifecycle(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .unknown }48}4950/** `spot` (a vault and a swap mandate), `perp` (a paper account, live under a derivative mandate), `stream` (built-in rule), `supervisor` (risk management). */51public enum AgentKind: String, Codable, Sendable, CaseIterable {52 case spot, perp, stream, supervisor53 case unknown54 public init(from decoder: Decoder) throws { self = AgentKind(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .unknown }55}5657// MARK: lenient scalars (database columns arrive as text or as numbers depending on their type)5859/** A numeric or textual column kept as the exact text the server sent (never converted through floating point when it was text). */60public struct ServerText: Codable, Sendable, Hashable, CustomStringConvertible {61 public let text: String62 public init(_ text: String) { self.text = text }63 public init(from decoder: Decoder) throws {64 let c = try decoder.singleValueContainer()65 if let s = try? c.decode(String.self) { text = s }66 else if let i = try? c.decode(Int64.self) { text = String(i) }67 else { text = String(try c.decode(Double.self)) }68 }69 public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(text) }70 public var description: String { text }71}7273/** A price / estimate column that may arrive as a number or as numeric text. Never an amount to approve. */74public struct ServerNumber: Codable, Sendable, Hashable {75 public let value: Double76 public init(from decoder: Decoder) throws {77 let c = try decoder.singleValueContainer()78 if let d = try? c.decode(Double.self) { value = d; return }79 guard let d = Double(try c.decode(String.self)) else { throw DecodingError.dataCorruptedError(in: c, debugDescription: "not a number") }80 value = d81 }82 public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(value) }83}8485/**86 A USD limit the owner typed, kept as decimal text (at most 7 integer digits and 6 decimals) so that it can be compared exactly with87 what a mandate says. Sent to the server as a JSON number (the server's schema is numeric); read back from the server's number.88 */89public struct USDLimit: Codable, Sendable, Hashable, CustomStringConvertible {90 /** Canonical text: no leading zero, no trailing zero, "." as the separator. */91 public let text: String9293 public init(_ input: String) throws(AmountError) {94 guard input.range(of: #"^\d{1,7}(\.\d{1,6})?$"#, options: .regularExpression) != nil else { throw .invalid }95 text = Self.normalize(input)96 }97 private static func normalize(_ s: String) -> String {98 var t = s99 if t.contains(".") { while t.last == "0" { t.removeLast() }; if t.last == "." { t.removeLast() } }100 while t.count > 1, t.first == "0", !t.hasPrefix("0.") { t.removeFirst() }101 return t102 }103 public init(from decoder: Decoder) throws {104 let c = try decoder.singleValueContainer()105 let raw: String106 if let i = try? c.decode(Int64.self) { raw = String(i) } else { raw = String(try c.decode(Double.self)) }107 // a limit whose shortest decimal form is not plain (exponent) or has more than 6 decimals cannot be compared exactly: refused, never rounded108 do { self = try USDLimit(raw) } catch { throw DecodingError.dataCorruptedError(in: c, debugDescription: "USD limit \(raw) cannot be represented exactly") }109 }110 public func encode(to encoder: Encoder) throws {111 var c = encoder.singleValueContainer()112 if let i = Int64(text) { try c.encode(i) } else { try c.encode(Decimal(string: text, locale: Locale(identifier: "en_US_POSIX"))!) }113 }114 public var description: String { text }115 /** The limit in base units of an asset worth 1 USD per unit (the cash leg), exactly. */116 public func baseUnits(decimals: Int) throws(AmountError) -> BaseUnits { try BaseUnits.parse(text, decimals: decimals) }117}118119// MARK: risk settings (the limits the owner chooses; a mandate is derived from them)120121/** Limits of a spot agent (`Risk` in agents/routes.ts). Every field is required here: the server's defaults are never applied silently. */122public struct SpotAgentRisk: Codable, Sendable, Equatable {123 /** Share of the vault that may be invested in non-cash assets, percent (1–100). */124 public let maxExposurePct: Double125 /** The ENGINE stops the agent when equity falls this far below the capital, percent (1–100). Not enforced by the signer; a gap can overshoot it. */126 public let maxLossPct: Double127 /** Largest input of one order, USD (1–100 000). Becomes a per-asset base-unit cap of the mandate at the prices of the preparation. */128 public let maxOrderUsd: USDLimit129 /** Total input per UTC day, USD (1–1 000 000). */130 public let maxDailyUsd: USDLimit131 /** 1–200. */132 public let maxOrdersPerDay: Int133 /** Validity of the mandate, days (1–90). */134 public let mandateDays: Int135 /** 5–300. The mandate's own slippage guard is `min(500, max(150, slippageBps + 80))`. */136 public let slippageBps: Int137138 public init(maxExposurePct: Double, maxLossPct: Double, maxOrderUsd: USDLimit, maxDailyUsd: USDLimit, maxOrdersPerDay: Int, mandateDays: Int, slippageBps: Int) {139 self.maxExposurePct = maxExposurePct; self.maxLossPct = maxLossPct; self.maxOrderUsd = maxOrderUsd; self.maxDailyUsd = maxDailyUsd140 self.maxOrdersPerDay = maxOrdersPerDay; self.mandateDays = mandateDays; self.slippageBps = slippageBps141 }142 /** `maxSlippageBps` of the mandate the server builds from these limits (routes.ts `mandateFor`). */143 public var mandateSlippageBps: Int { min(500, max(150, slippageBps + 80)) }144}145146/** Limits of a perp agent (`PerpRisk` in agents/perp-engine.ts). Every field is required. */147public struct PerpAgentRisk: Codable, Sendable, Equatable {148 /** Account leverage and leverage setting of every order, integer 1–5. */149 public let maxLeverage: Int150 /** Gross exposure as a multiple of the capital (0.1–5). */151 public let maxGrossExposureX: Double152 /** Position on one instrument as a multiple of the capital (0.05–5). */153 public let maxPositionX: Double154 /** Loss in one UTC day, percent of the capital (0.01–50): flatten, then stop. Must not exceed the total. */155 public let maxDailyLossPct: Double156 /** Loss since creation, percent of the capital (0.01–90). */157 public let maxTotalLossPct: Double158 /** 5–100. */159 public let slippageBps: Int160 /** A rebalance smaller than this share of equity is not traded, percent. */161 public let minTradePct: Double162163 public init(maxLeverage: Int, maxGrossExposureX: Double, maxPositionX: Double, maxDailyLossPct: Double, maxTotalLossPct: Double, slippageBps: Int, minTradePct: Double) {164 self.maxLeverage = maxLeverage; self.maxGrossExposureX = maxGrossExposureX; self.maxPositionX = maxPositionX; self.maxDailyLossPct = maxDailyLossPct165 self.maxTotalLossPct = maxTotalLossPct; self.slippageBps = slippageBps; self.minTradePct = minTradePct166 }167}168169// MARK: agents (list / detail of /api/v1/agents)170171public struct AgentWarning: Codable, Sendable, Hashable { public let code: String; public let message: String }172173/** One registry asset an agent holds for a market symbol (`holdings` of the spot view). */174public struct AgentHolding: Codable, Sendable, Hashable {175 /** Market symbol (the cash symbol for the cash leg). */176 public let symbol: String177 /** `native` or the token contract. */178 public let asset: String179 public let assetSymbol: String180 public let name: String181 /** `cash`, `native`, `token`, `wrapped`, `pegged`. */182 public let kind: String183 public let issuer: String?184 public var isCash: Bool { kind == "cash" }185}186187/** What the agent row remembers of its spot mandate (the mandate itself lives at the signer). */188public struct AgentMandateSummary: Codable, Sendable, Hashable {189 /** Unix seconds. */190 public let expiresAt: Int191 public let label: String192 public let strategySha256: String193 public let maxOrdersPerDay: Int194 public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt)) }195 public func isExpired(at now: Date = Date()) -> Bool { now >= expiry }196}197198/**199 An agent as the list and the creation routes answer it: `view` (spot), `perpView` (perp) or `runtimeView` (stream / supervisor) of the200 backend, one struct with the fields that exist for its kind. `mode` is the mode it is in now; `state` is the historical state text201 (CREATED, AWAITING_APPROVAL, PAPER_TRADING, LIVE, PAUSED, STOPPING, STOPPED, RUNNING…), shown verbatim when unknown.202 */203public struct Agent: Codable, Sendable, Hashable, Identifiable {204 public let id: String205 /** Absent on a spot agent (the server's spot view does not carry it). */206 public let kind: AgentKind?207 public let name: String208 public let mission: String209 public let state: String210 public let mode: AgentMode211 /** A spot agent: the network of its vault. A perp agent: the venue. A stream agent: its venues joined by `+`. */212 public let network: String213 public let networkName: String?214 /** Market symbols (spot) or instruments' symbols (perp). */215 public let universe: [String]216 public let cash: String?217 public let interval: String218 /** The limits as stored. Typed through `spotRisk` / `perpRisk`. */219 public let risk: JSONValue220 public let holdings: [AgentHolding]?221 /** Empty for an agent without a vault (perp, stream, supervisor). */222 public let vaultAddress: String223 public let vaultIndex: Int?224 /** Allocated capital, decimal text in USDC. For perp and stream agents in simulation this is SIMULATED capital. */225 public let capitalUsdc: String226 public let strategyVersionId: String?227 public let mandateId: String?228 public let mandate: AgentMandateSummary?229 public let family: String?230 public let template: String?231 /** `bar`, `stream`, `supervisor`. */232 public let engine: String?233 public let configVersion: Int?234 /** `LIVE` when a paused spot agent was live: resuming needs a NEW mandate (the previous one was revoked at the signer). */235 public let pausedFrom: String?236 public let lastBar: Date?237 public let stopReason: String?238 public let createdAt: Date?239 public let updatedAt: Date?240 /** Perp / stream views: true while nothing the agent does is real. */241 public let simulation: Bool?242 /** Perp agent in LIVE mode: `mainnet` or `testnet` (testnet = the money is not real). Nil in simulation. */243 public let liveNetwork: String?244 public let venue: String?245 /** Perp: instrument ids (`hyperliquid:BTC`). */246 public let instruments: [String]?247 /** Perp: the PAPER derivatives account of the agent. */248 public let accountId: String?249 public let flag: JSONValue?250 public let hold: JSONValue?251 public let flattening: JSONValue?252 /** Creation only: remarks that never block (fees against the order size, symbols that can only be paper traded). */253 public let warnings: [AgentWarning]?254255 public var resolvedKind: AgentKind { kind ?? .spot }256 public var hasVault: Bool { resolvedKind == .spot && !vaultAddress.isEmpty }257 public var spotRisk: SpotAgentRisk? { resolvedKind == .spot ? try? risk.decode(SpotAgentRisk.self) : nil }258 public var perpRisk: PerpAgentRisk? { resolvedKind == .perp ? try? risk.decode(PerpAgentRisk.self) : nil }259 /** True only when the agent is LIVE on real money: a spot agent under a mandate, or a perp agent on the venue's mainnet. */260 public var tradesRealMoney: Bool { mode == .live && (resolvedKind == .perp ? liveNetwork == "mainnet" : true) }261}262263/** A balance of the agent's vault, read on-chain. Real funds whatever the agent's mode. */264public struct VaultBalance: Codable, Sendable, Hashable, Identifiable {265 public let symbol: String266 public let assetSymbol: String267 public let name: String268 public let kind: String269 public let issuer: String?270 /** `cash`, `asset`, or `gas` (the native coin when the agent does not trade it: it only pays fees). */271 public let role: String272 public let asset: String273 /** Base units. */274 public let amount: String275 public let display: String276 /** Estimate at the displayed price; nil when no price is known (never 0). */277 public let usd: Double?278 public var id: String { asset }279 public var units: BaseUnits? { try? BaseUnits(amount) }280}281282/** The mandate as the SIGNER reports it now (limits, today's usage, revoked / expired). Nil when the signer has none for this agent. */283public struct SpotMandateStatus: Codable, Sendable, Hashable {284 public struct Usage: Codable, Sendable, Hashable { public let sold: [String: String]?; public let orders: Int? }285 public let active: Bool286 public let revoked: Bool287 public let expired: Bool288 public let expiresAt: Int289 public let today: Usage?290 public let maxOrder: [String: String]291 public let maxDaily: [String: String]292 public let maxOrdersPerDay: Int293 public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt)) }294}295296/** The SIMULATED holdings of a spot agent (agents/paper-view.ts). Always paper: never added to the vault's real balances. */297public struct PaperBook: Codable, Sendable, Hashable {298 public struct Position: Codable, Sendable, Hashable { public let symbol: String; public let units: String; public let usd: Double? }299 public let positions: [Position]300 public let cashSymbol: String301 public let cashUsd: Double302 public let asOf: Date303 public var mode: AgentMode { .paper }304}305306/**307 Figures of a BACKTEST report. A backtest is a simulation on historical data under stated assumptions; it is not a track record. The308 type exists so that these numbers can never be handed to a view that expects paper or live performance (`AgentPerformance`).309 */310public struct SimulationFigures: Sendable, Hashable {311 public let metrics: JSONValue?312 public let robustness: JSONValue?313 public let benchmarks: JSONValue?314 public let config: JSONValue?315 public let checks: JSONValue?316 public var mode: AgentMode { .research }317 /** The label every screen puts on these numbers. */318 public var label: String { "backtest" }319 public var isEmpty: Bool { metrics == nil && robustness == nil && benchmarks == nil && checks == nil }320 /** `pass` when the report's own look-ahead check passed (required before a version can be approved). */321 public var lookaheadCheck: String? { checks?["lookahead"]?.stringValue }322}323324/** A strategy version pinned to an agent by the SHA-256 of its code (table `strategy_versions`). */325public struct StrategyVersion: Decodable, Sendable, Hashable, Identifiable {326 public let id: String327 public let name: String328 public let version: String329 public let sha256: String330 /** `draft`, `backtesting`, `approved`, `retired`. */331 public let status: String332 public let notes: String?333 public let approvedBy: String?334 public let hasReport: Bool?335 public let createdAt: Date?336 public let approvedAt: Date?337 public let meta: JSONValue?338 /** Backtest figures: simulation, always. */339 public let simulation: SimulationFigures340 /** Perp versions: the summary the owner reads before approving (perp-routes.ts `perpReportSummary`); `problem` non-null = cannot be approved. */341 public let perpSummary: PerpReportSummary?342343 enum K: String, CodingKey { case id, name, version, sha256, code_sha256, status, notes, approvedBy, hasReport, createdAt, created_at, approvedAt, approved_at, meta, metrics, robustness, benchmarks, config, checks, summary }344 public init(from decoder: Decoder) throws {345 let c = try decoder.container(keyedBy: K.self)346 id = try c.decode(String.self, forKey: .id); name = try c.decode(String.self, forKey: .name); version = try c.decode(String.self, forKey: .version)347 if let s = try c.decodeIfPresent(String.self, forKey: .sha256) { sha256 = s } else { sha256 = try c.decode(String.self, forKey: .code_sha256) }348 status = try c.decode(String.self, forKey: .status); notes = try c.decodeIfPresent(String.self, forKey: .notes)349 approvedBy = try c.decodeIfPresent(String.self, forKey: .approvedBy); hasReport = try c.decodeIfPresent(Bool.self, forKey: .hasReport)350 createdAt = try c.decodeIfPresent(Date.self, forKey: .createdAt) ?? c.decodeIfPresent(Date.self, forKey: .created_at)351 approvedAt = try c.decodeIfPresent(Date.self, forKey: .approvedAt) ?? c.decodeIfPresent(Date.self, forKey: .approved_at)352 meta = try c.decodeIfPresent(JSONValue.self, forKey: .meta)353 func j(_ k: K) throws -> JSONValue? { let v = try c.decodeIfPresent(JSONValue.self, forKey: k); return v?.isNull == true ? nil : v }354 simulation = SimulationFigures(metrics: try j(.metrics), robustness: try j(.robustness), benchmarks: try j(.benchmarks), config: try j(.config), checks: try j(.checks))355 perpSummary = try c.decodeIfPresent(PerpReportSummary.self, forKey: .summary)356 }357 public var isApproved: Bool { status == "approved" }358}359360/** A swap of a spot agent as the engine recorded it (table `agent_orders`). `mode` says whether it was simulated or signed. */361public struct SpotAgentOrder: Decodable, Sendable, Hashable {362 public let id: ServerText363 public let ts: Date364 public let mode: AgentMode365 public let fromSymbol: String366 public let toSymbol: String367 /** Base units of the input asset, as stored. */368 public let amountIn: ServerText?369 public let expectedOut: ServerText?370 public let minOut: ServerText?371 public let received: ServerText?372 /** `prepared`, `signed`, `broadcast`, `filled`, `failed`, `skipped`. Only `filled` is a completed swap. */373 public let state: String374 public let reason: String?375 public let txid: String?376 enum CodingKeys: String, CodingKey { case id, ts, mode, fromSymbol = "from_symbol", toSymbol = "to_symbol", amountIn = "amount_in", expectedOut = "expected_out", minOut = "min_out", received, state, reason, txid }377}378379public struct AgentEquityPoint: Decodable, Sendable, Hashable {380 public let ts: Date381 public let mode: AgentMode382 public let equityUsd: ServerNumber383 enum CodingKeys: String, CodingKey { case ts, mode, equityUsd = "equity_usd" }384}385386/** A line of the agent's log as the historical detail views carry it (table `research_log`). */387public struct AgentLogRow: Decodable, Sendable, Hashable {388 public let ts: Date389 public let kind: String390 public let title: String391 public let body: String?392 public let mode: AgentMode?393 public let severity: String?394 public let code: String?395}396397/** `GET /agents/:id` of a spot agent. Orders and equity belong to ONE mode (`records`): the mode the agent is in now (live, else paper). */398public struct SpotAgentDetail: Decodable, Sendable {399 public let agent: Agent400 /** Real on-chain balances; nil when the chain could not be read (never an empty vault). */401 public let vault: [VaultBalance]?402 public let mandateStatus: SpotMandateStatus?403 /** Simulated holdings; nil when the agent never ran on paper. */404 public let paper: PaperBook?405 public let versions: [StrategyVersion]406 public let orders: ModeScoped<[SpotAgentOrder]>407 public let equity: ModeScoped<[AgentEquityPoint]>408 public let log: [AgentLogRow]409410 enum K: String, CodingKey { case vault, mandateStatus, paper, versions, orders, equity, log }411 public init(from decoder: Decoder) throws {412 agent = try Agent(from: decoder)413 let c = try decoder.container(keyedBy: K.self)414 vault = try c.decodeIfPresent([VaultBalance].self, forKey: .vault)415 mandateStatus = try c.decodeIfPresent(SpotMandateStatus.self, forKey: .mandateStatus)416 paper = try c.decodeIfPresent(PaperBook.self, forKey: .paper)417 versions = try c.decodeIfPresent([StrategyVersion].self, forKey: .versions) ?? []418 // routes.ts (D5): the records of the mode the agent is in NOW — never both in one list. A row of another mode is a refusal, not a merge.419 let records: AgentMode = agent.mode == .live ? .live : .paper420 let o = try c.decodeIfPresent([SpotAgentOrder].self, forKey: .orders) ?? [], e = try c.decodeIfPresent([AgentEquityPoint].self, forKey: .equity) ?? []421 guard o.allSatisfy({ $0.mode == records }), e.allSatisfy({ $0.mode == records }) else {422 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "the agent's records mix modes (expected \(records.rawValue) only)"))423 }424 orders = ModeScoped(mode: records, value: o); equity = ModeScoped(mode: records, value: e)425 log = try c.decodeIfPresent([AgentLogRow].self, forKey: .log) ?? []426 }427 public var approvedVersion: StrategyVersion? { versions.first { $0.id == agent.strategyVersionId && $0.isApproved } }428}429430/** `GET /agents/:id`: the shape depends on the agent's kind. */431public enum AgentDetail: Decodable, Sendable {432 case spot(SpotAgentDetail)433 case perp(PerpAgentDetail)434 /** Stream and supervisor agents: the panel reads `overview` for the rest. */435 case runtime(Agent)436437 public init(from decoder: Decoder) throws {438 struct Probe: Decodable { let kind: AgentKind? }439 switch try Probe(from: decoder).kind ?? .spot {440 case .spot: self = .spot(try SpotAgentDetail(from: decoder))441 case .perp: self = .perp(try PerpAgentDetail(from: decoder))442 default: self = .runtime(try Agent(from: decoder))443 }444 }445 public var agent: Agent { switch self { case .spot(let d): d.agent; case .perp(let d): d.agent; case .runtime(let a): a } }446}447448// MARK: what an agent can trade (GET /agents/networks)449450public struct AgentNetworks: Codable, Sendable, Hashable {451 public struct Gas: Codable, Sendable, Hashable {452 /** Reserve of the native coin the vault must hold before going live, decimal text. */453 public let reserve: String454 public let perOrder: String455 public let perOrderUsd: Double?456 public let gasPriceGwei: Double?457 }458 public struct Cash: Codable, Sendable, Hashable { public let symbol: String; public let asset: String; public let name: String }459 public struct DataQuality: Codable, Sendable, Hashable { public let status: String; public let fresh: Bool; public let lastTs: JSONValue? }460 public struct Representation: Codable, Sendable, Hashable { public let asset: String; public let assetSymbol: String; public let name: String; public let kind: String; public let issuer: String? }461 public struct Symbol: Codable, Sendable, Hashable {462 public let symbol: String463 public let sources: [String]464 /** False: the signer cannot price it (not listed on both Coinbase and Kraken) — paper trading only. */465 public let live: Bool466 public let defaultAsset: String?467 public let data: [String: DataQuality?]?468 public let representations: [Representation]469 }470 public struct Network: Codable, Sendable, Hashable, Identifiable {471 public let id: String472 public let name: String473 public let native: String474 public let enabled: Bool475 public let cash: [Cash]476 public let defaultCash: String?477 /** Nil: the reserve could not be estimated (shown as unknown). */478 public let gas: Gas?479 public let feeWarning: Bool480 public let symbols: [Symbol]481 }482 public let networks: [Network]483 public let maxSymbols: Int484 /** A mandate covers at most 12 assets: the cash leg and 11 symbols. */485 public let maxLiveSymbols: Int486 public let feeWarnShare: Double?487}488489// MARK: vault: funds elsewhere, return to the owner490491/** What the vault's address holds on the OTHER EVM networks (the same address exists on all of them). */492public struct FundsElsewhere: Codable, Sendable, Hashable {493 public struct Holding: Codable, Sendable, Hashable, Identifiable {494 public let network: String495 public let networkName: String496 public let asset: String497 public let symbol: String498 public let display: String499 /** Symbol of the native coin that pays the fee there. */500 public let gas: String501 public let hasGas: Bool502 public let gasHeld: String?503 /** What one token withdrawal would cost right now; nil when unknown. */504 public let gasNeed: String?505 public let gasEnough: Bool?506 public var id: String { "\(network):\(asset)" }507 }508 public let address: String509 public let holdings: [Holding]510}511512public enum VaultReturnState: String, Codable, Sendable, CaseIterable {513 case requested, signed, broadcast, confirmed, failed, notSent = "not_sent"514 case unknown515 public init(from decoder: Decoder) throws { self = VaultReturnState(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .unknown }516 public var isOpen: Bool { self == .requested || self == .signed || self == .broadcast }517 public var isTerminal: Bool { self == .confirmed || self == .failed || self == .notSent }518}519520/**521 A vault return (agents/withdrawals.ts `view`): the WHOLE balance of one asset of the vault, paid to the owner's own address — the only522 destination the signer signs for a vault. `ok` is true only once it was broadcast; `arrived` only when the payment was seen on-chain.523 */524public struct VaultReturn: Codable, Sendable, Hashable, Identifiable {525 public let id: String526 public let ok: Bool527 public let state: VaultReturnState528 public let network: String?529 public let asset: String?530 public let symbol: String531 /** Decimal text in whole units (not base units). */532 public let amount: String533 public let txid: String?534 public let explorer: String?535 public let error: String?536 public let arrived: Bool537 public let createdAt: Date?538 public let updatedAt: Date?539 public let confirmedAt: Date?540 /** This answer is an existing return (double tap / retry with the same key): nothing new was signed. */541 public let duplicate: Bool?542 /** Success is the chain's: mined AND the payment to the owner seen in the transaction. */543 public var isSettled: Bool { state == .confirmed && arrived }544}545546public struct VaultReturns: Codable, Sendable, Hashable {547 public let withdrawals: [VaultReturn]548 /** False: this server signs but does not relay transactions (a return then ends `not_sent`). */549 public let broadcast: Bool?550}551552// MARK: strategy library553554/** A version of the laboratory's library (strategies.ts `StrategyInfo`, perp-strategies.ts `PerpStrategyInfo`). The API never writes strategy code. */555public struct LibraryStrategy: Codable, Sendable, Hashable, Identifiable {556 public struct Meta: Codable, Sendable, Hashable {557 public let name: String558 public let version: String559 public let kind: String?560 public let universe: [String]561 public let interval: String562 public let lookback: Int?563 public let params: JSONValue?564 public let maxLeverage: Double?565 public let maxGrossExposure: Double?566 enum CodingKeys: String, CodingKey { case name, version, kind, universe, interval, lookback, params, maxLeverage = "max_leverage", maxGrossExposure = "max_gross_exposure" }567 }568 /** `strategies/<name>/<version>`. Registration takes it without the `strategies/` prefix (`registrationPath`). */569 public let path: String570 public let sha256: String571 public let kind: String?572 /** Universe `["*"]`: the symbols are the agent's, between `minSymbols` and `maxSymbols` of them. */573 public let generic: Bool?574 public let minSymbols: Int?575 public let maxSymbols: Int?576 public let spotLegs: Bool?577 public let meta: Meta578 public let readme: String?579 public var id: String { "\(path)@\(sha256)" }580 public var registrationPath: String { path.hasPrefix("strategies/") ? String(path.dropFirst("strategies/".count)) : path }581}582583/** Answer of the registration of a library version to an agent: its backtest starts; approval stays a separate owner action. */584public struct StrategyRegistration: Codable, Sendable, Hashable {585 public let id: String586 public let sha256: String587 public let status: String588 public let kind: String?589 public let generic: Bool?590 public let symbols: [String]?591}592593// MARK: agent panel (runtime-routes.ts)594595/** `agentSummary` of agent-runtime/store.ts: one vocabulary for every agent, whatever engine runs it. */596public struct AgentSummary: Decodable, Sendable, Hashable, Identifiable {597 public struct Strategy: Codable, Sendable, Hashable {598 public let name: String599 public let version: String600 public let sha256: String601 public let path: String?602 public let status: String603 /** `python` (hash-pinned laboratory code) or `rule` (built-in TypeScript rule). */604 public let kind: String605 }606 /** Which mandate, if any, is in force for the agent (a reference: the mandate itself lives at the signer). */607 public struct MandateRef: Codable, Sendable, Hashable { public let kind: String; public let id: String; public let accountId: String? }608 public struct LiveCapability: Codable, Sendable, Hashable { public let capable: Bool; public let code: String?; public let reason: String? }609610 public let id: String611 public let name: String612 public let mission: String613 public let kind: AgentKind614 public let family: String615 public let template: String?616 public let engine: String617 public let state: AgentLifecycle618 /** The historical state text (`PAPER_TRADING`, `LIVE`, `STOPPING`…). */619 public let phase: String620 public let mode: AgentMode621 public let venue: String622 public let network: String?623 public let universe: [String]624 public let interval: String625 public let capitalUsd: String626 public let riskLimits: JSONValue627 public let configVersion: Int628 public let strategy: Strategy?629 public let mandate: MandateRef?630 public let pausedFrom: String?631 public let live: LiveCapability632 public let stopReason: String?633 public let lastBar: Date?634 public let createdAt: Date?635 public let updatedAt: Date?636 /** Stop only: what the wind-down of a live agent did (mandate revoked, positions being closed). */637 public let windDown: JSONValue?638 /** STOPPING is still active: the engine is closing positions. */639 public var isWindingDown: Bool { phase == "STOPPING" }640}641642public struct FamilyModes: Codable, Sendable, Hashable {643 public let engine: String?644 public let modes: [AgentMode]645 /** Why the family cannot go live, when it cannot. */646 public let liveReason: String?647}648649/** The kill switch as the agents see it. There is ONE switch (the risk engine's); it is released with the passkey in the Risk screen, never here. */650public struct AgentKillSwitchState: Codable, Sendable, Hashable {651 public struct Release: Codable, Sendable, Hashable { public let route: String; public let passkey: Bool }652 public let engaged: Bool653 public let reason: String?654 public let at: Date?655 public let by: String?656 public let readOnly: Bool657 public let readOnlyReason: String?658 public let release: Release?659}660661public enum AgentJobStatus: String, Codable, Sendable {662 case queued, running, done, failed, cancelled663 case unknown664 public init(from decoder: Decoder) throws { self = AgentJobStatus(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .unknown }665 public var isFinished: Bool { self == .done || self == .failed || self == .cancelled }666}667668/** A job of the agent queue (`jobView`): backtests run asynchronously, the answer is a job to poll. */669public struct AgentJob: Codable, Sendable, Hashable, Identifiable {670 public let id: String671 public let agentId: String?672 public let kind: String673 public let status: AgentJobStatus674 public let deadLettered: Bool?675 public let attempts: Int?676 public let maxAttempts: Int?677 public let runAt: Date?678 public let error: String?679 public let result: JSONValue?680 public let createdAt: Date?681 public let updatedAt: Date?682 public let finishedAt: Date?683}684685/** The answer of a backtest request. `label` is always `backtest`: the result is a simulation, read through the strategy version. */686public struct BacktestRequestResult: Codable, Sendable, Hashable { public let job: AgentJob; public let label: String }687688/** `GET /agents/:id/overview`: the summary plus the family's modes, the backtests (labelled), the runtime of a stream agent, the worker and the switch. */689public struct AgentOverview: Decodable, Sendable {690 public struct Backtests: Decodable, Sendable {691 public let label: String692 public let note: String693 public let versions: [StrategyVersion]694 /** A stream agent's recorded replay (simulation). */695 public let recorded: JSONValue?696 }697 /** The SIMULATED book of a stream agent. */698 public struct Book: Codable, Sendable, Hashable {699 public let simulated: Bool700 public let positions: JSONValue?701 public let quotes: JSONValue?702 public let pair: JSONValue?703 public let realizedPnl: Double?704 public let fees: Double?705 public let funding: Double?706 }707 public struct Runtime: Codable, Sendable, Hashable {708 public let venues: [String]709 public let rule: String?710 public let config: JSONValue?711 public let counters: JSONValue?712 public let hold: JSONValue?713 public let lastPass: JSONValue?714 public let book: Book?715 }716 public struct Lease: Codable, Sendable, Hashable { public let owner: String; public let heartbeatAt: Date?; public let expiresAt: Date?; public let active: Bool }717 public struct Worker: Codable, Sendable, Hashable { public let lease: Lease?; public let tick: JSONValue? }718719 public let summary: AgentSummary720 public let familyModes: FamilyModes?721 public let backtests: Backtests722 public let runtime: Runtime?723 public let worker: Worker?724 public let jobs: [AgentJob]725 public let killSwitch: AgentKillSwitchState726727 enum K: String, CodingKey { case familyModes, backtests, runtime, worker, jobs, killSwitch }728 public init(from decoder: Decoder) throws {729 summary = try AgentSummary(from: decoder)730 let c = try decoder.container(keyedBy: K.self)731 familyModes = try c.decodeIfPresent(FamilyModes.self, forKey: .familyModes)732 backtests = try c.decode(Backtests.self, forKey: .backtests)733 runtime = try c.decodeIfPresent(Runtime.self, forKey: .runtime)734 worker = try c.decodeIfPresent(Worker.self, forKey: .worker)735 jobs = try c.decodeIfPresent([AgentJob].self, forKey: .jobs) ?? []736 killSwitch = try c.decode(AgentKillSwitchState.self, forKey: .killSwitch)737 }738}739740public struct AgentConfigVersion: Codable, Sendable, Hashable {741 public let version: Int742 public let config: JSONValue743 public let sha256: String744 public let actor: String745 public let reason: String746 public let createdAt: Date?747 enum CodingKeys: String, CodingKey { case version, config, sha256, actor, reason, createdAt = "created_at" }748}749750/** What the owner would have to approve for this agent to go live — the FIELDS, read-only. Nothing is prepared at the signer by reading it. */751public struct MandateDraft: Codable, Sendable, Hashable {752 public struct Approval: Codable, Sendable, Hashable { public let route: String; public let note: String }753 public struct Pending: Codable, Sendable, Hashable { public let mandateId: String; public let state: String; public let accountId: String? }754 public struct Create: Codable, Sendable, Hashable { public let method: String?; public let path: String; public let body: JSONValue? }755 public let draft: String756 public let agentId: String757 public let family: String758 public let available: Bool759 /** `spot`, `derivative`, `quoting`, `none`. */760 public let kind: String?761 /** The canonical shape(s) the approval commits to, e.g. `SPW-MANDATE-v1`. */762 public let shape: String?763 public let code: String?764 public let reason: String?765 public let fields: JSONValue?766 public let approval: Approval767 public let pending: Pending?768 public let create: Create?769 public let readiness: JSONValue?770 public let checklist: String?771 public let existingFlow: String?772}773774public struct AgentSignal: Decodable, Sendable, Hashable, Identifiable {775 public let id: String776 public let ts: Date777 public let mode: AgentMode778 public let kind: String?779 public let configVersion: Int?780 public let strategySha256: String?781 public let inputsDigest: String?782 public let status: String?783 public let decision: String?784 public let reasonCode: String?785 public let reason: String?786 public let output: JSONValue?787 public let scaled: JSONValue?788 public let scale: JSONValue?789 public let equity: String?790 public let targets: JSONValue?791 public let orders: JSONValue?792 public let createdAt: Date?793 public let updatedAt: Date?794}795796public struct AgentJournalEntry: Decodable, Sendable, Hashable, Identifiable {797 public let id: String798 public let ts: Date799 public let mode: AgentMode800 public let kind: String801 public let severity: String?802 public let code: String?803 public let title: String804 public let body: String?805 public let data: JSONValue?806 public let ref: JSONValue?807 public let configVersion: Int?808}809810/** An order of ONE mode of an agent (`agentOrders`): a unified order, a simulated order of the seam gateway, or a row of the engine tables of before. */811public struct AgentOrder: Decodable, Sendable, Hashable, Identifiable {812 public struct Transition: Codable, Sendable, Hashable { public let at: Date?; public let from: String?; public let to: String?; public let event: String?; public let reason: String? }813 public let id: ServerText814 /** `orders`, `gateway`, `legacy`. */815 public let source: String816 public let mode: AgentMode817 public let ts: Date818 public let updatedAt: Date?819 public let venue: String?820 public let instrument: String?821 public let side: String?822 public let reduceOnly: Bool?823 public let size: String?824 public let notional: String?825 public let filledSize: String?826 public let avgFillPrice: String?827 /** Canonical order state (`APPROVED`, `SUBMITTED`, `FILLED`, `REJECTED`, `FAILED`, `CANCELLED`, `UNKNOWN`…). Only `FILLED` is a fill. */828 public let state: String829 public let reason: String?830 public let detail: String?831 public let venueOrderId: String?832 public let fills: JSONValue?833 public let signalId: String?834 public let configVersion: Int?835 public let strategySha256: String?836 public let history: [Transition]?837}838839/** A statistic with the reason it is missing when it is (too few points, no trade…). Never coerced to 0. */840public struct PerformanceFigure: Codable, Sendable, Hashable { public let value: Double?; public let reason: String? }841842/** A statistic of ONE mode: the mode travels with the number. */843public struct ModedFigure: Sendable, Hashable {844 public let mode: AgentMode845 public let value: Double?846 public let reason: String?847 public var isSimulated: Bool { mode != .live }848}849850/**851 Performance of ONE mode of one agent (`agentPerformance`). Research answers no figure at all: backtests are reports, read as852 `SimulationFigures`. Every accessor returns the number together with its mode.853 */854public struct AgentPerformance: Decodable, Sendable, Hashable {855 public struct Point: Codable, Sendable, Hashable { public let ts: Date; public let equity: Double }856 public let mode: AgentMode857 /** The server's label: `PAPER — simulated orders and fills; no money moved`, `LIVE — real orders…`, `RESEARCH — …`. */858 public let label: String859 public let points: Int860 public let from: Date?861 public let to: Date?862 public let periodsPerYear: Double?863 private let curve: [Point]864 private let figures: [String: PerformanceFigure]865 public let closedTrades: Int866 public let orders: Int867 public let warnings: [AgentWarning]868869 public static let figureNames = ["totalReturn", "volatility", "sharpe", "sortino", "maxDrawdown", "winRate", "profitFactor", "turnover", "feesUsd", "fundingUsd", "slippageUsd", "netPnlUsd"]870 struct K: CodingKey { var stringValue: String; var intValue: Int? { nil }; init(_ s: String) { stringValue = s }; init?(stringValue: String) { self.stringValue = stringValue }; init?(intValue: Int) { nil } }871 public init(from decoder: Decoder) throws {872 let c = try decoder.container(keyedBy: K.self)873 mode = try c.decode(AgentMode.self, forKey: K("mode")); label = try c.decode(String.self, forKey: K("label"))874 points = try c.decodeIfPresent(Int.self, forKey: K("points")) ?? 0875 from = try c.decodeIfPresent(Date.self, forKey: K("from")); to = try c.decodeIfPresent(Date.self, forKey: K("to"))876 periodsPerYear = try c.decodeIfPresent(Double.self, forKey: K("periodsPerYear"))877 curve = try c.decodeIfPresent([Point].self, forKey: K("equityCurve")) ?? []878 var f: [String: PerformanceFigure] = [:]879 for n in Self.figureNames { if let v = try c.decodeIfPresent(PerformanceFigure.self, forKey: K(n)) { f[n] = v } }880 figures = f881 closedTrades = try c.decodeIfPresent(Int.self, forKey: K("closedTrades")) ?? 0; orders = try c.decodeIfPresent(Int.self, forKey: K("orders")) ?? 0882 warnings = try c.decodeIfPresent([AgentWarning].self, forKey: K("warnings")) ?? []883 }884 private func figure(_ n: String) -> ModedFigure { ModedFigure(mode: mode, value: figures[n]?.value, reason: figures[n]?.reason ?? (figures[n] == nil ? "not reported" : nil)) }885 public var equityCurve: ModeScoped<[Point]> { ModeScoped(mode: mode, value: curve) }886 public var totalReturn: ModedFigure { figure("totalReturn") }887 public var volatility: ModedFigure { figure("volatility") }888 public var sharpe: ModedFigure { figure("sharpe") }889 public var sortino: ModedFigure { figure("sortino") }890 public var maxDrawdown: ModedFigure { figure("maxDrawdown") }891 public var winRate: ModedFigure { figure("winRate") }892 public var profitFactor: ModedFigure { figure("profitFactor") }893 public var turnover: ModedFigure { figure("turnover") }894 public var feesUsd: ModedFigure { figure("feesUsd") }895 public var fundingUsd: ModedFigure { figure("fundingUsd") }896 public var slippageUsd: ModedFigure { figure("slippageUsd") }897 public var netPnlUsd: ModedFigure { figure("netPnlUsd") }898}899900/** signal → decision → order → fill → error, newest first, of ONE mode. */901public struct AgentTimelineItem: Decodable, Sendable, Hashable {902 public let ts: Date903 public let type: String904 public let severity: String?905 public let code: String?906 public let title: String907 public let body: String?908 public let ref: JSONValue?909 public let configVersion: Int?910}911912/** The workers as the monitor and the panel see them (`GET /agents/runtime/status`). */913public struct AgentRuntimeStatus: Decodable, Sendable {914 public struct Workers: Codable, Sendable, Hashable { public let inProcess: Bool; public let worker: JSONValue?; public let mode: String? }915 public struct Loop: Codable, Sendable, Hashable {916 public let name: String917 public let everyMs: Double?918 public let runs: Int?919 public let lastOkAt: Date?920 public let lastErrorAt: Date?921 public let lastError: String?922 public let failures: Int?923 }924 /** One worker holds one agent at a time; a lease that is not `active` has expired. */925 public struct Lease: Codable, Sendable, Hashable { public let agentId: String; public let owner: String; public let token: Int?; public let heartbeatAt: Date?; public let expiresAt: Date?; public let active: Bool }926 public struct Queue: Codable, Sendable, Hashable { public let queued: Int; public let running: Int; public let dead24h: Int; public let oldestQueuedMs: Double? }927 public let workers: Workers928 public let loops: [Loop]929 public let leases: [Lease]930 public let queue: Queue931 public let killSwitch: AgentKillSwitchState932 public let streams: JSONValue?933 public let streamStats: JSONValue?934}935936// MARK: templates and the laboratory's verdicts937938public struct LocalizedText: Codable, Sendable, Hashable {939 public let fr: String940 public let en: String941 public func text(locale: String) -> String { locale.hasPrefix("fr") ? fr : en }942}943944/**945 The laboratory's out-of-sample result for a strategy, a study or a policy (agents/lab-verdicts.ts). BACKTEST figures read from the946 lab's files: a simulation, never a promise and never a track record. Unavailable files answer `available == false` with the reason.947 */948public struct LabVerdict: Codable, Sendable, Hashable {949 public struct Stop: Codable, Sendable, Hashable { public let code: String; public let reason: String; public let ts: String? }950 public struct GrossToNet: Codable, Sendable, Hashable { public let pricePnl, funding, fees, liquidationPenalties, slippage, latency, netPnl: Double? }951 public struct Split: Codable, Sendable, Hashable {952 public let netReturn, netSharpe, grossSharpe, maxDrawdown: Double?953 public let trades: Double?954 /** Non-nil: the engine's own loss limit (or a liquidation) ended this split. */955 public let stop: Stop?956 public let grossToNet: GrossToNet?957 }958 public struct Results: Codable, Sendable, Hashable { public let dir: String; public let file: String?; public let fileSha256: String?; public let matchesManifest: Bool? }959 public struct Window: Codable, Sendable, Hashable { public let start: String?; public let end: String?; public let interval: String?; public let bars: Double? }960961 public let available: Bool962 /** `strategy`, `study`, `policy`. */963 public let kind: String964 public let name: String965 /** Why it is unavailable. */966 public let reason: String?967 public let backtest: Bool?968 public let version: String?969 public let strategy: String?970 public let sha256: String?971 public let symbols: [String]?972 public let installedHashMatches: Bool?973 /** `agent`, `backtest_only`, `research_only`. */974 public let scope: String?975 public let liveCapable: Bool?976 public let deflatedSharpe: Double?977 public let deflatedSharpeThreshold: Double?978 /** The lab's own rule (deflated Sharpe against its threshold). Nil: not decided. */979 public let significant: Bool?980 public let trialsTested: Double?981 public let ownTrials: Double?982 public let testSharpeCi: [Double]?983 /** `train`, `validation`, `test`. */984 public let splits: [String: Split?]?985 public let stoppedSplits: [String]?986 public let checks: [String: String]?987 public let window: Window?988 public let dataSha256: String?989 public let codeSha256: String?990 public let engineParityApplied: Bool?991 public let statement: String?992 public let assumptions: [String]?993 public let fillsAreModelled: Bool?994 public let results: Results?995996 public var mode: AgentMode { .research }997 public var label: String { "backtest" }998}9991000public struct AgentTemplate: Codable, Sendable, Hashable, Identifiable {1001 public struct Installed: Codable, Sendable, Hashable {1002 public let path: String1003 public let name: String1004 public let version: String1005 public let sha256: String1006 public let universe: [String]1007 public let interval: String1008 public let spotLegs: Bool?1009 public let generic: Bool?1010 public let minSymbols: Int?1011 public let maxSymbols: Int?1012 public let defaultUniverse: [String]?1013 public let liveCapable: Bool1014 public let liveReason: String?1015 public let liveCondition: String?1016 }1017 public struct Rule: Codable, Sendable, Hashable { public let name: String; public let version: String; public let sha256: String }1018 public struct LabBacktest: Codable, Sendable, Hashable { public let wanted: [String]; public let installed: [String]; public let agentRunnable: Bool? }1019 public struct LabStudy: Codable, Sendable, Hashable { public let name: String; public let kind: String; public let installed: Bool }1020 /** What the template proposes. They are shown in the form and sent back explicitly: nothing is defaulted by this package. */1021 public struct Defaults: Codable, Sendable, Hashable {1022 public let universe: [String]1023 public let venues: [String]1024 public let interval: String1025 public let capitalUsdc: String1026 public let config: [String: JSONValue]1027 public let risk: [String: JSONValue]1028 }1029 public let id: String1030 public let family: String1031 public let engine: String1032 public let kind: String1033 public let name: LocalizedText1034 public let summary: LocalizedText1035 public let modes: [AgentMode]1036 public let liveReason: String?1037 public let strategyNames: [String]1038 public let installed: [Installed]1039 public let strategyInstalled: Bool1040 public let rule: Rule?1041 public let labBacktest: LabBacktest?1042 public let labStudies: [LabStudy]?1043 public let labVerdicts: [LabVerdict]?1044 public let defaults: Defaults1045}10461047public struct AgentTemplates: Codable, Sendable, Hashable {1048 public let templates: [AgentTemplate]1049 public let families: [String: FamilyModes]1050}10511052/** Answer of the creation from a template. Nothing is signed; the agent starts in research mode. */1053public struct TemplateAgentCreated: Decodable, Sendable {1054 public let agent: AgentSummary1055 public let strategy: JSONValue?1056 public let warnings: [AgentWarning]?1057}10581059public struct RuntimeConfigUpdated: Decodable, Sendable {1060 public let agent: AgentSummary1061 public let configVersion: Int1062}1063