import Foundation import OSLog /// Chats through the user's own installed Claude Code (`claude -p`), signed in by them with their /// Claude plan. Seer never reads, stores or forwards the login: it only launches the unmodified /// binary, which authenticates itself. Meant for personal use on the user's own Mac. final class ClaudeCodeProvider: ModelProvider, @unchecked Sendable { let displayName = "Claude Code" private let executable: URL /// Lets Claude Code use its own WebSearch and WebFetch tools. private let webAccess: Bool init(executable: URL, webAccess: Bool) { self.executable = executable self.webAccess = webAccess } // MARK: - Detection /// Where the `claude` binary is, if Claude Code is installed. Looked up once. static let installedPath: URL? = CLIProcess.find("claude", extra: [ "\(NSHomeDirectory())/.claude/local/claude", "\(NSHomeDirectory())/.bun/bin/claude", ]) static var isInstalled: Bool { installedPath != nil } // MARK: - Streaming func stream(messages: [APIMessage], model: String, tools: [ChatTool]) async throws -> AsyncThrowingStream { Logger.api.info("Claude Code 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) var content: [[String: Any]] = images.map { ["type": "image", "source": ["type": "base64", "media_type": "image/jpeg", "data": $0.base64EncodedString()]] } content.append(["type": "text", "text": prompt]) let input = try JSONSerialization.data(withJSONObject: [ "type": "user", "message": ["role": "user", "content": content], ] as [String: Any]) + Data("\n".utf8) let process = Process() process.executableURL = executable var args = [ "-p", "--output-format", "stream-json", "--input-format", "stream-json", "--include-partial-messages", "--verbose", ] + (webAccess ? ["--tools", "WebSearch,WebFetch", "--allowedTools", "WebSearch", "WebFetch"] : ["--tools", ""] // Seer's own tools are described in the prompt instead ) + [ "--no-session-persistence", "--disable-slash-commands", "--strict-mcp-config", "--setting-sources", "", "--system-prompt", system, ] let trimmed = model.trimmingCharacters(in: .whitespaces) if !trimmed.isEmpty { args += ["--model", trimmed] } process.arguments = args // A neutral folder, so nothing in the user's projects is picked up as context. process.currentDirectoryURL = FileManager.default.temporaryDirectory // An API key in the environment would silently replace the Claude plan login. process.environment = CLIProcess.environment(executable: executable, removing: ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"]) let stdin = Pipe(), stdout = Pipe(), stderr = Pipe() process.standardInput = stdin process.standardOutput = stdout process.standardError = stderr try process.run() stdin.fileHandleForWriting.write(input) try? stdin.fileHandleForWriting.close() let wantsTools = !tools.isEmpty return AsyncThrowingStream { cont in let task = Task { 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 "stream_event": if let event = object["event"] as? [String: Any], event["type"] as? String == "message_start", sawText { cont.yield(.text(" ")) // text after a tool round continues the answer } if let event = object["event"] as? [String: Any], event["type"] as? String == "content_block_delta", let delta = event["delta"] as? [String: Any], delta["type"] as? String == "text_delta", let token = delta["text"] as? String { let visible = filter.feed(token) if !visible.isEmpty { sawText = true; cont.yield(.text(visible)) } } case "result": if object["is_error"] as? Bool == true { failure = (object["result"] as? String) ?? "Claude Code 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(failure) } else if !sawText && calls.isEmpty { let err = String(decoding: stderr.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) .trimmingCharacters(in: .whitespacesAndNewlines) throw ProviderError.decodingError(err.isEmpty ? "Claude Code returned nothing. Is it signed in? Run `claude` in a terminal and use /login." : String(err.prefix(300))) } Logger.api.info("Claude Code stream finished") cont.finish() } catch { Logger.api.error("Claude Code error: \(error, privacy: .public)") cont.finish(throwing: error) } } cont.onTermination = { _ in task.cancel() if process.isRunning { process.terminate() } } } } }