Skip to content
Source
Sign inSign up
samwillis/jerry
Open History to see the last commit

ExplorerLanguageModel.swift

148 lines9.8 KB

1import AppKit
2import FoundationModels
3import ImageIO
4import UniformTypeIdentifiers
5import ExpeditionCore
6​
7@available(macOS 27.0, *)
8struct ExplorerLanguageModel: LanguageModel {
9 struct Configuration: Hashable, Sendable {
10 let model: String
11 let bearer: String
12 let scriptedPlan: String?
13 let sessionID: UUID
14 var reasoning = ExplorerReasoningCache()
15 static func == (lhs: Self, rhs: Self) -> Bool {
16 lhs.model == rhs.model && lhs.bearer == rhs.bearer && lhs.scriptedPlan == rhs.scriptedPlan && lhs.sessionID == rhs.sessionID
17 }
18 func hash(into hasher: inout Hasher) { hasher.combine(model); hasher.combine(bearer); hasher.combine(scriptedPlan); hasher.combine(sessionID) }
19 }
20 let executorConfiguration: Configuration
21 var capabilities: LanguageModelCapabilities { .init([.vision, .toolCalling]) }
22 typealias Executor = ExplorerModelExecutor
24​
25@available(macOS 27.0, *)
26actor ExplorerReasoningCache {
27 var turns = 0
28 var reasoning: [String: Data] = [:]
29 func nextTurn() throws -> Int { turns += 1; guard turns <= 160 else { throw AgentConnectionError(message: "The prototype stopped at its 160-turn limit.") }; return turns }
30 func save(_ data: Data, for id: String) { reasoning[id] = data }
31 func read(_ id: String) -> Data? { reasoning[id] }
33​
34/// Native Foundation Models provider. The executor runs model networking only;
35/// only validated physical computer tools can operate the desktop.
36@available(macOS 27.0, *)
37struct ExplorerModelExecutor: LanguageModelExecutor {
38 typealias Model = ExplorerLanguageModel
39 typealias Configuration = ExplorerLanguageModel.Configuration
40 private let configuration: Configuration
41 private var cache: ExplorerReasoningCache { configuration.reasoning }
42 init(configuration: Configuration) throws { self.configuration = configuration }
43​
44 func respond(to request: LanguageModelExecutorGenerationRequest, model: Model, streamingInto channel: LanguageModelExecutorGenerationChannel) async throws {
45 try Task.checkCancellation()
46 let turn = try await cache.nextTurn()
47 if let scripted = configuration.scriptedPlan {
48 // Deterministic transport check, with no external model or task planning.
49 if turn == 1 {
50 await channel.send(.toolCalls(action: .toolCall(id: "offline-inspect", name: "computer_action", action: .appendArguments(scripted, tokenCount: 0))))
51 } else {
52 await channel.send(.response(action: .appendText("Offline connection test complete. Choose ChatGPT or an API key in Settings to plan computer tasks.", tokenCount: 0)))
53 }
54 return
55 }
56 guard request.schema == nil else { throw AgentConnectionError(message: "This prototype supports text and computer tools, not guided final-response schemas.") }
57 var input: [[String: Any]] = []
58 for entry in request.transcript {
59 switch entry {
60 case .instructions(let instructions):
61 input.append(["role": "developer", "content": try contents(instructions.segments)])
62 case .prompt(let prompt):
63 input.append(["role": "user", "content": try contents(prompt.segments)])
64 case .response(let response):
65 input.append(["role": "assistant", "content": text(response.segments)])
66 case .toolCalls(let calls):
67 if let first = calls.first, let data = await cache.read(first.id), let reasoning = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] { input += reasoning }
68 for call in calls {
69 input.append(["type": "function_call", "call_id": call.id, "name": call.toolName, "namespace": "explorer", "arguments": call.arguments.jsonString])
70 }
71 case .toolOutput(let output):
72 input.append(["type": "function_call_output", "call_id": output.id, "output": try contents(output.segments)])
73 case .reasoning: break // Opaque provider reasoning is preserved with its calls.
74 default: throw AgentConnectionError(message: "The transcript contains an unsupported attachment or entry.")
75 }
76 }
77 let tools: [[String: Any]] = try request.enabledToolDefinitions.map {
78 ["type": "function", "name": $0.name, "description": $0.description, "parameters": try JSONSerialization.jsonObject(with: JSONEncoder().encode($0.parameters))]
79 }
80 let body: [String: Any] = ["model": configuration.model, "store": false, "stream": true,
81 "input": input, "include": ["reasoning.encrypted_content"],
82 "tools": [["type": "namespace", "name": "explorer", "description": "Physically embodied explorer computer tools", "tools": tools]]]
83 var http = URLRequest(url: URL(string: "https://api.openai.com/v1/responses")!)
84 http.httpMethod = "POST"; http.timeoutInterval = 90
85 http.setValue("Bearer \(configuration.bearer)", forHTTPHeaderField: "Authorization")
86 http.setValue("application/json", forHTTPHeaderField: "Content-Type")
87 http.httpBody = try JSONSerialization.data(withJSONObject: body)
88 let (bytes, response) = try await URLSession.shared.bytes(for: http)
89 guard let status = response as? HTTPURLResponse, (200..<300).contains(status.statusCode) else {
90 // Never echo remote response bodies: they can contain account details.
91 throw AgentConnectionError(message: "The model request failed (HTTP \((response as? HTTPURLResponse)?.statusCode ?? 0)). Check the selected model, connection and account eligibility.")
92 }
93 var completed = false
94 var streamedItems: [[String: Any]] = []
95 var events = ResponsesEventStream()
96 for try await line in bytes.lines {
97 try Task.checkCancellation()
98 if let data = try events.consume(line) {
99 guard let event = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { continue }
100 switch event["type"] as? String {
101 case "response.output_item.done":
102 if let item = event["item"] as? [String: Any] { streamedItems.append(item) }
103 case "response.output_text.delta":
104 if let delta = event["delta"] as? String { await channel.send(.response(action: .appendText(delta, tokenCount: 0))) }
105 case "response.completed":
106 guard let response = event["response"] as? [String: Any], let finalOutput = response["output"] as? [[String: Any]] else { throw AgentConnectionError(message: "The model returned an incomplete response.") }
107 // Some streaming hosts omit items from the terminal envelope.
108 // Preserve the completed items delivered earlier in the stream.
109 let output = finalOutput.isEmpty ? streamedItems : finalOutput
110 let calls = output.filter { $0["type"] as? String == "function_call" }
111 guard calls.count <= 1 else { throw AgentConnectionError(message: "The prototype accepts one computer tool call per turn; input actions must be sequential.") }
112 let reasoning = output.filter { $0["type"] as? String == "reasoning" }
113 for call in calls {
114 guard let id = call["call_id"] as? String, let name = call["name"] as? String,
115 request.enabledToolDefinitions.contains(where: { $0.name == name }), let arguments = call["arguments"] as? String else { throw AgentConnectionError(message: "The model requested a tool outside the prototype's scope.") }
116 await cache.save(try JSONSerialization.data(withJSONObject: reasoning), for: id)
117 await channel.send(.toolCalls(action: .toolCall(id: id, name: name, action: .appendArguments(arguments, tokenCount: 0))))
118 }
119 completed = true
120 case "error", "response.failed", "response.incomplete":
121 throw AgentConnectionError(message: "The model could not complete this request. No desktop action was performed.")
122 default: break
123 }
124 }
125 }
126 try events.finish()
127 guard completed else { throw AgentConnectionError(message: "The model stream ended before completion.") }
128 }
129 private func text(_ segments: [Transcript.Segment]) -> String {
130 segments.map { switch $0 { case .text(let t): t.content; case .structure(let s): s.content.jsonString; default: "" } }.joined(separator: "\n")
131 }
132 private func contents(_ segments: [Transcript.Segment]) throws -> [[String: Any]] {
133 try segments.map {
134 switch $0 {
135 case .text(let text): return ["type": "input_text", "text": text.content]
136 case .structure(let structure): return ["type": "input_text", "text": structure.content.jsonString]
137 case .attachment(let attachment):
138 guard case .image(let image) = attachment.content, image.orientation == .up else { throw AgentConnectionError(message: "Only upright image observations are supported in this prototype.") }
139 let data = NSMutableData()
140 guard let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil) else { throw AgentConnectionError(message: "Could not encode the screen observation.") }
141 CGImageDestinationAddImage(destination, image.cgImage, nil)
142 guard CGImageDestinationFinalize(destination) else { throw AgentConnectionError(message: "Could not encode the screen observation.") }
143 return ["type": "input_image", "image_url": "data:image/png;base64," + (data as Data).base64EncodedString()]
144 @unknown default: throw AgentConnectionError(message: "Unsupported observation content.")
145 }
146 }
147 }