import Foundation import OSLog /// Chats through the user's own installed OpenAI Codex CLI (`codex exec`), signed in by them with their /// ChatGPT plan. Seer never reads, stores or forwards the login. Meant for personal use on the user's own Mac. /// Codex reports whole messages rather than token streams, so a reply appears all at once. final class CodexProvider: ModelProvider, @unchecked Sendable { let displayName = "Codex" private let executable: URL /// Lets Codex use its own live web search. private let webAccess: Bool init(executable: URL, webAccess: Bool) { self.executable = executable self.webAccess = webAccess } static let installedPath: URL? = CLIProcess.find("codex") static var isInstalled: Bool { installedPath != nil } func stream(messages: [APIMessage], model: String, tools: [ChatTool]) async throws -> AsyncThrowingStream { Logger.api.info("Codex request — model=\(model, privacy: .public) messages=\(messages.count, privacy: .public) tools=\(tools.count, privacy: .public)") let (system, prompt, images) = CLIPrompt.flatten(messages: messages, tools: tools) // Codex has no system-prompt flag, so the instructions lead the prompt. let fullPrompt = "Instructions (follow them for every reply):\n\(system)\n\n\(prompt)" // Codex takes images as files. let workDir = FileManager.default.temporaryDirectory.appendingPathComponent("seer-codex-\(UUID().uuidString)") try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true) var imagePaths: [String] = [] for (i, data) in images.enumerated() { let url = workDir.appendingPathComponent("image\(i).jpg") try data.write(to: url) imagePaths.append(url.path) } var args = [ "exec", "--json", "--skip-git-repo-check", "--ephemeral", "--ignore-user-config", "--ignore-rules", "-s", "read-only", "--disable", "shell_tool", // answers only: no running commands "--disable", "apps", "-c", "web_search=\"\(webAccess ? "live" : "disabled")\"", "-c", "model_reasoning_effort=\"low\"", "-C", workDir.path, ] let trimmed = model.trimmingCharacters(in: .whitespaces) if !trimmed.isEmpty { args += ["-m", trimmed] } for path in imagePaths { args += ["-i", path] } args.append("-") // prompt from stdin let process = Process() process.executableURL = executable process.arguments = args process.currentDirectoryURL = workDir // An API key in the environment would replace the ChatGPT plan login. process.environment = CLIProcess.environment(executable: executable, removing: ["OPENAI_API_KEY", "CODEX_API_KEY"]) let stdin = Pipe(), stdout = Pipe(), stderr = Pipe() process.standardInput = stdin process.standardOutput = stdout process.standardError = stderr try process.run() stdin.fileHandleForWriting.write(Data(fullPrompt.utf8)) try? stdin.fileHandleForWriting.close() let wantsTools = !tools.isEmpty return AsyncThrowingStream { cont in let task = Task { defer { try? FileManager.default.removeItem(at: workDir) } var filter = InlineToolCallFilter() var sawText = false var failure: String? do { for try await line in stdout.fileHandleForReading.bytes.lines { guard let data = line.data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { continue } switch object["type"] as? String { case "item.completed": if let item = object["item"] as? [String: Any], item["type"] as? String == "agent_message", let text = item["text"] as? String, !text.isEmpty { let visible = filter.feed(sawText ? " " + text : text) if !visible.isEmpty { sawText = true; cont.yield(.text(visible)) } } case "turn.failed", "error": failure = (object["message"] as? String) ?? ((object["error"] as? [String: Any])?["message"] as? String) ?? "Codex reported an error." default: break } } let (rest, calls) = filter.finish() if !rest.isEmpty { sawText = true; cont.yield(.text(rest)) } if wantsTools { for call in calls { cont.yield(.toolCall(call)) } } process.waitUntilExit() if let failure { throw ProviderError.decodingError(String(failure.prefix(300))) } else if !sawText && calls.isEmpty { let err = String(decoding: stderr.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) .trimmingCharacters(in: .whitespacesAndNewlines) throw ProviderError.decodingError(err.isEmpty ? "Codex returned nothing. Is it signed in? Run `codex login` in a terminal." : String(err.suffix(300))) } Logger.api.info("Codex stream finished") cont.finish() } catch { Logger.api.error("Codex error: \(error, privacy: .public)") cont.finish(throwing: error) } } cont.onTermination = { _ in task.cancel() if process.isRunning { process.terminate() } } } } }