Repository Public License
1import Foundation2import PrismComponentSDK3import PrismCore4import PrismDataRuntime5import PrismIconKit6import PrismLogicRuntime7import PrismObjectModel8import PrismRenderer9import PrismScriptRuntime1011/// The agent's working area for one build: a draft blueprint, checkpoints, and a throwaway preview.12/// Nothing here touches the saved project until the user accepts the result.13@MainActor14public final class BuildWorkspace {15 public struct CallRecord: Sendable, Equatable {16 public var tool: String17 public var ok: Bool18 public var summary: String19 }2021 public let registry: ComponentRegistry22 /// The saved app when evolving; nil when creating.23 public let baseline: AppBlueprint?24 public private(set) var blueprint: AppBlueprint?25 public private(set) var intent: JSONValue?26 public private(set) var calls: [CallRecord] = []27 public private(set) var requestedPermissions: [String] = []28 public private(set) var preview: AppRuntime?29 private var checkpoints: [String: AppBlueprint] = [:]30 private var catalogConsulted = false3132 /// Off by default: the model sees schema and counts, never the user's rows (threat model §3).33 public var allowSampleRows = false34 /// The user's existing database for this project, used read-only by `data.migrate`.35 public var existingDataURL: URL?36 /// Asks the user. When nil, grantable permissions are recorded for the approval screen and anything else is denied.37 public var permissionHandler: ((_ permission: String, _ reason: String) async -> Bool)?38 public var audit: (_ kind: String, _ summary: String, _ detail: JSONValue) -> Void = { _, _, _ in }3940 public init(registry: ComponentRegistry, baseline: AppBlueprint? = nil) {41 self.registry = registry42 self.baseline = baseline43 self.blueprint = baseline44 self.catalogConsulted = false45 }4647 public var issues: [ValidationIssue] { blueprint.map { BlueprintValidator.validate($0, registry: registry) } ?? [] }4849 // MARK: Execution5051 public func execute(_ name: String, _ input: JSONValue, dryRun: Bool = false) async -> ToolResult {52 guard let spec = ToolCatalog.spec(wireName: name) else {53 return record(name, .failure("tool.unknown", "There is no tool `\(name)`."), input: input)54 }55 let problems = SchemaValidator.problems(input, schema: spec.inputSchema)56 guard problems.isEmpty else {57 return record(spec.name, .failure("input.invalid", problems.joined(separator: " ")), input: input)58 }59 let before = blueprint60 var result = await run(spec, input)61 if dryRun && spec.mutating {62 // Dry run: report what would happen, then put everything back.63 blueprint = before64 if var o = result.content.objectValue { o["dryRun"] = true; result.content = .object(o) }65 } else if blueprint != before {66 preview = nil67 }68 return record(spec.name, result, input: input, dryRun: dryRun)69 }7071 private func record(_ tool: String, _ result: ToolResult, input: JSONValue, dryRun: Bool = false) -> ToolResult {72 calls.append(CallRecord(tool: tool, ok: result.ok, summary: result.summary))73 audit("tool.call", "\(tool): \(result.summary)", ["tool": .string(tool), "ok": .bool(result.ok), "dryRun": .bool(dryRun), "input": Self.abbreviated(input)])74 return result75 }7677 /// Audit entries keep the shape of an input without storing large payloads.78 static func abbreviated(_ value: JSONValue, depth: Int = 0) -> JSONValue {79 switch value {80 case .string(let s): return s.count > 200 ? .string(String(s.prefix(200)) + "…") : value81 case .array(let a): return depth > 3 ? .string("[\(a.count) items]") : .array(a.prefix(20).map { abbreviated($0, depth: depth + 1) })82 case .object(let o): return depth > 3 ? .string("{\(o.count) fields}") : .object(o.mapValues { abbreviated($0, depth: depth + 1) })83 default: return value84 }85 }8687 private func need() throws -> AppBlueprint {88 guard let blueprint else { throw ToolFailure("project.missing", "Call project.create first.") }89 return blueprint90 }9192 private struct ToolFailure: Error {93 let code: String, message: String94 init(_ code: String, _ message: String) { self.code = code; self.message = message }95 }9697 private func mutate(_ summary: String, _ patches: [BlueprintPatch]) throws -> ToolResult {98 let bp = try need()99 do { blueprint = try bp.applying(patches) } catch { throw ToolFailure("patch.failed", error.localizedDescription) }100 return .success(["ok": true], summary)101 }102103 private func run(_ spec: ToolSpec, _ input: JSONValue) async -> ToolResult {104 do { return try await dispatch(spec, input) }105 catch let f as ToolFailure { return .failure(f.code, f.message) }106 catch { return .failure("tool.failed", error.localizedDescription) }107 }108109 private func dispatch(_ spec: ToolSpec, _ input: JSONValue) async throws -> ToolResult {110 func s(_ key: String) -> String { input[key]?.stringValue ?? "" }111 switch spec.name {112 // MARK: catalog113 case "catalog.search":114 catalogConsulted = true115 let hits = registry.search(s("query"), category: input["category"]?.stringValue, limit: min(max(input["limit"]?.intValue ?? 10, 1), 40))116 var results: [JSONValue] = hits.map { ["type": .string($0.manifest.type), "name": .string($0.manifest.name), "category": .string($0.manifest.category), "summary": .string($0.manifest.summary)] }117 // Components already defined for this app are offered alongside the catalog.118 for d in blueprint?.componentDefinitions ?? [] {119 results.append(["type": .string(ObjectType.customPrefix + d.id), "name": .string(d.name.isEmpty ? d.id : d.name), "category": "custom", "summary": d.props["summary"] ?? ""])120 }121 return .success(["results": .array(results)],122 hits.isEmpty ? "No component matches “\(s("query"))”" : "Found \(hits.count): \(hits.prefix(4).map(\.manifest.name).joined(separator: ", "))")123 case "catalog.inspect":124 catalogConsulted = true125 guard let m = registry.manifest(s("type")) ?? blueprint.flatMap({ registry.manifest(s("type"), in: $0) }) else { throw ToolFailure("component.unknown", "`\(s("type"))` is not in the catalog. Use catalog.search.") }126 var json = m.json.objectValue ?? [:]127 json["fixture"] = nil128 json["examples"] = nil129 json["commonProps"] = .array(CommonProps.all.map { ["name": .string($0.name), "kind": .string($0.kind.rawValue), "summary": .string($0.summary)] })130 return .success(.object(json), "Inspected \(m.name)")131 case "catalog.examples":132 catalogConsulted = true133 guard let m = registry.manifest(s("type")) else { throw ToolFailure("component.unknown", "`\(s("type"))` is not in the catalog.") }134 return .success(["examples": .array(m.examples)], "\(m.examples.count) example(s) of \(m.name)")135136 // MARK: project137 case "project.create":138 guard blueprint == nil else { throw ToolFailure("project.exists", "The app already exists. Use project.read and the ui.* tools to change it.") }139 let name = s("name").trimmingCharacters(in: .whitespacesAndNewlines)140 guard !name.isEmpty else { throw ToolFailure("input.invalid", "The app needs a name.") }141 var bp = AppBlueprint(id: "app_" + PrismID.slug(name), name: String(name.prefix(60)))142 bp.summary = s("summary")143 blueprint = bp144 intent = ["summary": .string(s("summary")), "features": input["features"] ?? [], "acceptanceCriteria": input["acceptanceCriteria"] ?? []]145 return .success(["appId": .string(bp.id)], "Intent parsed: “\(bp.name)” with \(input["acceptanceCriteria"]?.arrayValue?.count ?? 0) acceptance criteria")146 case "project.read":147 let bp = try need()148 if let id = input["objectId"]?.stringValue {149 guard let o = bp.object(id) else { throw ToolFailure("object.missing", "There is no object `\(id)`.") }150 return .success(o.json, "Read \(id)")151 }152 return .success(Self.outline(bp), "Read the app outline (\(bp.objects.count) objects)")153 case "project.patch":154 let patches: [BlueprintPatch]155 do { patches = try (input["patches"]?.arrayValue ?? []).map(BlueprintPatch.init(json:)) } catch { throw ToolFailure("patch.invalid", error.localizedDescription) }156 if patches.contains(where: { if case .addObject(let o, _, _) = $0 { return o.isComponent } else { return false } }) { try requireCatalog() }157 return try mutate("Applied \(patches.count) patch(es)", patches)158 case "project.snapshot":159 checkpoints[s("label")] = try need()160 return .success(["checkpoints": .array(checkpoints.keys.sorted().map(JSONValue.string))], "Checkpoint “\(s("label"))” saved")161 case "project.rollback":162 guard let saved = checkpoints[s("label")] else { throw ToolFailure("checkpoint.missing", "No checkpoint “\(s("label"))”. Known: \(checkpoints.keys.sorted().joined(separator: ", ")).") }163 blueprint = saved164 return .success(["ok": true], "Returned to checkpoint “\(s("label"))”")165166 // MARK: ui167 case "ui.createPage":168 let bp = try need()169 var page = PrismObject(id: s("id"), type: ObjectType.page, name: s("name"), provenance: ["source": "agent"])170 if let icon = input["icon"] { page.props["icon"] = icon }171 var patches: [BlueprintPatch] = [.addObject(page, parent: nil, index: nil)]172 if bp.entrypoint.isEmpty { patches.append(.setBlueprintField(field: "entrypoint", value: .string(page.id))) }173 return try mutate("Page “\(page.name)” created", patches)174 case "ui.addComponent":175 try requireCatalog()176 let bp = try need()177 guard let manifest = registry.manifest(s("type"), in: bp) else {178 throw ToolFailure("component.unknown", "`\(s("type"))` is not in the catalog. Search the catalog; if nothing fits, define an on-demand component with component.define and use its `custom.<id>` type.")179 }180 guard let parent = bp.object(s("parent")) else { throw ToolFailure("parent.missing", "There is no object `\(s("parent"))` to put this in.") }181 if parent.isComponent, registry.manifest(parent.type, in: bp)?.acceptsChildren != true {182 throw ToolFailure("parent.leaf", "`\(parent.id)` (\(parent.type)) cannot contain components. Use a stack, card, grid or another container.")183 }184 var object = PrismObject(id: s("id"), type: manifest.type, name: s("name"), props: input["props"]?.objectValue ?? [:], provenance: ["source": "agent"])185 for (event, actions) in input["events"]?.objectValue ?? [:] { object.events[event] = actions.arrayValue ?? [] }186 if let table = object.props["table"]?.stringValue ?? object.props["query"]?["table"]?.stringValue, bp.object(table)?.isTable == true { object.dependencies = [table] }187 return try mutate("Added \(manifest.name) “\(object.name.isEmpty ? object.id : object.name)”", [.addObject(object, parent: parent.id, index: input["index"]?.intValue)])188 case "ui.setProperties":189 var patches: [BlueprintPatch] = []190 for (k, v) in (input["props"]?.objectValue ?? [:]).sorted(by: { $0.key < $1.key }) { patches.append(.setProp(id: s("id"), key: k, value: v)) }191 for k in input["remove"]?.arrayValue ?? [] { if let k = k.stringValue { patches.append(.removeProp(id: s("id"), key: k)) } }192 if let name = input["name"] { patches.append(.setField(id: s("id"), field: "name", value: name)) }193 guard !patches.isEmpty else { throw ToolFailure("input.invalid", "Nothing to change: give `props`, `remove` or `name`.") }194 return try mutate("Updated \(s("id"))", patches)195 case "ui.connectAction":196 return try mutate("Connected \(s("event")) of \(s("id"))", [.setEvent(id: s("id"), event: s("event"), actions: input["actions"]?.arrayValue ?? [])])197 case "ui.preview", "code.runTests", "runtime.start":198 return try previewReport(restart: spec.name == "runtime.start")199 case "code.lint":200 let warnings = issues.warnings201 return .success(["warnings": .array(warnings.map(\.json))], warnings.isEmpty ? "No warnings" : "\(warnings.count) warning(s)")202203 // MARK: data204 case "data.createSchema":205 let bp = try need()206 var props: [String: JSONValue] = ["columns": input["columns"] ?? []]207 if let seed = input["seed"] { props["seed"] = seed }208 let table = PrismObject(id: s("id"), type: ObjectType.dataTable, name: s("name").isEmpty ? s("id") : s("name"), props: props, provenance: ["source": "agent"])209 do { _ = try TableSchema(object: table) } catch { throw ToolFailure("schema.invalid", error.localizedDescription) }210 var patches: [BlueprintPatch] = bp.object(table.id) == nil211 ? [.addObject(table, parent: nil, index: nil)]212 : [.setField(id: table.id, field: "props", value: .object(props)), .setField(id: table.id, field: "name", value: .string(table.name))]213 if bp.object(table.id) != nil, bp.object(table.id)?.isTable != true { throw ToolFailure("id.taken", "`\(table.id)` already exists and is not a table.") }214 if !bp.permissions.contains(Permission.storageLocal) {215 patches.append(.setBlueprintField(field: "permissions", value: .array((bp.permissions + [Permission.storageLocal]).map(JSONValue.string))))216 if !requestedPermissions.contains(Permission.storageLocal) { requestedPermissions.append(Permission.storageLocal) }217 }218 return try mutate("Data model: table “\(table.name)” with \(input["columns"]?.arrayValue?.count ?? 0) columns", patches)219 case "data.import":220 let bp = try need()221 guard let table = bp.object(s("table")), table.isTable else { throw ToolFailure("table.missing", "There is no table `\(s("table"))`.") }222 let rows = input["rows"]?.arrayValue ?? []223 guard rows.count <= 200 else { throw ToolFailure("input.tooLarge", "At most 200 sample rows.") }224 let schema = try TableSchema(object: table)225 for (i, row) in rows.enumerated() {226 for (k, v) in row.objectValue ?? [:] {227 guard let column = schema.column(k) else { throw ToolFailure("column.unknown", "Row \(i + 1): table `\(table.id)` has no column `\(k)`.") }228 do { _ = try schema.coerce(v, for: column) } catch { throw ToolFailure("row.invalid", "Row \(i + 1): \(error.localizedDescription)") }229 }230 }231 return try mutate("Set \(rows.count) sample row(s) for \(table.id)", [.setProp(id: table.id, key: "seed", value: .array(rows))])232 case "data.query":233 let runtime = try startPreview()234 let query: DataQuery235 do { query = try DataQuery(json: input["query"] ?? .null) } catch { throw ToolFailure("query.invalid", error.localizedDescription) }236 guard let schema = runtime.schema(query.table) else { throw ToolFailure("table.missing", "There is no table `\(query.table)`.") }237 if let problem = query.problems(schema: schema).first { throw ToolFailure("query.invalid", problem) }238 let rows: [[String: JSONValue]]239 do { rows = try runtime.store.run(query, scope: runtime.scope()) } catch { throw ToolFailure("query.failed", error.localizedDescription) }240 var out: [String: JSONValue] = ["columns": .array(query.outputColumns(schema: schema).map(JSONValue.string)), "rowCount": .int(rows.count)]241 if allowSampleRows { out["sampleRows"] = .array(rows.prefix(5).map(JSONValue.object)) }242 return .success(.object(out), "Query returns \(rows.count) row(s)")243 case "data.migrate":244 let bp = try need()245 let store = try AppDataStore(url: existingDataURL)246 defer { store.close() }247 let plan: AppDataStore.MigrationReport248 do { plan = try store.plan(for: bp) } catch { throw ToolFailure("schema.invalid", error.localizedDescription) }249 return .success(["createdTables": .array(plan.createdTables.map(JSONValue.string)), "addedColumns": .array(plan.addedColumns.map(JSONValue.string)),250 "kept": .array(plan.retained.map(JSONValue.string)), "dropsData": false],251 "Migration plan: +\(plan.createdTables.count) table(s), +\(plan.addedColumns.count) column(s), nothing dropped")252253 // MARK: logic254 case "logic.createWorkflow":255 let bp = try need()256 let queryJSON = input["query"] ?? .null257 do { _ = try DataQuery(json: queryJSON) } catch { throw ToolFailure("query.invalid", error.localizedDescription) }258 let object = PrismObject(id: s("id"), type: ObjectType.dataQuery, name: s("name"), props: ["query": queryJSON],259 dependencies: (queryJSON["table"]?.stringValue).flatMap { bp.object($0) != nil ? [$0] : nil } ?? [], provenance: ["source": "agent", "generated": true])260 let patches: [BlueprintPatch] = bp.object(object.id) == nil ? [.addObject(object, parent: nil, index: nil)] : [.setProp(id: object.id, key: "query", value: queryJSON)]261 return try mutate("Query “\(object.id)” defined", patches)262 case "logic.bind":263 let bp = try need()264 var state = bp.state265 for (k, v) in input["state"]?.objectValue ?? [:] {266 guard StatePath.isValid(k), !k.contains(".") else { throw ToolFailure("state.invalid", "`\(k)` is not a valid state key (letters, digits, underscores).") }267 state[k] = v268 }269 return try mutate("Declared state: \((input["state"]?.objectValue ?? [:]).keys.sorted().joined(separator: ", "))", [.setBlueprintField(field: "state", value: .object(state))])270 case "logic.validate":271 let runtime = try startPreview()272 let expression: PrismLogicRuntime.Expression273 do { expression = try PrismLogicRuntime.Expression(s("expression")) } catch { throw ToolFailure("expression.syntax", error.localizedDescription) }274 if let unknown = expression.calledFunctions.first(where: { !Evaluator.functionNames.contains($0) }) {275 throw ToolFailure("expression.function", "Unknown function `\(unknown)`. Available: \(Evaluator.functionNames.sorted().joined(separator: ", ")).")276 }277 do {278 let value = try Evaluator.evaluate(expression, scope: runtime.scope())279 return .success(["valid": true, "type": .string(value.typeName), "value": allowSampleRows || value.arrayValue == nil ? value : .string("[\(value.arrayValue?.count ?? 0) rows]")], "Expression is valid (\(value.typeName))")280 } catch { throw ToolFailure("expression.runtime", error.localizedDescription) }281282 // MARK: design283 case "design.listThemes":284 return .success([285 "presets": .array(ThemeSpec.presets.map { ["name": .string($0.name), "summary": .string($0.summary), "theme": $0.theme] }),286 "tokens": [287 "preset": "A preset name; explicit tokens below override it.", "accent": "hex", "appearance": "system | light | dark (derived from the background when a palette is given)",288 "density": "compact | regular | comfortable", "radius": "0 to 28", "font": .string(ThemeSpec.fonts.joined(separator: " | ")), "headingFont": .string(ThemeSpec.fonts.joined(separator: " | ")),289 "headingWeight": .string(ThemeSpec.weights.joined(separator: " | ")), "surface": .string(ThemeSpec.surfaces.joined(separator: " | ") + " (how cards and panels are drawn)"),290 "palette": .string("{" + ThemeSpec.paletteKeys.joined(separator: ", ") + "} as hex colors"), "backgroundGradient": "2 or 3 hex colors, all dark or all light", "backgroundAngle": "degrees",291 "chartColors": "1 to 8 hex colors",292 ],293 ], "\(ThemeSpec.presets.count) theme presets")294 case "design.setTheme":295 _ = try need()296 guard let theme = input["theme"]?.objectValue, !theme.isEmpty else { throw ToolFailure("input.invalid", "`theme` must be an object with a preset and/or tokens.") }297 let problems = ThemeSpec.problems(theme)298 if let first = problems.first(where: \.isError) { throw ToolFailure("theme.invalid", problems.filter(\.isError).map(\.message).joined(separator: " ").isEmpty ? first.message : problems.filter(\.isError).map(\.message).joined(separator: " ")) }299 var result = try mutate("Theme set" + ((theme["preset"]?.stringValue).map { " from preset “\($0)”" } ?? " (custom)"), [.setBlueprintField(field: "theme", value: .object(theme))])300 result.content = ["ok": true, "warnings": .array(problems.map { .string($0.message) }), "resolved": .object(ThemeSpec.resolved(theme))]301 return result302 case "design.setIcon":303 _ = try need()304 let icon = input["icon"] ?? .null305 let problems = IconSpec.problems(icon)306 guard problems.isEmpty else { throw ToolFailure("icon.invalid", problems.prefix(8).joined(separator: " ")) }307 let png: Data308 do { png = try IconRenderer.png(icon, pixels: 256) } catch { throw ToolFailure("icon.failed", error.localizedDescription) }309 var result = try mutate("Icon designed (\(icon["layers"]?.arrayValue?.count ?? 0) layers)", [.setBlueprintField(field: "icon", value: icon)])310 result.content = ["ok": true, "note": "The drawn icon is attached. Check that the motif is centred, large enough, readable at small sizes and distinct from the background; call design.setIcon again to refine it."]311 result.imagePNG = png312 return result313314 // MARK: on-demand components and scripts (ADR 0009)315 case "component.define":316 try requireCatalog()317 let bp = try need()318 let id = s("id")319 guard PrismID.isValid(id) else { throw ToolFailure("input.invalid", "`\(id)` is not a valid id (letters, digits, underscores).") }320 if let existing = bp.object(id), !existing.isComponentDefinition { throw ToolFailure("id.taken", "`\(id)` already exists and is not an on-demand component.") }321 var props: [String: JSONValue] = ["summary": .string(s("summary")), "source": .string(s("source")), "props": input["props"] ?? [], "events": input["events"] ?? []]322 if let tick = input["tick"] { props["tick"] = tick }323 if let keys = input["keys"] { props["keys"] = keys }324 let definition = PrismObject(id: id, type: ObjectType.componentDefinition, name: s("name").isEmpty ? id : s("name"), props: props, provenance: ["source": "agent", "generated": true])325 do { _ = try CustomComponent.manifest(definition) } catch { throw ToolFailure("component.invalid", error.localizedDescription) }326 if let problem = ScriptEngine.syntaxError(s("source"), asFunctionBody: true) { throw ToolFailure("script.syntax", problem) }327 // Run it once in isolation: it must load and offer render().328 let probe = ScriptEngine()329 do { try probe.define(component: id, source: s("source")) } catch { throw ToolFailure("script.failed", error.localizedDescription) }330 guard probe.has("render", component: id) else { throw ToolFailure("component.invalid", "The source must define `function render(props)`.") }331 var patches: [BlueprintPatch] = bp.object(id) == nil332 ? [.addObject(definition, parent: nil, index: nil)]333 : [.setField(id: id, field: "props", value: .object(props)), .setField(id: id, field: "name", value: .string(definition.name))]334 patches += scriptPermissionPatches(bp)335 var result = try mutate("On-demand component “\(definition.name)” defined", patches)336 result.content = ["ok": true, "type": .string(ObjectType.customPrefix + id), "next": "Test it with component.test, then place it with ui.addComponent."]337 return result338 case "component.test":339 let bp = try need()340 guard let definition = bp.object(s("id")), definition.isComponentDefinition else { throw ToolFailure("component.unknown", "There is no on-demand component `\(s("id"))`.") }341 let runtime = try startPreview(restart: true)342 let before = runtime.logs.count343 var props: [String: JSONValue] = [:]344 for spec in definition.props["props"]?.arrayValue ?? [] { if let name = spec["name"]?.stringValue { props[name] = input["props"]?[name] ?? spec["default"] ?? .null } }345 let instance = "__test_" + definition.id346 if let call = input["call"], let fn = call["function"]?.stringValue {347 runtime.callComponent(definition.id, fn, (call["args"]?.arrayValue ?? []) + [["props": .object(props)]], instance: instance)348 }349 let tree = runtime.callComponent(definition.id, "render", [.object(props)], instance: instance, readOnly: true)350 let problems = runtime.logs.dropFirst(before).filter { $0.level != .info }.map(\.message)351 let logs = runtime.logs.dropFirst(before).filter { $0.level == .info }.map(\.message)352 var report: [String: JSONValue] = ["problems": .array(problems.map(JSONValue.string)), "logs": .array(logs.suffix(20).map(JSONValue.string))]353 if let tree, tree.objectValue != nil {354 var counts: [String: Int] = [:], texts: [String] = []355 Self.walk(tree) { node in356 counts[node["type"]?.stringValue ?? "?", default: 0] += 1357 if let t = node["text"]?.displayString ?? node["title"]?.displayString, texts.count < 12 { texts.append(String(t.prefix(40))) }358 }359 let known: Set<String> = ["vstack", "hstack", "zstack", "grid", "scroll", "text", "symbol", "rect", "circle", "ellipse", "capsule", "spacer", "divider", "button", "input", "toggle", "slider", "picker", "progress", "canvas"]360 report["nodes"] = .object(counts.mapValues(JSONValue.int))361 report["sampleText"] = .array(texts.map(JSONValue.string))362 let unknown = counts.keys.filter { !known.contains($0) }.sorted()363 if !unknown.isEmpty { report["unknownNodeTypes"] = .array(unknown.map(JSONValue.string)) }364 let ok = problems.isEmpty && unknown.isEmpty365 return ToolResult(ok: ok, content: .object(report), summary: ok ? "Component renders: \(counts.values.reduce(0, +)) nodes" : "Component renders with problems")366 }367 report["rendered"] = false368 if problems.isEmpty { report["problems"] = ["render(props) did not return a view tree object."] }369 return ToolResult(ok: false, content: .object(report), summary: "Component does not render")370 case "logic.createScript":371 try requireCatalog()372 let bp = try need()373 let id = s("id")374 guard PrismID.isValid(id) else { throw ToolFailure("input.invalid", "`\(id)` is not a valid id (letters, digits, underscores).") }375 if let existing = bp.object(id), !existing.isScript { throw ToolFailure("id.taken", "`\(id)` already exists and is not a script.") }376 if let problem = ScriptEngine.syntaxError(s("source")) { throw ToolFailure("script.syntax", problem) }377 let script = PrismObject(id: id, type: ObjectType.script, name: s("name").isEmpty ? id : s("name"), props: ["source": .string(s("source"))], provenance: ["source": "agent", "generated": true])378 var patches: [BlueprintPatch] = bp.object(id) == nil ? [.addObject(script, parent: nil, index: nil)] : [.setProp(id: id, key: "source", value: .string(s("source")))]379 patches += scriptPermissionPatches(bp)380 return try mutate("Script “\(id)” saved", patches)381 case "code.run":382 let runtime = try startPreview()383 let before = runtime.logs.count384 do {385 let value = try runtime.callScript(s("function"), input["args"]?.arrayValue ?? [])386 let logs = runtime.logs.dropFirst(before).map(\.message)387 return .success(["result": allowSampleRows || value.arrayValue == nil ? value : .string("[\(value.arrayValue?.count ?? 0) items]"), "logs": .array(logs.suffix(20).map(JSONValue.string))], "`\(s("function"))` returned \(value.typeName)")388 } catch { throw ToolFailure("script.failed", error.localizedDescription) }389 case "code.read":390 let bp = try need()391 guard let o = bp.object(s("id")), o.isScript || o.isComponentDefinition else {392 throw ToolFailure("code.missing", "`\(s("id"))` is not a script or an on-demand component. Known: \((bp.scripts + bp.componentDefinitions).map(\.id).joined(separator: ", ")).")393 }394 return .success(["id": .string(o.id), "kind": .string(o.isScript ? "script" : "component"), "source": o.props["source"] ?? ""], "Read the source of \(o.id)")395 case "code.proposePatch":396 throw ToolFailure("not_available", "There is no patch tool: replace a script with logic.createScript or an on-demand component with component.define (read it first with code.read).")397 case "ui.screenshot":398 let bp = try need()399 let runtime = try startPreview()400 if let page = input["page"]?.stringValue {401 guard bp.object(page)?.isPage == true else { throw ToolFailure("page.missing", "There is no page `\(page)`.") }402 runtime.currentPage = page403 }404 guard let png = await AppSnapshot.png(runtime: runtime) else { throw ToolFailure("screenshot.failed", "The preview could not be drawn.") }405 var result = ToolResult.success(["page": .string(runtime.currentPage), "size": "900 × 620 points", "note": "The picture of the running preview is attached."], "Looked at page “\(runtime.currentPage)”")406 result.imagePNG = png407 return result408409 // MARK: runtime410 case "runtime.stop":411 preview = nil412 return .success(["running": false], "Preview stopped")413 case "runtime.logs":414 let logs = (preview?.logs ?? []).suffix(min(max(input["limit"]?.intValue ?? 30, 1), 200))415 return .success(["running": .bool(preview != nil), "logs": .array(logs.map { ["level": .string($0.level.rawValue), "message": .string($0.message)] })], "\(logs.count) log line(s)")416417 // MARK: publisher418 case "publisher.prepare", "publisher.validate":419 let bp = try need()420 let errors = issues.errors421 return .success([422 "ready": .bool(errors.isEmpty), "errors": .array(errors.map(\.json)), "displayName": .string(bp.name),423 "permissions": .array(bp.permissions.map(JSONValue.string)), "components": .array(bp.componentTypes.map(JSONValue.string)),424 "runtime": "prism-satellite (embedded; the published app does not need PRISM to be open)",425 ], errors.isEmpty ? "Ready to publish" : "Not ready: \(errors.count) error(s)")426 case "publisher.publishLocal":427 throw ToolFailure("needs_user", "Publishing installs an app on the user's Mac, so only the user can start it, from the Publish view. Tell them the app is ready to publish.")428429 // MARK: security430 case "security.requestPermission":431 let bp = try need()432 let permission = s("permission")433 if bp.permissions.contains(permission) { return .success(["granted": true], "\(permission) is already granted") }434 if Permission.unavailable.contains(permission) { throw ToolFailure("permission.unavailable", "`\(permission)` cannot be granted in this version of PRISM. Build the app without it and tell the user.") }435 guard Permission.grantable[permission] != nil else { throw ToolFailure("permission.unknown", "`\(permission)` is not a permission. Known: \(Permission.grantable.keys.sorted().joined(separator: ", ")).") }436 if let permissionHandler, await permissionHandler(permission, s("reason")) == false {437 audit("permission.deny", "User declined \(permission)", ["reason": .string(s("reason"))])438 throw ToolFailure("permission.denied", "The user declined `\(permission)`. Do not ask again; build the app without the features that need it and say so.")439 }440 if !requestedPermissions.contains(permission) { requestedPermissions.append(permission) }441 audit("permission.grant", "Granted \(permission)", ["reason": .string(s("reason"))])442 return try mutate("Permission \(permission) granted", [.setBlueprintField(field: "permissions", value: .array((bp.permissions + [permission]).map(JSONValue.string)))])443 case "security.inspectCapabilities":444 let bp = try need()445 let needed = Set(bp.components.flatMap { registry.manifest($0.type, in: bp)?.permissions ?? [] })446 return .success([447 "granted": .array(bp.permissions.map(JSONValue.string)), "neededByComponents": .array(needed.sorted().map(JSONValue.string)),448 "missing": .array(needed.subtracting(bp.permissions).sorted().map(JSONValue.string)),449 "grantable": .object(Permission.grantable.mapValues(JSONValue.string)), "unavailable": .array(Permission.unavailable.sorted().map(JSONValue.string)),450 ], "\(bp.permissions.count) permission(s) granted")451 default:452 throw ToolFailure("tool.unimplemented", "`\(spec.name)` is declared but not implemented.")453 }454 }455456 private func scriptPermissionPatches(_ bp: AppBlueprint) -> [BlueprintPatch] {457 guard !bp.permissions.contains(Permission.scripts) else { return [] }458 if !requestedPermissions.contains(Permission.scripts) { requestedPermissions.append(Permission.scripts) }459 return [.setBlueprintField(field: "permissions", value: .array((bp.permissions + [Permission.scripts]).map(JSONValue.string)))]460 }461462 static func walk(_ node: JSONValue, depth: Int = 0, _ visit: (JSONValue) -> Void) {463 guard depth < 40, node.objectValue != nil else { return }464 visit(node)465 for child in node["children"]?.arrayValue ?? [] { walk(child, depth: depth + 1, visit) }466 }467468 /// Hard rule 3: the registry is consulted before any component is placed.469 private func requireCatalog() throws {470 guard catalogConsulted || baseline != nil else {471 throw ToolFailure("catalog.first", "Query the catalog (catalog.search or catalog.inspect) before adding components.")472 }473 }474475 // MARK: Preview476477 private func startPreview(restart: Bool = false) throws -> AppRuntime {478 if let preview, !restart { return preview }479 let bp = try need()480 if let error = issues.errors.first { throw ToolFailure("blueprint.invalid", "Fix validation errors first (ui.preview lists them). First: \(error.message)") }481 do {482 let runtime = try AppRuntime(blueprint: bp, store: AppDataStore(url: nil), registry: registry)483 preview = runtime484 return runtime485 } catch { throw ToolFailure("preview.failed", error.localizedDescription) }486 }487488 /// Validates, starts the app on an in-memory database with its sample rows, and evaluates every dynamic prop and query.489 private func previewReport(restart: Bool) throws -> ToolResult {490 let bp = try need()491 let all = issues492 var report: [String: JSONValue] = [493 "errors": .array(all.errors.map(\.json)), "warnings": .array(all.warnings.map(\.json)),494 "coverage": .double((registry.coverage(of: bp) * 100).rounded() / 100), "components": .int(bp.components.count),495 "pages": .int(bp.pages.count), "tables": .int(bp.tables.count), "permissions": .array(bp.permissions.map(JSONValue.string)),496 "customComponents": .int(bp.componentDefinitions.count), "scripts": .int(bp.scripts.count),497 "themed": .bool(!bp.theme.isEmpty), "iconDesigned": .bool(bp.icon != nil),498 ]499 guard all.errors.isEmpty else {500 report["running"] = false501 return ToolResult(ok: false, content: .object(report), summary: "Preview blocked by \(all.errors.count) validation error(s)")502 }503 preview = nil504 let runtime = try startPreview(restart: true)505 for o in bp.components {506 let manifest = registry.manifest(o.type, in: bp)507 if let definition = CustomComponent.id(ofType: o.type) {508 // Draw every on-demand component once, with the props its instance gives it.509 var props: [String: JSONValue] = [:]510 for spec in bp.object(definition)?.props["props"]?.arrayValue ?? [] {511 guard let name = spec["name"]?.stringValue else { continue }512 let raw = o.props[name]513 props[name] = spec["kind"]?.stringValue == "query" && raw != nil ? .array(runtime.rows(raw).map(JSONValue.object))514 : runtime.bindingPath(raw).map { runtime.resolve(["$expr": .string("state." + $0)]) } ?? (raw.map { runtime.resolve($0) } ?? spec["default"] ?? .null)515 }516 let tree = runtime.callComponent(definition, "render", [.object(props)], instance: o.id, readOnly: true)517 if tree?.objectValue == nil { runtime.log(.error, "Component `\(o.id)` (\(o.type)): render(props) did not return a view tree.") }518 }519 for (name, value) in o.props {520 if DynamicValue(value).isDynamic { _ = runtime.resolve(value) }521 if manifest?.prop(name)?.kind == .query { _ = runtime.rows(value) }522 }523 }524 for q in bp.queries { _ = runtime.rows(q.props["query"]) }525 let problems = runtime.logs.filter { $0.level != .info }.map(\.message)526 report["running"] = true527 report["runtimeProblems"] = .array(Array(Set(problems)).sorted().map(JSONValue.string))528 let ok = problems.isEmpty529 return ToolResult(ok: ok, content: .object(report), summary: ok ? "Preview running: \(bp.components.count) components, no errors" : "Preview running with \(problems.count) runtime problem(s)")530 }531532 // MARK: Outline533534 static func outline(_ bp: AppBlueprint) -> JSONValue {535 func node(_ id: String, _ depth: Int) -> JSONValue {536 guard let o = bp.object(id), depth < 40 else { return .string(id) }537 var d: [String: JSONValue] = ["id": .string(o.id), "type": .string(o.type)]538 if !o.name.isEmpty { d["name"] = .string(o.name) }539 if !o.props.isEmpty { d["props"] = .array(o.props.keys.sorted().map(JSONValue.string)) }540 if !o.events.isEmpty { d["events"] = .array(o.events.keys.sorted().map(JSONValue.string)) }541 if !o.children.isEmpty { d["children"] = .array(o.children.map { node($0, depth + 1) }) }542 return .object(d)543 }544 return [545 "name": .string(bp.name), "summary": .string(bp.summary), "entrypoint": .string(bp.entrypoint),546 "permissions": .array(bp.permissions.map(JSONValue.string)), "state": .object(bp.state),547 "tables": .array(bp.tables.map { ["id": .string($0.id), "columns": $0.props["columns"] ?? [], "sampleRows": .int($0.props["seed"]?.arrayValue?.count ?? 0)] }),548 "queries": .array(bp.queries.map { ["id": .string($0.id), "query": $0.props["query"] ?? .null] }),549 "theme": .object(bp.theme), "iconDesigned": .bool(bp.icon != nil),550 "scripts": .array(bp.scripts.map { .string($0.id) }),551 "customComponents": .array(bp.componentDefinitions.map { ["type": .string(ObjectType.customPrefix + $0.id), "summary": $0.props["summary"] ?? "", "props": .array(($0.props["props"]?.arrayValue ?? []).compactMap { $0["name"] })] }),552 "pages": .array(bp.pages.map { node($0.id, 0) }),553 ]554 }555}556