Repository Public License
1import Foundation2import PrismComponentCatalog3import PrismCore4import PrismObjectModel5import PrismSecurity6import PrismAIOrchestrator7import PrismRenderer89/// A scripted Anthropic API: each request gets the next canned response. Requests are recorded for assertions.10public final class ScriptedTransport: HTTPTransport, @unchecked Sendable {11 public enum Reply: Sendable {12 case sse([String])13 case json(Int, String, headers: [String: String] = [:])14 case fail(URLError.Code)15 /// Streams the given lines, then waits until cancelled.16 case hang([String])17 }1819 private let lock = NSLock()20 private var replies: [Reply]21 public private(set) var requests: [URLRequest] = []2223 public init(_ replies: [Reply]) { self.replies = replies }2425 /// Adds more canned responses to the end of the script.26 public func append(_ more: [Reply]) { lock.withLock { replies += more } }2728 public var bodies: [JSONValue] { lock.withLock { requests.compactMap { $0.httpBody.flatMap { try? JSONValue.parse($0) } } } }29 public var count: Int { lock.withLock { requests.count } }3031 public func send(_ request: URLRequest) async throws -> (HTTPResponseHead, AsyncThrowingStream<String, Error>) {32 let reply: Reply? = lock.withLock {33 requests.append(request)34 return replies.isEmpty ? nil : replies.removeFirst()35 }36 guard let reply else { return (HTTPResponseHead(status: 500), lines(["{\"error\":{\"message\":\"script exhausted\"}}"])) }37 switch reply {38 case .sse(let l): return (HTTPResponseHead(status: 200, headers: ["request-id": "req_test_\(count)"]), lines(l))39 case .json(let status, let body, let headers): return (HTTPResponseHead(status: status, headers: headers), lines([body]))40 case .fail(let code): throw URLError(code)41 case .hang(let l):42 return (HTTPResponseHead(status: 200), AsyncThrowingStream { c in43 let task = Task {44 for x in l { c.yield(x) }45 do { try await Task.sleep(for: .seconds(60)); c.finish() } catch { c.finish(throwing: CancellationError()) }46 }47 c.onTermination = { _ in task.cancel() }48 })49 }50 }5152 private func lines(_ l: [String]) -> AsyncThrowingStream<String, Error> {53 AsyncThrowingStream { c in for x in l { c.yield(x) }; c.finish() }54 }55}5657/// Builds the SSE lines of one assistant turn in the documented event format.58public enum SSE {59 public enum Block {60 case text(String)61 case tool(String, JSONValue)62 case rawTool(String, String)63 case thinking(String, signature: String)64 }6566 public static func turn(_ blocks: [Block], stop: String = "tool_use", input: Int = 1000, output: Int = 200, cacheRead: Int = 0, cacheWrite: Int = 0, model: String = "claude-opus-5-5") -> [String] {67 func data(_ v: JSONValue) -> String { "data: " + v.canonicalString() }68 var out: [String] = ["event: message_start", data(["type": "message_start", "message": [69 "id": "msg_test", "type": "message", "role": "assistant", "model": .string(model), "content": [],70 "usage": ["input_tokens": .int(input), "output_tokens": 1, "cache_read_input_tokens": .int(cacheRead), "cache_creation_input_tokens": .int(cacheWrite)],71 ]])]72 for (i, block) in blocks.enumerated() {73 switch block {74 case .text(let t):75 out.append(data(["type": "content_block_start", "index": .int(i), "content_block": ["type": "text", "text": ""]]))76 let mid = t.index(t.startIndex, offsetBy: t.count / 2)77 for part in [String(t[..<mid]), String(t[mid...])] where !part.isEmpty {78 out.append(data(["type": "content_block_delta", "index": .int(i), "delta": ["type": "text_delta", "text": .string(part)]]))79 }80 case .tool(let name, let input):81 out.append(data(["type": "content_block_start", "index": .int(i), "content_block": ["type": "tool_use", "id": .string("toolu_\(i)_\(name)"), "name": .string(name), "input": [:]]]))82 let json = input.canonicalString()83 let mid = json.index(json.startIndex, offsetBy: json.count / 2)84 for part in [String(json[..<mid]), String(json[mid...])] {85 out.append(data(["type": "content_block_delta", "index": .int(i), "delta": ["type": "input_json_delta", "partial_json": .string(part)]]))86 }87 case .rawTool(let name, let raw):88 out.append(data(["type": "content_block_start", "index": .int(i), "content_block": ["type": "tool_use", "id": .string("toolu_\(i)_\(name)"), "name": .string(name), "input": [:]]]))89 out.append(data(["type": "content_block_delta", "index": .int(i), "delta": ["type": "input_json_delta", "partial_json": .string(raw)]]))90 case .thinking(let t, let signature):91 out.append(data(["type": "content_block_start", "index": .int(i), "content_block": ["type": "thinking", "thinking": "", "signature": ""]]))92 out.append(data(["type": "content_block_delta", "index": .int(i), "delta": ["type": "thinking_delta", "thinking": .string(t)]]))93 out.append(data(["type": "content_block_delta", "index": .int(i), "delta": ["type": "signature_delta", "signature": .string(signature)]]))94 }95 out.append(data(["type": "content_block_stop", "index": .int(i)]))96 }97 out.append(data(["type": "message_delta", "delta": ["stop_reason": .string(stop)], "usage": ["output_tokens": .int(output)]]))98 out += ["event: message_stop", data(["type": "message_stop"])]99 return out100 }101}102103public let testKey = "sk-ant-api03-TESTKEYTESTKEYTESTKEYTESTKEY"104105public func makeClient(_ transport: ScriptedTransport, key: String? = testKey, log: @escaping @Sendable (String) -> Void = { _ in }) -> AnthropicClient {106 var config = ClaudeConfiguration()107 config.retryBaseDelay = 0108 return AnthropicClient(transport: transport, secrets: InMemorySecretStore(key.map { [SecretAccount.anthropicAPIKey: $0] } ?? [:]), configuration: config, log: log)109}110111public let testRepoRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()112113public func templateBlueprint() throws -> AppBlueprint {114 try AppBlueprint.load(Data(contentsOf: testRepoRoot.appendingPathComponent("templates/expense-tracker/blueprint.json")))115}116117/// The tool calls a model would make to build the hand-written expense tracker, derived from the template itself.118public func toolCallsBuilding(_ bp: AppBlueprint) -> [(String, JSONValue)] {119 var calls: [(String, JSONValue)] = [120 ("project_create", ["name": .string(bp.name), "summary": .string(bp.summary), "features": ["CSV import", "category filter", "monthly chart", "persistent storage"],121 "acceptanceCriteria": ["A CSV file can be imported", "Transactions can be filtered by category", "A chart shows spending per month", "Data is kept between launches"]]),122 ("catalog_search", ["query": "csv import"]), ("catalog_search", ["query": "category filter"]), ("catalog_search", ["query": "monthly chart"]),123 ("catalog_inspect", ["type": "prism.table"]),124 ]125 for t in bp.tables { calls.append(("data_createSchema", ["id": .string(t.id), "name": .string(t.name), "columns": t.props["columns"] ?? []])) }126 calls.append(("logic_bind", ["state": .object(bp.state)]))127 for p in ["files.import.userSelected", "files.export.userSelected"] { calls.append(("security_requestPermission", ["permission": .string(p), "reason": "Import and export transactions as CSV files you choose."])) }128 for q in bp.queries { calls.append(("logic_createWorkflow", ["id": .string(q.id), "name": .string(q.name), "query": q.props["query"] ?? .null])) }129 func add(_ id: String, parent: String) {130 guard let o = bp.object(id) else { return }131 var input: [String: JSONValue] = ["parent": .string(parent), "id": .string(o.id), "type": .string(o.type), "name": .string(o.name), "props": .object(o.props)]132 if !o.events.isEmpty { input["events"] = .object(o.events.mapValues(JSONValue.array)) }133 calls.append(("ui_addComponent", .object(input)))134 o.children.forEach { add($0, parent: o.id) }135 }136 for page in bp.pages {137 calls.append(("ui_createPage", ["id": .string(page.id), "name": .string(page.name)]))138 page.children.forEach { add($0, parent: page.id) }139 }140 calls.append(("ui_preview", [:]))141 return calls142}143144/// Groups tool calls into assistant turns of `size` parallel calls, then a closing text turn.145public func script(_ calls: [(String, JSONValue)], perTurn size: Int = 6, closing: String = "Your expense tracker is ready.") -> [ScriptedTransport.Reply] {146 var replies: [ScriptedTransport.Reply] = []147 var i = 0148 while i < calls.count {149 let chunk = calls[i..<min(i + size, calls.count)]150 replies.append(.sse(SSE.turn([.text("Working.")] + chunk.map { .tool($0.0, $0.1) }, cacheRead: i == 0 ? 0 : 3000, cacheWrite: i == 0 ? 3000 : 0)))151 i += size152 }153 replies.append(.sse(SSE.turn([.text(closing)], stop: "end_turn")))154 return replies155}156157/// The tool calls for golden-journey step 6: "Add a budget alert and a new chart."158public let budgetAlertAndChartCalls: [(String, JSONValue)] = [159 ("project_read", [:]),160 ("catalog_search", ["query": "budget alert"]),161 ("catalog_search", ["query": "chart by category"]),162 ("logic_bind", ["state": ["budget": 1500]]),163 ("ui_addComponent", ["parent": "bar", "id": "budget_field", "type": "prism.currencyField", "name": "Monthly budget", "index": 2,164 "props": ["label": "Monthly budget", "value": ["$bind": "budget"]]]),165 ("ui_addComponent", ["parent": "root", "id": "budget_alert", "type": "prism.alert", "name": "Budget alert", "index": 1, "props": [166 "title": "Over budget this month", "tone": "danger", "visible": ["$expr": "sum(queries.q_this_month, 'total') > state.budget"],167 "message": ["$expr": "concat('Spent ', formatCurrency(sum(queries.q_this_month, 'total')), ' of ', formatCurrency(state.budget))"],168 ]]),169 ("ui_addComponent", ["parent": "root", "id": "category_chart", "type": "prism.chart.pie", "name": "Spending by category", "props": [170 "title": "By category", "label": "category", "value": "total", "format": "currency", "height": 260,171 "query": ["table": "transactions", "groupBy": ["column": "category", "as": "category"], "aggregates": [["fn": "sum", "column": "amount", "as": "total"]]],172 ]]),173 ("ui_preview", [:]),174]175176/// File dialogs that answer from a script instead of showing panels.177@MainActor178public final class ScriptedDialogs: FileDialogs {179 public var open: URL?180 public var save: URL?181 public private(set) var askedExtensions: [[String]] = []182 public init() {}183 public func chooseFileToOpen(allowedExtensions: [String]) -> URL? { askedExtensions.append(allowedExtensions); return open }184 public func chooseFileToSave(suggestedName: String) -> URL? { save }185}186187public let modelListJSON = #"{"data":[{"id":"claude-opus-5-5","display_name":"Claude Opus 5.5","max_input_tokens":1000000,"max_tokens":128000},{"id":"claude-haiku-5-5","display_name":"Claude Haiku 5.5"}],"has_more":false}"#188