Repository Public License
1// FlowEngine — the interpreter: runs a validated program against a host, and the dry-run planner.2import Foundation3import NavigatorCore45public struct FlowRunRequest: Sendable {6 /// Values for the workflow's `param` declarations (those with a default may be omitted).7 public var parameters: [String: FlowValue]8 /// Capabilities the user granted for this run. Nothing outside this set reaches the host.9 public var grant: Set<FlowCapability>10 public var workflowID: WorkflowID?1112 public init(parameters: [String: FlowValue] = [:], grant: Set<FlowCapability>, workflowID: WorkflowID? = nil) {13 self.parameters = parameters; self.grant = grant; self.workflowID = workflowID14 }15}1617/// Mutable state of one run, shared by the branches of parallel blocks.18actor FlowRunState {19 private(set) var record: FlowRunRecord20 private let limits: FlowLimits21 private let observers: [any FlowRunObserver]22 private var deadline: ContinuousClock.Instant23 private var nextStepID: Int2425 init(record: FlowRunRecord, limits: FlowLimits, observers: [any FlowRunObserver]) {26 self.record = record; self.limits = limits; self.observers = observers27 deadline = ContinuousClock.now + .seconds(limits.maximumDurationSeconds)28 nextStepID = (record.steps.map(\.id).max() ?? -1) + 129 }3031 private func publish() async {32 record.updatedAt = .now33 for observer in observers { await observer.runDidChange(record) }34 }3536 func start() async { await publish() }3738 /// Seconds left before the duration limit; throws once it is reached.39 func remainingSeconds() throws -> Double {40 let remaining = ContinuousClock.now.duration(to: deadline)41 let seconds = Double(remaining.components.seconds) + Double(remaining.components.attoseconds) / 1e1842 guard seconds > 0 else { throw FlowRunError.durationLimitExceeded(seconds: limits.maximumDurationSeconds) }43 return seconds44 }4546 func extendDeadline(by duration: Duration) { deadline += duration }4748 /// Accounts for one step and logs its start. Throws when the step budget or the duration is exhausted,49 /// before anything is asked of the host.50 func beginStep(path: String, action: String, summary: String) async throws -> Int {51 guard record.stepsUsed < limits.maximumSteps else { throw FlowRunError.stepLimitExceeded(limit: limits.maximumSteps) }52 _ = try remainingSeconds()53 record.stepsUsed += 154 let id = nextStepID55 nextStepID += 156 record.steps.append(FlowStepRecord(id: id, path: path, action: action, summary: summary, status: .running, startedAt: .now))57 await publish()58 return id59 }6061 func setStep(_ id: Int, _ status: FlowStepRecord.Status, error: String? = nil) async {62 guard let index = record.steps.lastIndex(where: { $0.id == id }) else { return }63 record.steps[index].status = status64 record.steps[index].error = error65 if status != .running, status != .awaitingConfirmation { record.steps[index].finishedAt = .now }66 if status == .awaitingConfirmation { record.status = .awaitingConfirmation }67 else if record.status == .awaitingConfirmation, !record.steps.contains(where: { $0.status == .awaitingConfirmation }) {68 record.status = .running69 }70 await publish()71 }7273 func checkpoint(next: Int, variables: [String: FlowValue], collections: [String: [FlowValue]]) async {74 record.checkpoint = FlowCheckpoint(nextStatement: next, variables: variables, collections: collections)75 await publish()76 }7778 func finish(_ status: FlowRunRecord.Status, failure: FlowRunError?) async -> FlowRunRecord {79 // A step still marked as in progress was interrupted by the failure of a sibling or by cancellation.80 for index in record.steps.indices where record.steps[index].status == .running || record.steps[index].status == .awaitingConfirmation {81 record.steps[index].status = .cancelled82 record.steps[index].finishedAt = .now83 }84 record.status = status85 record.failure = failure86 record.finishedAt = .now87 await publish()88 return record89 }90}9192/// Runs validated workflows. A runner holds no state between runs; several runs can execute at once.93public struct FlowRunner: Sendable {94 private let host: any FlowHost95 private let observers: [any FlowRunObserver]9697 /// - Parameter observers: receive every change of the run record; pass a `FlowRunStore` to make runs98 /// resumable after a failure or a relaunch. Pass none for a ghost (private) context.99 public init(host: any FlowHost, observers: [any FlowRunObserver] = []) {100 self.host = host; self.observers = observers101 }102103 /// Checks the supplied parameters against the declarations and fills in defaults.104 public static func resolveParameters(_ supplied: [String: FlowValue], for program: FlowValidatedProgram) throws -> [String: FlowValue] {105 var resolved: [String: FlowValue] = [:]106 let declared = Set(program.parameters.map(\.name))107 for name in supplied.keys.sorted() where !declared.contains(name) {108 throw FlowRunError.invalidParameter(name: name, reason: "the workflow has no such parameter.")109 }110 for spec in program.parameters {111 guard var value = supplied[spec.name] ?? spec.defaultValue else {112 throw FlowRunError.invalidParameter(name: spec.name, reason: "a value is required.")113 }114 // Text typed by the user for a url parameter is converted here, with the same checks as url().115 if spec.type == .url, case .text(let text) = value { value = .url(try FlowEvaluator.parseURL(text)) }116 guard value.type == spec.type else {117 throw FlowRunError.invalidParameter(name: spec.name, reason: "expected \(spec.type), got \(value.type).")118 }119 switch value {120 case .url(let url):121 guard program.policy.allows(url) else {122 throw FlowRunError.invalidParameter(name: spec.name, reason: "\(url.absoluteString) is not on the allowed domains.")123 }124 case .number(let number) where !number.isFinite:125 throw FlowRunError.invalidParameter(name: spec.name, reason: "the number is not finite.")126 case .text(let text) where text.utf8.count > 64 * 1024:127 throw FlowRunError.invalidParameter(name: spec.name, reason: "the text is longer than 64 KB.")128 default: break129 }130 resolved[spec.name] = value131 }132 return resolved133 }134135 /// Runs a workflow from its first statement. Never throws: the outcome, including any failure, is the136 /// returned record. Cancelling the calling task cancels the run cooperatively.137 public func run(_ program: FlowValidatedProgram, request: FlowRunRequest) async -> FlowRunRecord {138 var record = FlowRunRecord(id: UUID(), workflowID: request.workflowID, name: program.name, sourceHash: program.sourceHash,139 parameters: request.parameters, grantedCapabilities: request.grant.map(\.rawValue).sorted(),140 status: .running, steps: [],141 checkpoint: FlowCheckpoint(nextStatement: 0, variables: [:], collections: [:]),142 statementCount: program.program.body.statements.count, stepsUsed: 0, startedAt: .now,143 updatedAt: .now, finishedAt: nil, failure: nil, resumeCount: 0)144 do {145 let parameters = try Self.resolveParameters(request.parameters, for: program)146 record.parameters = parameters147 record.checkpoint.variables = parameters148 } catch {149 let state = FlowRunState(record: record, limits: program.limits, observers: observers)150 return await state.finish(.failed, failure: error as? FlowRunError ?? .evaluation("\(error)"))151 }152 return await execute(program, record: record, grant: request.grant)153 }154155 /// Continues a stopped run from its last completed top-level statement, with the variables saved there.156 /// The workflow text must be unchanged. The step count carries over; the duration limit starts afresh.157 /// Statements before the checkpoint are not executed again; the interrupted statement is executed again158 /// from its beginning, so its side effects may repeat.159 public func resume(_ record: FlowRunRecord, program: FlowValidatedProgram, grant: Set<FlowCapability>) async throws -> FlowRunRecord {160 guard record.sourceHash == program.sourceHash else { throw FlowRunError.notResumable("the workflow was edited since this run.") }161 guard record.status != .completed else { throw FlowRunError.notResumable("it already completed.") }162 guard record.isResumable, record.checkpoint.nextStatement >= 0,163 record.statementCount == program.program.body.statements.count else {164 throw FlowRunError.notResumable("there is nothing left to run.")165 }166 var resumed = record167 resumed.status = .running168 resumed.failure = nil169 resumed.finishedAt = nil170 resumed.resumeCount += 1171 resumed.grantedCapabilities = grant.map(\.rawValue).sorted()172 // Steps of the interrupted statement stay in the log, marked as they ended.173 for index in resumed.steps.indices where resumed.steps[index].status == .running || resumed.steps[index].status == .awaitingConfirmation {174 resumed.steps[index].status = .cancelled175 }176 return await execute(program, record: resumed, grant: grant)177 }178179 private func execute(_ program: FlowValidatedProgram, record: FlowRunRecord, grant: Set<FlowCapability>) async -> FlowRunRecord {180 let state = FlowRunState(record: record, limits: program.limits, observers: observers)181 await state.start()182 let interpreter = FlowInterpreter(program: program, host: host, state: state, grant: grant, runID: record.id)183 var env = FlowEnvironment(scopes: [record.checkpoint.variables], collections: record.checkpoint.collections)184 let statements = program.program.body.statements185 do {186 for index in record.checkpoint.nextStatement..<statements.count {187 try Task.checkCancellation()188 try await interpreter.execute(statements[index], &env, path: "\(index)")189 await state.checkpoint(next: index + 1, variables: env.scopes[0], collections: env.collections)190 }191 return await state.finish(.completed, failure: nil)192 } catch {193 let failure = FlowInterpreter.map(error, action: "")194 return await state.finish(failure == .cancelled ? .cancelled : .failed, failure: failure)195 }196 }197}198199struct FlowInterpreter: Sendable {200 let program: FlowValidatedProgram201 let host: any FlowHost202 let state: FlowRunState203 let grant: Set<FlowCapability>204 let runID: UUID205206 private var evaluator: FlowEvaluator {207 FlowEvaluator(policy: program.policy, caps: program.caps, knownCollections: Set(program.collections.keys))208 }209210 static func map(_ error: any Error, action: String) -> FlowRunError {211 if let error = error as? FlowRunError { return error }212 if error is CancellationError { return .cancelled }213 // The host's message may quote page content; keep it short and single-line for the log.214 let message = String(describing: error).split(whereSeparator: \.isNewline).first.map(String.init) ?? "error"215 return .hostFailure(action: action, message: String(message.prefix(300)))216 }217218 func execute(_ statements: [FlowStatement], _ env: inout FlowEnvironment, path: String) async throws {219 for (index, statement) in statements.enumerated() {220 try await execute(statement, &env, path: "\(path).\(index)")221 }222 }223224 private func scoped(_ env: inout FlowEnvironment, bindings: [String: FlowValue] = [:],225 _ body: (inout FlowEnvironment) async throws -> Void) async throws {226 env.scopes.append(bindings)227 defer { env.scopes.removeLast() }228 try await body(&env)229 }230231 func execute(_ statement: FlowStatement, _ env: inout FlowEnvironment, path: String) async throws {232 try Task.checkCancellation()233 switch statement.kind {234 case .action(let action):235 let value = try await run(action, env, path: path)236 if let binding = action.binding { env.bind(binding, value) }237 case .let_(let statement):238 env.bind(statement.name, try evaluator.evaluate(statement.value, env))239 case .collect(let collect):240 let value = try evaluator.evaluate(collect.value, env)241 var items = env.collections[collect.target] ?? []242 guard items.count < program.caps.maximumListLength else {243 throw FlowRunError.valueTooLarge("“\(collect.target)” exceeds \(program.caps.maximumListLength) items.")244 }245 items.append(value)246 env.collections[collect.target] = items247 case .conditional(let conditional):248 guard case .bool(let flag) = try evaluator.evaluate(conditional.condition, env) else {249 throw FlowRunError.evaluation("A condition must be true or false.")250 }251 if flag {252 try await scoped(&env) { try await execute(conditional.thenBlock.statements, &$0, path: path + ".then") }253 } else if let elseBlock = conditional.elseBlock {254 try await scoped(&env) { try await execute(elseBlock.statements, &$0, path: path + ".else") }255 }256 case .forEach(let loop):257 guard case .list(let all) = try evaluator.evaluate(loop.sequence, env) else {258 throw FlowRunError.evaluation("“for” needs a list.")259 }260 // The static limit bounds the loop whatever the list holds.261 let items = Array(all.prefix(min(loop.limit ?? 1, program.caps.maximumLoopIterations)))262 if let width = loop.parallelWidth, width > 1, items.count > 1 {263 let results = try await branches(count: items.count, width: width, base: env) { index, branch in264 branch.scopes.append([loop.variable: items[index]])265 try await execute(loop.body.statements, &branch, path: "\(path)[\(index)]")266 }267 merge(results, into: &env, bindings: false)268 } else {269 for (index, item) in items.enumerated() {270 try await scoped(&env, bindings: [loop.variable: item]) {271 try await execute(loop.body.statements, &$0, path: "\(path)[\(index)]")272 }273 }274 }275 case .parallel(let parallel):276 let statements = parallel.body.statements277 let width = min(parallel.width ?? 1, program.caps.maximumParallelWidth)278 let results = try await branches(count: statements.count, width: width, base: env) { index, branch in279 branch.scopes.append([:])280 try await execute(statements[index], &branch, path: "\(path).\(index)")281 }282 merge(results, into: &env, bindings: true)283 }284 }285286 /// Runs `count` branches, at most `width` at a time, each on its own copy of the environment. The first287 /// failure cancels the others and is rethrown.288 private func branches(count: Int, width: Int, base: FlowEnvironment,289 _ body: @escaping @Sendable (Int, inout FlowEnvironment) async throws -> Void) async throws -> [FlowEnvironment] {290 guard count > 0 else { return [] }291 return try await withThrowingTaskGroup(of: (Int, FlowEnvironment).self) { group in292 var results = [FlowEnvironment?](repeating: nil, count: count)293 var next = 0294 let initial = min(max(1, width), count)295 while next < initial {296 let index = next297 next += 1298 group.addTask { var env = base; try await body(index, &env); return (index, env) }299 }300 while let (index, env) = try await group.next() {301 results[index] = env302 if next < count {303 let following = next304 next += 1305 group.addTask { var env = base; try await body(following, &env); return (following, env) }306 }307 }308 return results.compactMap { $0 }309 }310 }311312 /// Folds branch results back in branch order, so the outcome does not depend on which branch finished313 /// first: collected items are appended branch by branch; names bound by a branch become visible after the block.314 private func merge(_ results: [FlowEnvironment], into env: inout FlowEnvironment, bindings: Bool) {315 let base = env.collections.mapValues(\.count)316 for result in results {317 for (name, items) in result.collections.sorted(by: { $0.key < $1.key }) {318 let added = items.dropFirst(base[name] ?? 0)319 if !added.isEmpty { env.collections[name, default: []].append(contentsOf: added) }320 }321 if bindings, let scope = result.scopes.last, result.scopes.count == env.scopes.count + 1 {322 for (name, value) in scope { env.bind(name, value) }323 }324 }325 }326327 // MARK: Actions328329 static func summarize(_ name: String, _ arguments: [String: FlowValue], definition: FlowActionDefinition) -> String {330 var text = name331 for parameter in definition.parameters {332 guard let value = arguments[parameter.name] else { continue }333 let shown = String(value.displayText.split(whereSeparator: \.isNewline).first ?? "").prefix(120)334 text += parameter.label.map { " \($0) \(shown)" } ?? " \(shown)"335 }336 return text337 }338339 private func run(_ action: FlowActionStatement, _ env: FlowEnvironment, path: String) async throws -> FlowValue {340 guard let definition = program.registry.definition(named: action.name) else {341 throw FlowRunError.evaluation("Unknown action “\(action.name)”.")342 }343 var arguments: [String: FlowValue] = [:]344 for argument in action.arguments {345 guard let parameter = definition.parameter(label: argument.label) else { continue }346 switch parameter.kind {347 case .option:348 guard case .identifier(let word, _) = argument.value else { throw FlowRunError.evaluation("Invalid option for “\(action.name)”.") }349 arguments[parameter.name] = .option(word)350 case .value(let types):351 var expecting: FlowType? = types.count == 1 ? types[0] : nil352 if case .string = argument.value, types.contains(.url), !types.contains(.text) { expecting = .url }353 arguments[parameter.name] = try evaluator.evaluate(argument.value, env, expecting: expecting)354 }355 }356 let summary = Self.summarize(action.name, arguments, definition: definition)357 let stepID = try await state.beginStep(path: path, action: action.name, summary: summary)358 do {359 let value = try await perform(definition, arguments, stepID: stepID, summary: summary)360 await state.setStep(stepID, .succeeded)361 return value362 } catch {363 let failure = Self.map(error, action: action.name)364 let status: FlowStepRecord.Status365 switch failure {366 case .cancelled: status = .cancelled367 case .confirmationDenied: status = .denied368 case .stepTimedOut, .durationLimitExceeded: status = .timedOut369 default: status = .failed370 }371 await state.setStep(stepID, status, error: failure.description)372 throw failure373 }374 }375376 private func perform(_ definition: FlowActionDefinition, _ arguments: [String: FlowValue], stepID: Int, summary: String) async throws -> FlowValue {377 // 1. Capability granted for this run?378 if let capability = definition.capability, !grant.contains(capability) {379 throw FlowRunError.capabilityNotGranted(capability: capability.rawValue, action: definition.name)380 }381 // 2. Every URL the host could act on is on the allow-list — checked on the actual run-time values.382 for value in arguments.values {383 for url in value.navigableURLs where !program.policy.allows(url) {384 throw FlowRunError.domainNotAllowed(url: url.absoluteString, action: definition.name)385 }386 }387 // 3. Engine-only action.388 if definition.name == FlowBuiltInAction.wait {389 guard case .duration(let seconds)? = arguments["duration"], seconds.isFinite, seconds >= 0 else {390 throw FlowRunError.evaluation("“wait” needs a duration.")391 }392 let pause = min(seconds, program.caps.maximumWaitSeconds, try await state.remainingSeconds())393 try await Task.sleep(for: .seconds(pause))394 return .nothing395 }396 // 4. Confirmation: the run pauses, and the wait is not charged to the duration limit.397 if definition.confirmation == .always {398 await state.setStep(stepID, .awaitingConfirmation)399 let asked = ContinuousClock.now400 let confirmed = await host.confirm(FlowConfirmationRequest(runID: runID, stepID: stepID, workflowName: program.name,401 action: definition.name, capability: definition.capability,402 summary: summary, arguments: arguments))403 await state.extendDeadline(by: asked.duration(to: .now))404 try Task.checkCancellation()405 guard confirmed else { throw FlowRunError.confirmationDenied(action: definition.name) }406 await state.setStep(stepID, .running)407 }408 // 5. The host call, bounded by the step timeout and by what is left of the run.409 let remaining = try await state.remainingSeconds()410 let timeout = min(program.limits.stepTimeoutSeconds, remaining)411 let call = FlowActionCall(runID: runID, stepID: stepID, action: definition.name, arguments: arguments, policy: program.policy,412 timeoutSeconds: timeout, spaceName: program.program.spaceName)413 let host = self.host414 let limits = program.limits415 let value = try await withThrowingTaskGroup(of: FlowValue.self) { group in416 group.addTask { try await host.perform(call) }417 group.addTask {418 try await Task.sleep(for: .seconds(timeout))419 throw remaining < limits.stepTimeoutSeconds420 ? FlowRunError.durationLimitExceeded(seconds: limits.maximumDurationSeconds)421 : FlowRunError.stepTimedOut(action: call.action, seconds: timeout)422 }423 defer { group.cancelAll() }424 guard let first = try await group.next() else { throw FlowRunError.cancelled }425 return first426 }427 // 6. The host's answer is data from outside: check its type, its size and where a page ended up.428 guard value.type.isAssignable(to: definition.result) else {429 throw FlowRunError.hostContractViolation(action: definition.name, expected: "\(definition.result)", got: "\(value.type)")430 }431 if case .page(let page) = value, !program.policy.allows(page.url) {432 throw FlowRunError.domainNotAllowed(url: page.url.absoluteString, action: definition.name)433 }434 return try evaluator.check(value)435 }436}437438// MARK: - Dry run439440public struct FlowPlannedURL: Sendable, Hashable {441 /// The address, with `{name}` left in place where the value is only known while running.442 public var text: String443 public var isResolved: Bool444 /// `nil` when the URL is not resolved; it will be checked against the allow-list when the step runs.445 public var isAllowed: Bool?446}447448public struct FlowPlanStep: Sendable, Hashable {449 public var path: String450 public var action: String451 public var summary: String452 public var capability: FlowCapability?453 public var isGranted: Bool454 public var needsConfirmation: Bool455 public var urls: [FlowPlannedURL]456 /// How many times the step can run at most (product of the enclosing loop limits).457 public var maximumRepetitions: Int458 public var isConditional: Bool459 public var isParallel: Bool460}461462/// What a run would do, computed from the program text and the parameters only. Producing a plan calls no463/// host and has no side effect.464public struct FlowPlan: Sendable, Hashable {465 public var name: String466 public var spaceName: String?467 public var steps: [FlowPlanStep]468 public var requiredCapabilities: [FlowCapability]469 public var missingCapabilities: [FlowCapability]470 /// Worst-case number of confirmation prompts.471 public var maximumConfirmations: Int472 public var worstCaseSteps: Int473 public var limits: FlowLimits474 public var allowedDomains: [String]475 /// Reasons the run would fail before or while running (bad parameter, missing permission, URL off the list).476 public var problems: [String]477 public var isRunnable: Bool { problems.isEmpty }478}479480extension FlowRunner {481 /// Dry run: the full plan of a workflow for given parameters and permissions.482 public static func plan(_ program: FlowValidatedProgram, parameters: [String: FlowValue] = [:], grant: Set<FlowCapability>) -> FlowPlan {483 var problems: [String] = []484 var values: [String: FlowValue] = [:]485 do { values = try resolveParameters(parameters, for: program) } catch { problems.append("\(error)") }486 var planner = FlowPlanner(program: program, parameters: values, grant: grant)487 planner.walk(program.program.body.statements, path: "", repetitions: 1, conditional: false, parallel: false)488 let required = program.capabilities.sorted()489 let missing = required.filter { !grant.contains($0) }490 for capability in missing { problems.append("The “\(capability)” permission is needed and was not granted.") }491 for step in planner.steps {492 for url in step.urls where url.isAllowed == false { problems.append("\(url.text) is not on the allowed domains.") }493 }494 if program.worstCaseSteps > program.limits.maximumSteps {495 problems.append("The workflow can need \(program.worstCaseSteps) steps; it stops at its limit of \(program.limits.maximumSteps).")496 }497 return FlowPlan(name: program.name, spaceName: program.program.spaceName, steps: planner.steps, requiredCapabilities: required,498 missingCapabilities: missing,499 maximumConfirmations: planner.steps.filter(\.needsConfirmation).reduce(0) { $0 + $1.maximumRepetitions },500 worstCaseSteps: program.worstCaseSteps, limits: program.limits, allowedDomains: program.policy.domains,501 problems: problems)502 }503}504505private struct FlowPlanner {506 let program: FlowValidatedProgram507 let parameters: [String: FlowValue]508 let grant: Set<FlowCapability>509 var steps: [FlowPlanStep] = []510511 /// Source-like rendering of an expression, with parameter values substituted.512 func render(_ expression: FlowExpression, asURL: Bool = false) -> (text: String, resolved: Bool) {513 switch expression {514 case .string(let literal):515 var text = "", resolved = true516 for part in literal.parts {517 switch part {518 case .text(let piece): text += piece519 case .interpolation(let path, _):520 if path.count == 1, let value = parameters[path[0]] {521 let piece = value.displayText522 text += asURL ? (piece.addingPercentEncoding(withAllowedCharacters: FlowEvaluator.urlComponentAllowed) ?? "") : piece523 } else {524 text += "{\(path.joined(separator: "."))}"525 resolved = false526 }527 }528 }529 return (text, resolved)530 case .number(let value, _): return (FlowValue.number(value).displayText, true)531 case .bool(let value, _): return (value ? "true" : "false", true)532 case .duration(let seconds, _): return (FlowValue.duration(seconds).displayText, true)533 case .identifier(let name, _):534 if let value = parameters[name] { return (value.displayText, true) }535 return (name, false)536 case .member(let base, let name, _): return ("\(render(base).text).\(name)", false)537 case .call(let name, let arguments, _): return ("\(name)(\(arguments.map { render($0).text }.joined(separator: ", ")))", false)538 case .list(let items, _): return ("[\(items.map { render($0).text }.joined(separator: ", "))]", false)539 case .not(let operand, _): return ("not \(render(operand).text)", false)540 case .binary(let op, let left, let right, _): return ("\(render(left).text) \(op.rawValue) \(render(right).text)", false)541 case .invalid: return ("?", false)542 }543 }544545 mutating func walk(_ statements: [FlowStatement], path: String, repetitions: Int, conditional: Bool, parallel: Bool) {546 for (index, statement) in statements.enumerated() {547 let here = path.isEmpty ? "\(index)" : "\(path).\(index)"548 switch statement.kind {549 case .let_, .collect: break550 case .action(let action):551 guard let definition = program.registry.definition(named: action.name) else { continue }552 var summary = action.name553 var urls: [FlowPlannedURL] = []554 for parameter in definition.parameters {555 guard let argument = action.arguments.first(where: { $0.label == parameter.label }) else { continue }556 var isURL = false557 if case .value(let types) = parameter.kind, types.contains(.url) { isURL = true }558 let rendered = render(argument.value, asURL: isURL)559 summary += parameter.label.map { " \($0) \(rendered.text)" } ?? " \(rendered.text)"560 guard isURL else { continue }561 if rendered.resolved, let url = try? FlowEvaluator.parseURL(rendered.text) {562 urls.append(FlowPlannedURL(text: url.absoluteString, isResolved: true, isAllowed: program.policy.allows(url)))563 } else if case .string = argument.value {564 urls.append(FlowPlannedURL(text: rendered.text, isResolved: false, isAllowed: nil))565 } else if case .identifier(let name, _) = argument.value, case .url(let url)? = parameters[name] {566 urls.append(FlowPlannedURL(text: url.absoluteString, isResolved: true, isAllowed: program.policy.allows(url)))567 } else {568 urls.append(FlowPlannedURL(text: rendered.text, isResolved: false, isAllowed: nil))569 }570 }571 steps.append(FlowPlanStep(path: here, action: action.name, summary: summary, capability: definition.capability,572 isGranted: definition.capability.map(grant.contains) ?? true,573 needsConfirmation: definition.confirmation == .always, urls: urls,574 maximumRepetitions: repetitions, isConditional: conditional, isParallel: parallel))575 case .forEach(let loop):576 walk(loop.body.statements, path: here + "[]", repetitions: repetitions * max(1, loop.limit ?? 1),577 conditional: conditional, parallel: parallel || (loop.parallelWidth ?? 1) > 1)578 case .parallel(let block):579 walk(block.body.statements, path: here, repetitions: repetitions, conditional: conditional, parallel: true)580 case .conditional(let branch):581 walk(branch.thenBlock.statements, path: here + ".then", repetitions: repetitions, conditional: true, parallel: parallel)582 if let elseBlock = branch.elseBlock {583 walk(elseBlock.statements, path: here + ".else", repetitions: repetitions, conditional: true, parallel: parallel)584 }585 }586 }587 }588}589