Repository Public License
1// FlowEngine — the host protocol, run records and expression evaluation.2import Foundation3import NavigatorCore45// MARK: - Host67/// One action the interpreter asks the host to perform. Everything in it has already been checked: the8/// capability was granted, every URL is on the allow-list, the user confirmed if the action requires it.9public struct FlowActionCall: Sendable, Hashable {10 public var runID: UUID11 public var stepID: Int12 public var action: String13 /// Argument values keyed by `FlowParameter.name`.14 public var arguments: [String: FlowValue]15 /// The workflow's allow-list. The host must apply it to redirects and to anything else it loads on behalf16 /// of the step (`FlowDomainPolicy.allows`); the engine can only check the URLs it sees.17 public var policy: FlowDomainPolicy18 public var timeoutSeconds: Double19 /// `space "…"` of the workflow: where tabs should open.20 public var spaceName: String?21}2223public struct FlowConfirmationRequest: Sendable, Hashable {24 public var runID: UUID25 public var stepID: Int26 public var workflowName: String27 public var action: String28 public var capability: FlowCapability?29 /// One line describing the step ("download https://…").30 public var summary: String31 public var arguments: [String: FlowValue]32}3334/// What the app implements to give workflows effects. The engine never touches tabs, files, the network or the35/// AI provider itself.36///37/// `perform` must honour task cancellation: a step that times out or a run that is cancelled cancels the task38/// and waits for `perform` to return.39public protocol FlowHost: Sendable {40 func perform(_ call: FlowActionCall) async throws -> FlowValue41 /// Asks the user. The run is paused (status `awaitingConfirmation`) until this returns; the time spent42 /// here does not count against the workflow's duration limit.43 func confirm(_ request: FlowConfirmationRequest) async -> Bool44}4546// MARK: - Errors4748public enum FlowRunError: Error, Sendable, Hashable, Codable, CustomStringConvertible {49 case invalidParameter(name: String, reason: String)50 case capabilityNotGranted(capability: String, action: String)51 case domainNotAllowed(url: String, action: String)52 case invalidURL(String)53 case confirmationDenied(action: String)54 case stepLimitExceeded(limit: Int)55 case durationLimitExceeded(seconds: Double)56 case stepTimedOut(action: String, seconds: Double)57 case hostFailure(action: String, message: String)58 case hostContractViolation(action: String, expected: String, got: String)59 case evaluation(String)60 case valueTooLarge(String)61 case cancelled62 case notResumable(String)6364 public var description: String {65 switch self {66 case .invalidParameter(let name, let reason): return "Parameter “\(name)”: \(reason)"67 case .capabilityNotGranted(let capability, let action): return "“\(action)” needs the “\(capability)” permission, which was not granted for this run."68 case .domainNotAllowed(let url, let action): return "“\(action)” was stopped: \(url) is not on the workflow's allowed domains."69 case .invalidURL(let text): return "Not a valid http(s) URL: \(text)"70 case .confirmationDenied(let action): return "“\(action)” was not confirmed."71 case .stepLimitExceeded(let limit): return "The workflow reached its limit of \(limit) steps."72 case .durationLimitExceeded(let seconds): return "The workflow reached its duration limit of \(Int(seconds)) s."73 case .stepTimedOut(let action, let seconds): return "“\(action)” did not finish within \(seconds) s."74 case .hostFailure(let action, let message): return "“\(action)” failed: \(message)"75 case .hostContractViolation(let action, let expected, let got): return "“\(action)” returned \(got) instead of \(expected)."76 case .evaluation(let message): return message77 case .valueTooLarge(let message): return message78 case .cancelled: return "The run was cancelled."79 case .notResumable(let reason): return "This run cannot be resumed: \(reason)"80 }81 }82}8384// MARK: - Run log8586public struct FlowStepRecord: Codable, Sendable, Hashable, Identifiable {87 public enum Status: String, Codable, Sendable {88 case running, awaitingConfirmation, succeeded, failed, denied, timedOut, cancelled89 }9091 public var id: Int92 /// Position in the program: `2` is the third top-level statement, `2[1].0` the first statement of the93 /// second iteration of that loop.94 public var path: String95 public var action: String96 public var summary: String97 public var status: Status98 public var startedAt: Date99 public var finishedAt: Date?100 public var error: String?101}102103/// Where a run can restart: the index of the next top-level statement and the values that existed there.104public struct FlowCheckpoint: Codable, Sendable, Hashable {105 public var nextStatement: Int106 public var variables: [String: FlowValue]107 public var collections: [String: [FlowValue]]108}109110public struct FlowRunRecord: Codable, Sendable, Hashable, Identifiable {111 public enum Status: String, Codable, Sendable {112 case running, awaitingConfirmation, completed, failed, cancelled113 public var isTerminal: Bool { self == .completed || self == .failed || self == .cancelled }114 }115116 public var id: UUID117 public var workflowID: WorkflowID?118 public var name: String119 public var sourceHash: String120 public var parameters: [String: FlowValue]121 public var grantedCapabilities: [String]122 public var status: Status123 public var steps: [FlowStepRecord]124 public var checkpoint: FlowCheckpoint125 public var statementCount: Int126 public var stepsUsed: Int127 public var startedAt: Date128 public var updatedAt: Date129 public var finishedAt: Date?130 public var failure: FlowRunError?131 /// Number of times the run was resumed.132 public var resumeCount: Int133134 /// A run that stopped before its last top-level statement can be resumed from its checkpoint. A record still135 /// marked running or awaiting confirmation after a relaunch was interrupted by the app quitting.136 public var isResumable: Bool { status != .completed && checkpoint.nextStatement < statementCount }137 public var errorDescription: String? { failure?.description }138}139140/// Receives every state change of a run (start, each step, each checkpoint, end). `FlowRunStore` persists them;141/// the UI can observe the same way.142public protocol FlowRunObserver: Sendable {143 func runDidChange(_ record: FlowRunRecord) async144}145146// MARK: - Environment and evaluation147148struct FlowEnvironment: Sendable {149 var scopes: [[String: FlowValue]]150 var collections: [String: [FlowValue]]151152 func lookup(_ name: String) -> FlowValue? {153 for scope in scopes.reversed() { if let value = scope[name] { return value } }154 return collections[name].map(FlowValue.list)155 }156157 mutating func bind(_ name: String, _ value: FlowValue) { scopes[scopes.count - 1][name] = value }158}159160struct FlowEvaluator: Sendable {161 let policy: FlowDomainPolicy162 let caps: FlowCaps163 let knownCollections: Set<String>164165 /// Characters kept as they are when a value is inserted in a URL; everything else is percent-encoded, so a166 /// value can never add a path segment, a query separator or a fragment.167 static let urlComponentAllowed = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")168169 static func parseURL(_ text: String) throws -> URL {170 let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)171 guard let url = URL(string: trimmed), let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https",172 let host = url.host, !host.isEmpty, url.user == nil, url.password == nil else {173 throw FlowRunError.invalidURL(String(trimmed.prefix(200)))174 }175 return url176 }177178 func check(_ value: FlowValue) throws -> FlowValue {179 switch value {180 case .text(let text) where text.utf8.count > caps.maximumTextBytes:181 throw FlowRunError.valueTooLarge("A text value exceeds \(caps.maximumTextBytes) bytes.")182 case .list(let items) where items.count > caps.maximumListLength:183 throw FlowRunError.valueTooLarge("A list exceeds \(caps.maximumListLength) items.")184 default: return value185 }186 }187188 func evaluate(_ expression: FlowExpression, _ env: FlowEnvironment, expecting: FlowType? = nil) throws -> FlowValue {189 switch expression {190 case .invalid: throw FlowRunError.evaluation("The workflow contains an unreadable expression.")191 case .number(let value, _): return .number(value)192 case .bool(let value, _): return .bool(value)193 case .duration(let seconds, _): return .duration(seconds)194 case .string(let literal):195 let asURL = expecting == .url196 var text = ""197 for part in literal.parts {198 switch part {199 case .text(let piece): text += piece200 case .interpolation(let path, _):201 var value = try lookup(path[0], env)202 for member in path.dropFirst() { value = try self.member(value, member) }203 let piece = value.displayText204 text += asURL ? (piece.addingPercentEncoding(withAllowedCharacters: Self.urlComponentAllowed) ?? "") : piece205 }206 }207 return try check(asURL ? .url(try Self.parseURL(text)) : .text(text))208 case .identifier(let name, _):209 return try lookup(name, env)210 case .member(let base, let name, _):211 return try member(try evaluate(base, env), name)212 case .list(let items, _):213 var element: FlowType?214 if case .list(let expected)? = expecting { element = expected }215 return try check(.list(try items.map { try evaluate($0, env, expecting: element) }))216 case .not(let operand, _):217 guard case .bool(let flag) = try evaluate(operand, env) else { throw FlowRunError.evaluation("“not” needs true or false.") }218 return .bool(!flag)219 case .binary(let op, let left, let right, _):220 let lhs = try evaluate(left, env)221 switch op {222 case .and, .or:223 guard case .bool(let a) = lhs else { throw FlowRunError.evaluation("“\(op.rawValue)” needs true or false.") }224 // Short-circuit like every language the author is likely to know.225 if op == .and, !a { return .bool(false) }226 if op == .or, a { return .bool(true) }227 guard case .bool(let b) = try evaluate(right, env) else { throw FlowRunError.evaluation("“\(op.rawValue)” needs true or false.") }228 return .bool(b)229 case .equal, .notEqual:230 var expectingRight: FlowType?231 if case .url = lhs { expectingRight = .url }232 let rhs = try evaluate(right, env, expecting: expectingRight)233 return .bool((lhs == rhs) == (op == .equal))234 case .less, .lessOrEqual, .greater, .greaterOrEqual:235 let rhs = try evaluate(right, env)236 let a: Double, b: Double237 switch (lhs, rhs) {238 case (.number(let x), .number(let y)), (.duration(let x), .duration(let y)): a = x; b = y239 default: throw FlowRunError.evaluation("“\(op.rawValue)” compares numbers.")240 }241 switch op {242 case .less: return .bool(a < b)243 case .lessOrEqual: return .bool(a <= b)244 case .greater: return .bool(a > b)245 default: return .bool(a >= b)246 }247 }248 case .call(let name, let arguments, _):249 return try check(try call(name, arguments, env))250 }251 }252253 private func lookup(_ name: String, _ env: FlowEnvironment) throws -> FlowValue {254 if let value = env.lookup(name) { return value }255 // A collection nothing has been added to yet is an empty list.256 if knownCollections.contains(name) { return .list([]) }257 throw FlowRunError.evaluation("“\(name)” has no value.")258 }259260 private func member(_ value: FlowValue, _ name: String) throws -> FlowValue {261 switch (value, name) {262 case (.page(let page), "url"): return .url(page.url)263 case (.page(let page), "title"): return .text(page.title)264 case (.article(let article), "title"): return .text(article.title)265 case (.article(let article), "text"): return .text(article.text)266 case (.article(let article), "url"): return .url(article.url)267 case (.article(let article), "byline"): return .text(article.byline)268 case (.article(let article), "language"): return .text(article.language)269 case (.article(let article), "links"): return .list(article.links.prefix(caps.maximumListLength).map(FlowValue.url))270 case (.report(let report), "title"): return .text(report.title)271 case (.report(let report), "text"): return .text(report.text)272 case (.report(let report), "citations"): return .list(report.citations.prefix(caps.maximumListLength).map(FlowValue.url))273 case (.file(let file), "name"): return .text(file.name)274 case (.file(let file), "path"): return .text(file.path)275 default: throw FlowRunError.evaluation("This value has no “\(name)”.")276 }277 }278279 private func call(_ name: String, _ arguments: [FlowExpression], _ env: FlowEnvironment) throws -> FlowValue {280 func argument(_ index: Int, expecting: FlowType? = nil) throws -> FlowValue {281 guard index < arguments.count else { throw FlowRunError.evaluation("“\(name)” is missing an argument.") }282 return try evaluate(arguments[index], env, expecting: expecting)283 }284 func list(_ value: FlowValue) throws -> [FlowValue] {285 guard case .list(let items) = value else { throw FlowRunError.evaluation("“\(name)” needs a list.") }286 return items287 }288 func text(_ value: FlowValue) throws -> String {289 guard case .text(let text) = value else { throw FlowRunError.evaluation("“\(name)” needs text.") }290 return text291 }292 switch name {293 case "count", "empty":294 let count: Int295 switch try argument(0) {296 case .list(let items): count = items.count297 case .text(let text): count = text.count298 default: throw FlowRunError.evaluation("“\(name)” needs a list or a text.")299 }300 return name == "count" ? .number(Double(count)) : .bool(count == 0)301 case "contains":302 switch try argument(0) {303 case .text(let haystack): return .bool(haystack.localizedStandardContains(try text(try argument(1))))304 case .list(let items):305 var expecting: FlowType?306 if case .url? = items.first { expecting = .url }307 return .bool(items.contains(try argument(1, expecting: expecting)))308 default: throw FlowRunError.evaluation("“contains” needs a list or a text.")309 }310 case "first":311 guard let first = try list(try argument(0)).first else { throw FlowRunError.evaluation("“first” was given an empty list.") }312 return first313 case "take":314 guard case .number(let count) = try argument(1), count.isFinite else { throw FlowRunError.evaluation("“take” needs a number.") }315 return .list(Array(try list(try argument(0)).prefix(max(0, Int(min(count, 1e9))))))316 case "unique":317 var seen = Set<FlowValue>()318 return .list(try list(try argument(0)).filter { seen.insert($0).inserted })319 case "allowed":320 return .list(try list(try argument(0, expecting: .list(.url))).filter { value in321 if case .url(let url) = value { return policy.allows(url) }322 return false323 })324 case "join":325 return .text(try list(try argument(0)).map { try text($0) }.joined(separator: try text(try argument(1))))326 case "host":327 var expecting: FlowType?328 if case .string = arguments.first { expecting = .url }329 switch try argument(0, expecting: expecting) {330 case .url(let url): return .text(url.host ?? "")331 case .page(let page): return .text(page.url.host ?? "")332 default: throw FlowRunError.evaluation("“host” needs a url or a page.")333 }334 case "url":335 switch try argument(0, expecting: .url) {336 case .url(let url): return .url(url)337 case .text(let text): return .url(try Self.parseURL(text))338 default: throw FlowRunError.evaluation("“url” needs text.")339 }340 case "text":341 return .text(try argument(0).displayText)342 case "lower": return .text(try text(try argument(0)).lowercased())343 case "upper": return .text(try text(try argument(0)).uppercased())344 case "trim": return .text(try text(try argument(0)).trimmingCharacters(in: .whitespacesAndNewlines))345 default:346 throw FlowRunError.evaluation("Unknown function “\(name)”.")347 }348 }349}350