Repository Public License
1// FlowEngine — the action registry: what a workflow can ask the host to do (docs/SDK.md).2import Foundation34/// What an action is allowed to touch. The user grants capabilities per run; an action whose capability was5/// not granted does not reach the host.6public struct FlowCapability: RawRepresentable, Hashable, Sendable, Codable, Comparable, CustomStringConvertible {7 public var rawValue: String8 public init(rawValue: String) { self.rawValue = rawValue }9 public var description: String { rawValue }10 public static func < (lhs: FlowCapability, rhs: FlowCapability) -> Bool { lhs.rawValue < rhs.rawValue }1112 /// Open, reload or close tabs on allowed domains.13 public static let navigate = FlowCapability(rawValue: "navigate")14 /// Read the content of a page the workflow opened.15 public static let read = FlowCapability(rawValue: "read")16 /// Type into fields and click elements of a page.17 public static let interact = FlowCapability(rawValue: "interact")18 public static let submitForm = FlowCapability(rawValue: "submit-form")19 /// Send content to the AI provider the user configured.20 public static let ai = FlowCapability(rawValue: "ai")21 public static let writeFile = FlowCapability(rawValue: "write-file")22 public static let download = FlowCapability(rawValue: "download")23 public static let writeNote = FlowCapability(rawValue: "write-note")24 public static let writeBookmark = FlowCapability(rawValue: "write-bookmark")25 public static let notify = FlowCapability(rawValue: "notify")2627 /// Capabilities whose actions reach the network, and therefore require `allow domains`.28 static let networked: Set<FlowCapability> = [.navigate, .download, .submitForm, .interact]29}3031public enum FlowParameterKind: Hashable, Sendable {32 /// A value of one of these types.33 case value([FlowType])34 /// One word of a fixed set, written bare (`as markdown`).35 case option([String])36}3738public struct FlowParameter: Hashable, Sendable {39 /// Key of the argument in `FlowActionCall.arguments`.40 public var name: String41 /// The word that introduces the argument (`from`, `to`, `with`…); `nil` for the positional argument that42 /// directly follows the action name.43 public var label: String?44 public var kind: FlowParameterKind45 public var isRequired: Bool46 public var summary: String4748 public init(_ name: String, label: String?, _ kind: FlowParameterKind, required: Bool = true, summary: String = "") {49 self.name = name; self.label = label; self.kind = kind; isRequired = required; self.summary = summary50 }51}5253public struct FlowActionDefinition: Hashable, Sendable {54 public enum Confirmation: String, Sendable, Hashable {55 case never56 /// The host asks the user before every execution; the run pauses meanwhile.57 case always58 }5960 /// One or two lowercase words (`open`, `extract article`).61 public var name: String62 public var summary: String63 public var parameters: [FlowParameter]64 public var result: FlowType65 /// `nil` only for actions the engine performs itself without side effects (`wait`).66 public var capability: FlowCapability?67 public var confirmation: Confirmation6869 public init(name: String, summary: String, parameters: [FlowParameter] = [], result: FlowType = .void,70 capability: FlowCapability?, confirmation: Confirmation = .never) {71 self.name = name; self.summary = summary; self.parameters = parameters; self.result = result72 self.capability = capability; self.confirmation = confirmation73 }7475 public var positional: FlowParameter? { parameters.first { $0.label == nil } }76 public var labels: [String] { parameters.compactMap(\.label) }77 public func parameter(label: String?) -> FlowParameter? { parameters.first { $0.label == label } }78 /// When the action has a parameter labelled `as`, `as` is that parameter and the result cannot be bound.79 public var usesAsLabel: Bool { labels.contains("as") }8081 /// Signature shown in completion and documentation: `open <url> → page`.82 public var signature: String {83 var text = name84 for parameter in parameters {85 let value: String86 switch parameter.kind {87 case .value(let types): value = "<" + types.map(\.description).joined(separator: " | ") + ">"88 case .option(let words): value = words.joined(separator: "|")89 }90 let piece = parameter.label.map { "\($0) \(value)" } ?? value91 text += parameter.isRequired ? " \(piece)" : " [\(piece)]"92 }93 return result == .void ? text : "\(text) → \(result)"94 }95}9697public enum FlowRegistryError: Error, Sendable, Equatable, CustomStringConvertible {98 case invalidName(String)99 case duplicate(String)100 case invalidParameter(action: String, parameter: String)101 case builtInName(String)102103 public var description: String {104 switch self {105 case .invalidName(let name): return "“\(name)” is not a valid action name (one or two lowercase words, not reserved)."106 case .duplicate(let name): return "An action named “\(name)” already exists."107 case .invalidParameter(let action, let parameter): return "Parameter “\(parameter)” of “\(action)” is invalid."108 case .builtInName(let name): return "“\(name)” is performed by the engine and cannot be redefined."109 }110 }111}112113/// The fixed set of actions a workflow can use. A registry is data: a definition says what an action is called114/// and what it takes; *doing* it is the host's job (`FlowHost.perform`). Nothing in a registry is executable.115public struct FlowActionRegistry: Sendable, Hashable {116 public private(set) var definitions: [String: FlowActionDefinition] = [:]117118 public init() {}119120 public var names: [String] { definitions.keys.sorted() }121 public func definition(named name: String) -> FlowActionDefinition? { definitions[name] }122123 /// Every word that can start an action name.124 var firstWords: Set<String> { Set(definitions.keys.compactMap { $0.split(separator: " ").first.map(String.init) }) }125126 private static func isWord(_ text: Substring) -> Bool {127 guard let first = text.unicodeScalars.first, first.properties.isLowercase else { return false }128 return text.unicodeScalars.allSatisfy { $0.properties.isLowercase || $0 == "_" }129 }130131 /// Adds a definition after checking it cannot confuse the parser: name of one or two lowercase words that132 /// are not reserved, at most one positional parameter, unique labels and names, no `unknown`/`void` inputs.133 public mutating func register(_ definition: FlowActionDefinition) throws {134 let words = definition.name.split(separator: " ", omittingEmptySubsequences: false)135 guard (1...2).contains(words.count), words.allSatisfy(Self.isWord),136 !FlowKeywords.reserved.contains(String(words[0])), words.count == 1 || !FlowKeywords.reserved.contains(String(words[1])) else {137 throw FlowRegistryError.invalidName(definition.name)138 }139 guard definition.name != FlowBuiltInAction.wait else { throw FlowRegistryError.builtInName(definition.name) }140 guard definitions[definition.name] == nil else { throw FlowRegistryError.duplicate(definition.name) }141 // "extract" and "extract article" cannot coexist: the parser could not tell them apart.142 for existing in definitions.keys {143 let other = existing.split(separator: " ")144 if other.first == words.first, other.count != words.count { throw FlowRegistryError.duplicate(definition.name) }145 }146 var names = Set<String>(), labels = Set<String?>()147 for parameter in definition.parameters {148 var valid = names.insert(parameter.name).inserted && labels.insert(parameter.label).inserted149 if let label = parameter.label {150 valid = valid && Self.isWord(Substring(label)) && (label == "as" || !FlowKeywords.reserved.contains(label))151 }152 switch parameter.kind {153 case .value(let types):154 valid = valid && !types.isEmpty && !types.contains { $0.containsUnknown || $0 == .void || $0 == .option }155 case .option(let words):156 valid = valid && !words.isEmpty && words.allSatisfy { Self.isWord(Substring($0)) }157 }158 guard valid else { throw FlowRegistryError.invalidParameter(action: definition.name, parameter: parameter.name) }159 }160 guard !definition.result.containsUnknown, definition.result != .option else {161 throw FlowRegistryError.invalidParameter(action: definition.name, parameter: "result")162 }163 if definition.usesAsLabel, definition.result != .void {164 throw FlowRegistryError.invalidParameter(action: definition.name, parameter: "as")165 }166 guard definition.capability != nil else { throw FlowRegistryError.invalidParameter(action: definition.name, parameter: "capability") }167 definitions[definition.name] = definition168 }169170 /// A copy with more definitions (the documented extension point, see docs/SDK.md).171 public func adding(_ extra: [FlowActionDefinition]) throws -> FlowActionRegistry {172 var copy = self173 for definition in extra { try copy.register(definition) }174 return copy175 }176177 /// The actions that ship with ORIX Navigator.178 public static let standard: FlowActionRegistry = {179 var registry = FlowActionRegistry()180 let readable: [FlowType] = [.article, .report, .text, .list(.article), .list(.text)]181 let builtIns: [FlowActionDefinition] = [182 FlowActionDefinition(name: "open", summary: "Open a URL in a new tab of the workflow's space.",183 parameters: [FlowParameter("url", label: nil, .value([.url]), summary: "Address to open")],184 result: .page, capability: .navigate),185 FlowActionDefinition(name: "close", summary: "Close a tab the workflow opened.",186 parameters: [FlowParameter("page", label: nil, .value([.page]))], capability: .navigate),187 FlowActionDefinition(name: "extract article", summary: "Read the main article of a page (reader extraction).",188 parameters: [FlowParameter("page", label: "from", .value([.page]))], result: .article, capability: .read),189 FlowActionDefinition(name: "extract text", summary: "Read the visible text of a page.",190 parameters: [FlowParameter("page", label: "from", .value([.page]))], result: .text, capability: .read),191 FlowActionDefinition(name: "extract links", summary: "List the links of a page.",192 parameters: [FlowParameter("page", label: "from", .value([.page]))], result: .list(.url), capability: .read),193 FlowActionDefinition(name: "summarize", summary: "Summarise content with the AI provider chosen by the user.",194 parameters: [FlowParameter("content", label: nil, .value(readable)),195 FlowParameter("with", label: "with", .option(["citations"]), required: false,196 summary: "Keep numbered citations of the sources"),197 FlowParameter("length", label: "length", .option(["short", "medium", "long"]), required: false)],198 result: .report, capability: .ai),199 FlowActionDefinition(name: "ask", summary: "Ask the AI provider a question about content.",200 parameters: [FlowParameter("question", label: nil, .value([.text])),201 FlowParameter("content", label: "about", .value(readable))],202 result: .text, capability: .ai),203 FlowActionDefinition(name: "export", summary: "Write content to a file in a user folder.",204 parameters: [FlowParameter("content", label: nil, .value([.report, .article, .text])),205 FlowParameter("format", label: "as", .option(["markdown", "text", "html", "json"])),206 FlowParameter("destination", label: "to", .option(["downloads", "documents"]))],207 capability: .writeFile),208 FlowActionDefinition(name: "download", summary: "Download a file through the download manager.",209 parameters: [FlowParameter("url", label: nil, .value([.url]))],210 result: .file, capability: .download, confirmation: .always),211 FlowActionDefinition(name: "save note", summary: "Create a note.",212 parameters: [FlowParameter("content", label: nil, .value([.text, .report, .article])),213 FlowParameter("title", label: "title", .value([.text]), required: false)],214 capability: .writeNote),215 FlowActionDefinition(name: "bookmark", summary: "Add a bookmark.",216 parameters: [FlowParameter("target", label: nil, .value([.url, .page])),217 FlowParameter("title", label: "title", .value([.text]), required: false)],218 capability: .writeBookmark),219 FlowActionDefinition(name: "fill", summary: "Type text into a form field of a page.",220 parameters: [FlowParameter("selector", label: nil, .value([.text]), summary: "CSS selector of the field"),221 FlowParameter("page", label: "on", .value([.page])),222 FlowParameter("text", label: "with", .value([.text]))],223 capability: .interact),224 FlowActionDefinition(name: "click", summary: "Click an element of a page.",225 parameters: [FlowParameter("selector", label: nil, .value([.text])),226 FlowParameter("page", label: "on", .value([.page]))],227 capability: .interact, confirmation: .always),228 FlowActionDefinition(name: "submit", summary: "Submit a form of a page.",229 parameters: [FlowParameter("selector", label: nil, .value([.text]), summary: "CSS selector of the form"),230 FlowParameter("page", label: "on", .value([.page]))],231 capability: .submitForm, confirmation: .always),232 FlowActionDefinition(name: "notify", summary: "Show a notification.",233 parameters: [FlowParameter("message", label: nil, .value([.text]))], capability: .notify),234 ]235 for definition in builtIns {236 do { try registry.register(definition) } catch { preconditionFailure("standard action \(definition.name): \(error)") }237 }238 registry.definitions[FlowBuiltInAction.wait] = FlowBuiltInAction.waitDefinition239 return registry240 }()241}242243/// Actions the engine performs itself.244enum FlowBuiltInAction {245 static let wait = "wait"246 static let waitDefinition = FlowActionDefinition(247 name: wait, summary: "Pause for a duration (at most 60 s).",248 parameters: [FlowParameter("duration", label: nil, .value([.duration]))], capability: nil)249}250251/// The pure functions usable in expressions. They compute on values already in the workflow; none performs I/O.252enum FlowFunctions {253 struct Signature: Sendable {254 var name: String255 var summary: String256 var display: String257 }258259 static let all: [Signature] = [260 Signature(name: "count", summary: "Number of items of a list, or of characters of a text.", display: "count(list | text) → number"),261 Signature(name: "empty", summary: "Whether a list or a text is empty.", display: "empty(list | text) → bool"),262 Signature(name: "contains", summary: "Whether a text contains a text, or a list contains a value.", display: "contains(text, text) | contains(list<T>, T) → bool"),263 Signature(name: "first", summary: "First item of a list (the step fails if the list is empty).", display: "first(list<T>) → T"),264 Signature(name: "take", summary: "The first n items of a list.", display: "take(list<T>, number) → list<T>"),265 Signature(name: "unique", summary: "The list without duplicates, order kept.", display: "unique(list<T>) → list<T>"),266 Signature(name: "allowed", summary: "The URLs of a list that are on the allowed domains.", display: "allowed(list<url>) → list<url>"),267 Signature(name: "join", summary: "Texts joined with a separator.", display: "join(list<text>, text) → text"),268 Signature(name: "host", summary: "Host name of a URL or of a page.", display: "host(url | page) → text"),269 Signature(name: "url", summary: "A text checked and converted to a URL (http or https).", display: "url(text) → url"),270 Signature(name: "text", summary: "A value as text.", display: "text(value) → text"),271 Signature(name: "lower", summary: "Lowercased text.", display: "lower(text) → text"),272 Signature(name: "upper", summary: "Uppercased text.", display: "upper(text) → text"),273 Signature(name: "trim", summary: "Text without leading and trailing whitespace.", display: "trim(text) → text"),274 ]275276 static let names = Set(all.map(\.name))277}278