SPB Git

Repository Public License

ToolProtocol.swift 16.9 KB 168 lines swift

1import Foundation2import PrismCore34/// A typed tool of the builder agent (spec §9): schema, scope, authorization, structured errors, audit, dry run.5public struct ToolSpec: Sendable, Identifiable {6    public var name: String7    public var summary: String8    public var inputSchema: JSONValue9    /// What the tool may touch: `catalog` (read-only), `draft` (the working blueprint), `preview` (throwaway runtime),10    /// `project` (saved state), `system` (outside the project; always needs the user's confirmation).11    public var scope: String12    public var mutating: Bool13    public var requiresConfirmation: Bool1415    public var id: String { name }16    /// The Messages API only allows `[a-zA-Z0-9_-]` in tool names.17    public var wireName: String { name.replacingOccurrences(of: ".", with: "_") }1819    public init(_ name: String, _ summary: String, scope: String, mutating: Bool = false, requiresConfirmation: Bool = false, properties: [String: JSONValue] = [:], required: [String] = []) {20        self.name = name; self.summary = summary; self.scope = scope; self.mutating = mutating; self.requiresConfirmation = requiresConfirmation21        self.inputSchema = ["type": "object", "properties": .object(properties), "required": .array(required.map(JSONValue.string)), "additionalProperties": false]22    }2324    /// The definition sent to the API. `eager_input_streaming` is on because requests are streamed;25    /// inputs are therefore validated here before any tool runs.26    public var apiDefinition: JSONValue {27        ["name": .string(wireName), "description": .string(summary), "input_schema": inputSchema, "eager_input_streaming": true]28    }29}3031public struct ToolResult: Sendable, Equatable {32    public var ok: Bool33    public var content: JSONValue34    public var summary: String35    /// A picture returned to the model with the result (a drawn icon, a screenshot of the preview).36    public var imagePNG: Data? = nil3738    public static func success(_ content: JSONValue, _ summary: String) -> ToolResult { .init(ok: true, content: content, summary: summary) }3940    /// Structured error: a stable `code`, a message the model can act on, optional details.41    public static func failure(_ code: String, _ message: String, details: JSONValue? = nil) -> ToolResult {42        var o: [String: JSONValue] = ["error": ["code": .string(code), "message": .string(message)]]43        if let details { o["details"] = details }44        return .init(ok: false, content: .object(o), summary: message)45    }4647    public var errorCode: String? { content["error"]?["code"]?.stringValue }48}4950/// A small JSON Schema checker covering what the tool schemas use: type, properties, required, enum, items, additionalProperties.51public enum SchemaValidator {52    public static func problems(_ value: JSONValue, schema: JSONValue, path: String = "input") -> [String] {53        var out: [String] = []54        if let allowed = schema["enum"]?.arrayValue, !allowed.contains(value) {55            out.append("\(path) must be one of \(allowed.map(\.displayString).joined(separator: ", ")).")56        }57        guard let type = schema["type"]?.stringValue else { return out }58        switch type {59        case "object":60            guard let o = value.objectValue else { return out + ["\(path) must be an object, not \(value.typeName)."] }61            let props = schema["properties"]?.objectValue ?? [:]62            for r in schema["required"]?.arrayValue ?? [] { if let k = r.stringValue, o[k] == nil { out.append("\(path).\(k) is required.") } }63            for (k, v) in o.sorted(by: { $0.key < $1.key }) {64                if let sub = props[k] { out += problems(v, schema: sub, path: "\(path).\(k)") }65                else if schema["additionalProperties"]?.boolValue == false { out.append("\(path).\(k) is not a known field. Known: \(props.keys.sorted().joined(separator: ", ")).") }66            }67        case "array":68            guard let a = value.arrayValue else { return out + ["\(path) must be an array, not \(value.typeName)."] }69            if let items = schema["items"] { for (i, v) in a.enumerated().prefix(200) { out += problems(v, schema: items, path: "\(path)[\(i)]") } }70        case "string": if value.stringValue == nil { out.append("\(path) must be a string, not \(value.typeName).") }71        case "integer": if value.intValue == nil { out.append("\(path) must be a whole number, not \(value.typeName).") }72        case "number": if value.doubleValue == nil { out.append("\(path) must be a number, not \(value.typeName).") }73        case "boolean": if value.boolValue == nil { out.append("\(path) must be true or false, not \(value.typeName).") }74        default: break75        }76        return out77    }78}7980public enum ToolCatalog {81    private static let str: JSONValue = ["type": "string"]82    private static let obj: JSONValue = ["type": "object"]83    private static func arr(_ items: JSONValue) -> JSONValue { ["type": "array", "items": items] }84    private static func described(_ type: String, _ text: String) -> JSONValue { ["type": .string(type), "description": .string(text)] }8586    public static let all: [ToolSpec] = [87        ToolSpec("catalog.search", "Search the component catalog by what you need (e.g. 'monthly chart', 'csv import'). Always search before adding components.", scope: "catalog",88                 properties: ["query": described("string", "Words describing the need; empty lists everything."),89                              "category": ["type": "string", "description": "One catalog category, e.g. foundation, forms, input, data, charts, navigation, layout, display, text, feedback, productivity, time, commerce, social, logic."], "limit": ["type": "integer"]], required: ["query"]),90        ToolSpec("catalog.inspect", "Full contract of one component: props (kind, required, bindable), events, permissions.", scope: "catalog", properties: ["type": str], required: ["type"]),91        ToolSpec("catalog.examples", "Copyable example objects for one component.", scope: "catalog", properties: ["type": str], required: ["type"]),9293        ToolSpec("project.create", "Start the app: name, one-line summary, and the typed intent (features and acceptance criteria) you derived from the request.", scope: "draft", mutating: true,94                 properties: ["name": str, "summary": str, "features": arr(str), "acceptanceCriteria": arr(str)], required: ["name", "summary", "acceptanceCriteria"]),95        ToolSpec("project.read", "Read the working app: an outline (pages, component tree, tables, queries, state, permissions), or one object in full when `objectId` is given.", scope: "draft", properties: ["objectId": str]),96        ToolSpec("project.patch", "Apply low-level blueprint patches in order. Ops: addObject, removeObject, setProp, removeProp, setField, setEvent, moveChild, setBlueprintField. Prefer the ui.* and data.* tools; use this to remove or move things.", scope: "draft", mutating: true,97                 properties: ["patches": arr(obj)], required: ["patches"]),98        ToolSpec("project.snapshot", "Save a named checkpoint of the working app that project.rollback can return to.", scope: "draft", mutating: true, properties: ["label": str], required: ["label"]),99        ToolSpec("project.rollback", "Return the working app to a checkpoint made with project.snapshot.", scope: "draft", mutating: true, properties: ["label": str], required: ["label"]),100101        ToolSpec("ui.createPage", "Add a page. The first page becomes the entry page. Multiple pages get a navigation sidebar automatically.", scope: "draft", mutating: true,102                 properties: ["id": str, "name": str, "icon": described("string", "SF Symbol name.")], required: ["id", "name"]),103        ToolSpec("ui.addComponent", "Add a catalog component under a parent (a page or a container). Props use literals, {\"$expr\": \"…\"} for computed values, {\"$bind\": \"stateKey\"} for two-way state.", scope: "draft", mutating: true,104                 properties: ["parent": str, "id": str, "type": str, "name": described("string", "Human name; also the tab or sidebar title when placed in tabs or a sidebar."),105                              "props": obj, "events": described("object", "Event name → list of actions."), "index": ["type": "integer"]], required: ["parent", "id", "type"]),106        ToolSpec("ui.setProperties", "Set and/or remove props on an existing component.", scope: "draft", mutating: true,107                 properties: ["id": str, "props": obj, "remove": arr(str), "name": str], required: ["id"]),108        ToolSpec("ui.connectAction", "Replace the actions run by one event of a component. Actions: setState, toggleState, navigate, createRecord, updateRecord, deleteRecord, importCSV, exportCSV, showNotification, validate, when.", scope: "draft", mutating: true,109                 properties: ["id": str, "event": str, "actions": arr(obj)], required: ["id", "event", "actions"]),110        ToolSpec("ui.preview", "Validate the whole app and start it in a throwaway preview: every expression and query is evaluated against sample data. Returns errors to fix, warnings, and catalog coverage. Call it before you finish.", scope: "preview"),111112        ToolSpec("data.createSchema", "Define (or replace the definition of) a data table. Every table gets an `id` column automatically. Column types: text, number, integer, currency, date, boolean.", scope: "draft", mutating: true,113                 properties: ["id": described("string", "Table id, used as `table` in queries."), "name": str,114                              "columns": arr(["type": "object", "properties": ["name": str, "type": ["type": "string", "enum": ["text", "number", "integer", "currency", "date", "boolean"]], "label": str,115                                              "required": ["type": "boolean"], "options": arr(str), "default": [:]], "required": ["name", "type"], "additionalProperties": false]),116                              "seed": described("array", "Optional sample rows inserted when the table is first created.")], required: ["id", "columns"]),117        ToolSpec("data.import", "Set the sample rows of a table (used when the table is first created, and in previews).", scope: "draft", mutating: true,118                 properties: ["table": str, "rows": arr(obj)], required: ["table", "rows"]),119        ToolSpec("data.query", "Run a declarative query against the preview data to check it. Returns the SQL-free result shape: columns and row count (and sample rows only if the user allowed it).", scope: "preview",120                 properties: ["query": obj], required: ["query"]),121        ToolSpec("data.migrate", "Show what the working app would change in the user's existing database: tables created, columns added, and what is kept. Nothing is ever dropped.", scope: "project"),122123        ToolSpec("logic.createWorkflow", "Create a named, reusable query that expressions read as `queries.<id>` (a list of rows), e.g. a monthly total used by an alert.", scope: "draft", mutating: true,124                 properties: ["id": str, "name": str, "query": obj], required: ["id", "query"]),125        ToolSpec("logic.bind", "Declare app state keys with their initial values. Every `$bind` and every `state.x` must be declared here first.", scope: "draft", mutating: true,126                 properties: ["state": obj], required: ["state"]),127        ToolSpec("logic.validate", "Check an expression: syntax, known functions and names, and its value in the current preview.", scope: "preview", properties: ["expression": str], required: ["expression"]),128129        ToolSpec("design.listThemes", "List the theme presets and every theme token (palette, fonts, surfaces, gradients, chart colors).", scope: "catalog"),130        ToolSpec("design.setTheme", "Give the app its look. Pass a preset name and/or explicit tokens; explicit tokens win. Replaces the current theme. Contrast is checked.", scope: "draft", mutating: true,131                 properties: ["theme": described("object", "e.g. {\"preset\": \"midnight\", \"accent\": \"#5AC8FA\"} or a fully custom {accent, font, headingFont, headingWeight, surface, radius, density, palette: {background, surface, text, border}, backgroundGradient, chartColors}.")], required: ["theme"]),132        ToolSpec("design.setIcon", "Design the app's icon. You get the drawn icon back as an image: look at it and call again to refine it. Canvas is 100×100, y down; layers are painted in order.", scope: "draft", mutating: true,133                 properties: ["icon": described("object", "{background: {colors: [1-4 hex], style: linear|radial|mesh|solid, angle, pattern: none|dots|grid|rays|rings}, layers: [up to 12 of {symbol: SF Symbol name} | {path: SVG path data} | {shape: circle|ring|roundedRect|capsule|diamond|star|hexagon} | {text: 1-4 chars}, each with fill (hex or {colors, angle}), stroke, strokeWidth, x, y, size (or width/height), rotation, opacity, shadow, blend], finish: glass|matte|flat}")], required: ["icon"]),134135        ToolSpec("component.define", "Create (or replace) an on-demand component for this app when no catalog component fits. `source` is JavaScript defining render(props) that returns a view tree; use it afterwards with ui.addComponent and type `custom.<id>`. Search the catalog first.", scope: "draft", mutating: true,136                 properties: ["id": str, "name": str, "summary": str,137                              "props": described("array", "Declared props, like catalog props: {name, kind: string|number|boolean|enum|list|object|query|any, summary, required?, default?, values?, binding?: none|optional|required}."),138                              "events": arr(str), "source": str,139                              "tick": described("number", "Optional: call tick(props) every this many seconds."),140                              "keys": described("boolean", "Optional: receive key presses in key(event).")], required: ["id", "summary", "source"]),141        ToolSpec("component.test", "Render an on-demand component in the preview with the given props, optionally after calling one of its functions. Returns the view tree summary and any script error.", scope: "preview",142                 properties: ["id": str, "props": obj, "call": described("object", "Optional {function, args} to run first, as an event handler would.")], required: ["id"]),143        ToolSpec("logic.createScript", "Create (or replace) a global JavaScript script. Its top-level functions are called by `runScript` actions ({type: \"runScript\", function, args}) and by the expression function js('name', …). Use only for logic that actions and expressions cannot express.", scope: "draft", mutating: true,144                 properties: ["id": str, "name": str, "source": str], required: ["id", "source"]),145        ToolSpec("code.run", "Call a function of the app's global scripts in the preview and get its result and log lines.", scope: "preview",146                 properties: ["function": str, "args": ["type": "array"]], required: ["function"]),147        ToolSpec("code.read", "Read the JavaScript source of a script or an on-demand component of this app.", scope: "draft", properties: ["id": str], required: ["id"]),148        ToolSpec("code.proposePatch", "Not available: replace a script with logic.createScript or a component with component.define.", scope: "draft", properties: ["path": str, "patch": str]),149        ToolSpec("ui.screenshot", "Look at the app: returns a picture of one page of the running preview (the entry page by default). Use it to check layout and looks after ui.preview passes.", scope: "preview", properties: ["page": str]),150        ToolSpec("code.runTests", "Run the app's checks: validation plus a preview run. Same result as ui.preview, reported as pass/fail per check.", scope: "preview"),151        ToolSpec("code.lint", "List warnings (accessibility, unused objects, missing labels) for the working app.", scope: "preview"),152153        ToolSpec("runtime.start", "Start (or restart) the throwaway preview of the working app.", scope: "preview"),154        ToolSpec("runtime.stop", "Stop the preview.", scope: "preview"),155        ToolSpec("runtime.logs", "Recent log lines of the preview: failed expressions, failed queries, notices.", scope: "preview", properties: ["limit": ["type": "integer"]]),156157        ToolSpec("publisher.prepare", "Describe what publishing this app as a desktop satellite would produce: bundle id, name, permissions, components.", scope: "project"),158        ToolSpec("publisher.validate", "Check that the app is ready to publish.", scope: "project"),159        ToolSpec("publisher.publishLocal", "Publish as a desktop app. Always needs the user's approval in the Publish view; the agent can only request it.", scope: "system", mutating: true, requiresConfirmation: true),160161        ToolSpec("security.requestPermission", "Ask the user to grant the app a permission, with the reason. The user decides.", scope: "system", mutating: true, requiresConfirmation: true,162                 properties: ["permission": str, "reason": str], required: ["permission", "reason"]),163        ToolSpec("security.inspectCapabilities", "List the permissions the app holds, the ones its components need, and the ones that exist.", scope: "draft"),164    ]165166    public static func spec(wireName: String) -> ToolSpec? { all.first { $0.wireName == wireName || $0.name == wireName } }167}168
Files main
Menu

Theme