Something went wrong. Try again.
A small AI buddy that lives in the bottom right-hand corner of your Mac that wakes when you press a keybind.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377import AppKitimport OSLog
/// Carries out a task on the user's Mac. Each step reads the screen through Accessibility,/// asks a decision model (Jev-style: typed choices with probabilities, no text generation)/// what to do next, and does it. The chat model is used only to write free text to type.actor ComputerUseAgent { private let decisions: DecisionClient private let writer: ModelProvider private let writerModel: String private let approve: ApprovalHandler /// Tasks the user taught Seer that this goal calls for. private let lessons: [Lesson]
private static let maxSteps = 30 private static let timeLimit: TimeInterval = 180 /// Below this, a decision counts as unsure and the agent observes again instead of acting. private static let minProbability = 0.35 /// The separate "is the goal accomplished?" check that ends the task. Decision models are /// steadier at this yes/no judgment than at ranking DONE among the operations. private static let minDone = 0.6 /// A DONE operation chosen at least this confidently ends the task without the separate check. private static let minDoneVote = 0.6 /// Sending, deleting, buying and the like need the goal to clearly ask for it. private static let minAuthorization = 0.8
init(decisions: DecisionClient, writer: ModelProvider, writerModel: String, approve: @escaping ApprovalHandler, lessons: [Lesson] = []) { self.decisions = decisions self.writer = writer self.writerModel = writerModel self.approve = approve self.lessons = lessons }
private enum Operation: String, CaseIterable { case click, typeText, pressKey, scroll, openApp, WAIT, DONE, BLOCKED }
private var history: [String] = []
/// What a run ended with: a plain-text report for the chat model, and whether the goal was reached. struct Report: Sendable { let text: String let completed: Bool }
/// Runs the task and returns a report for the chat model. func run(task goal: String) async -> Report { Logger.computer.info("Computer use started — task=\(goal, privacy: .public)") history = [] let started = Date() let apps = AppCatalog.apps(relevantTo: goal, limit: decisions.nounOnly ? 60 : 200) var unsure = 0, waits = 0 var lastAction: (description: String, signature: String)? var repeats = 0 var observation: Observation? /// The last text typed; a field already holding it must not be filled again (result /// pages keep the query in a focused search box, which otherwise invites retyping and reloading). var lastTyped: String? /// Operations ruled out for the next decision only, because they would just repeat work. var excluded: Set<Operation> = []
func report(_ status: String) -> Report { Logger.computer.info("Computer use ended — \(status, privacy: .public)") var lines = ["Status: \(status)", "Actions taken:"] lines += history.isEmpty ? ["(none)"] : history.enumerated().map { "\($0 + 1). \($1)" } if let observation { lines.append("Final screen: \(observation.appName) — \"\(observation.windowTitle)\"") let text = observation.texts.joined(separator: " · ") if !text.isEmpty { lines.append("Visible text: \(text.prefix(800))") } } return Report(text: lines.joined(separator: "\n"), completed: status == "completed") }
guard AXIsProcessTrusted() else { return report("failed — Seer needs Accessibility access (System Settings → Privacy & Security → Accessibility)") }
for _ in 0..<Self.maxSteps { if Task.isCancelled { return report("cancelled by the user") } if Date().timeIntervalSince(started) > Self.timeLimit { return report("stopped — ran out of time") }
guard let obs = ScreenObserver.observe() else { return report("failed — couldn't read the screen") } observation = obs let state = render(goal: goal, obs)
do { let first = try await decisions.decide(state: state, choices: [ "operation": .init( instructions: "Given the goal, the current screen and the actions already taken, which single operation should happen next?", options: operations(for: obs, excluding: excluded)) ], nouls: [ "done": .init(instructions: "Have the actions already taken accomplished every part of the goal?", yes: "Yes, every part is done", no: "No, something is still left"), ]) guard let opAnswer = first.choices["operation"], let op = Operation(rawValue: opAnswer.choice) else { return report("failed — the decision model gave no answer") } let done = first.nouls["done"] ?? 0 Logger.computer.info("Decision: \(op.rawValue, privacy: .public) p=\(opAnswer.probability, format: .fixed(precision: 2), privacy: .public) done=\(done, format: .fixed(precision: 2), privacy: .public)") // A confident DONE vote counts too: waiting on the separate check only costs another round trip. let votedDone = op == .DONE && (opAnswer.probability >= Self.minDoneVote || done >= Self.minDone - 0.2) if !history.isEmpty, done >= Self.minDone || votedDone { return report("completed") }
if opAnswer.probability < Self.minProbability { unsure += 1 if unsure >= 3 { return report("stopped — not confident enough about the next step") } try await Task.sleep(for: .milliseconds(700)) continue } unsure = 0
let description: String switch op { case .DONE: // Not confirmed by the completion check above; look again. unsure += 1 if unsure >= 3 { return report("stopped — not sure whether the goal is complete") } try await Task.sleep(for: .milliseconds(700)) continue case .BLOCKED: return report("stopped — couldn't find a way to continue on the current screen") case .WAIT: waits += 1 if waits > 3 { return report("stopped — the screen stayed busy") } try await Task.sleep(for: .seconds(1)) continue
case .click: let options = obs.elements.map { (key: $0.id, description: "\($0.summary), \(obs.position(of: $0))") } let answers = try await decisions.decide(state: state, choices: [ "target": .init(instructions: "Which element should be clicked to best advance the goal?", options: options) ], nouls: consequenceQuestions(action: "clicking the chosen element")) guard let pick = answers.choices["target"], let element = obs.elements.first(where: { $0.id == pick.choice }) else { continue } description = "Clicked \(element.summary) in \(obs.appName)" if needsApproval(answers, label: element.label) { let action = "Click \(element.summary) in \(obs.appName)" guard await approve(ApprovalRequest(action: action)) else { return report("stopped — the user declined to let Seer: \(action)") } } if isRepeat(description, obs, &lastAction, &repeats) { return report("stopped — the same click kept having no effect") } await ActionFocus.move(to: element.center) ActionExecutor.click(element)
case .typeText: guard let field = obs.focused, field.isEditable else { continue } if let typed = lastTyped, field.value?.contains(typed) == true { excluded.insert(.typeText) continue } let text = try await textToType(goal: goal, field: field, obs) guard !text.isEmpty else { return report("stopped — couldn't work out what text to type") } if field.value?.contains(text) == true { excluded.insert(.typeText) continue } description = "Typed \"\(text.prefix(200))\" into \(field.label.isEmpty ? field.role : "\"\(field.label)\"")" if isRepeat(description, obs, &lastAction, &repeats) { return report("stopped — kept retyping the same text") } await ActionFocus.move(to: field.center) // Single-line fields are replaced, not appended to. if field.axRole != "AXTextArea", let value = field.value, !value.isEmpty, let selectAll = ActionExecutor.keys.first(where: { $0.name == "cmd+a" }) { ActionExecutor.press(selectAll, pid: obs.pid) } ActionExecutor.type(text, pid: obs.pid) lastTyped = text
case .pressKey: let options = ActionExecutor.keys.map { (key: $0.name, description: $0.description) } let answers = try await decisions.decide(state: state, choices: [ "key": .init(instructions: "Given the focused field and the last action taken, which key or shortcut should be pressed next?", options: options) ], nouls: consequenceQuestions(action: "pressing the chosen key")) guard let pick = answers.choices["key"], let key = ActionExecutor.keys.first(where: { $0.name == pick.choice }) else { continue } description = "Pressed \(key.description) in \(obs.appName)" if needsApproval(answers, label: "") { let action = "Press \(key.description) in \(obs.appName)" guard await approve(ApprovalRequest(action: action)) else { return report("stopped — the user declined to let Seer: \(action)") } } if isRepeat(description, obs, &lastAction, &repeats) { return report("stopped — the same key kept having no effect") } ActionExecutor.press(key, pid: obs.pid)
case .scroll: let answers = try await decisions.decide(state: state, choices: [ "direction": .init(instructions: "Which way should the window scroll to reveal what the goal needs?", options: [(key: "down", description: "Scroll down"), (key: "up", description: "Scroll up")]) ]) let down = answers.choices["direction"]?.choice != "up" description = "Scrolled \(down ? "down" : "up") in \(obs.appName)" if isRepeat(description, obs, &lastAction, &repeats) { return report("stopped — scrolling revealed nothing new") } if !obs.windowFrame.isEmpty { await ActionFocus.move(to: CGPoint(x: obs.windowFrame.midX, y: obs.windowFrame.midY)) } ActionExecutor.scroll(down: down, in: obs.windowFrame)
case .openApp: let answers = try await decisions.decide(state: state, choices: [ "app": .init(instructions: "Which application should be opened or switched to for the goal?", options: apps.enumerated().map { (key: "a\($0)", description: $1.name) }) ]) guard let pick = answers.choices["app"], let index = Int(pick.choice.dropFirst()), apps.indices.contains(index) else { continue } description = "Opened \(apps[index].name)" if isRepeat(description, obs, &lastAction, &repeats) { return report("stopped — \(apps[index].name) didn't come to the front") } await ActionExecutor.open(app: apps[index].url) }
waits = 0 excluded = [] history.append(description) Logger.computer.info("Step \(self.history.count, privacy: .public): \(description, privacy: .public)") // Let the app react before looking again. if op == .typeText { try await Task.sleep(for: .milliseconds(250)) } else { try await settle(after: obs.signature) } } catch is CancellationError { return report("cancelled by the user") } catch { if Task.isCancelled { return report("cancelled by the user") } Logger.computer.error("Computer use error: \(error, privacy: .public)") return report("failed — \(error.localizedDescription)") } } return report("stopped — reached the \(Self.maxSteps)-step limit") }
/// Waits only as long as the screen takes to react to an action, instead of a fixed pause: /// returns shortly after it changes, or after `limit` if nothing visibly happened. private func settle(after before: String, limit: Duration = .milliseconds(1500)) async throws { let deadline = ContinuousClock.now + limit while ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(120)) if let now = ScreenObserver.observe(), now.signature != before { try await Task.sleep(for: .milliseconds(250)) // let the change finish return } } }
// MARK: - Decisions
private func operations(for obs: Observation, excluding excluded: Set<Operation>) -> [(key: String, description: String)] { // Phrased as the condition for picking each one; yes/no-only models score them one at a time. var ops: [(Operation, String)] = [] if !obs.elements.isEmpty { ops.append((.click, "Click an element to open, select or focus it")) } if let field = obs.focused, field.isEditable, !excluded.contains(.typeText) { let name = field.label.isEmpty ? field.role : "\(field.role) \"\(field.label)\"" ops.append((.typeText, "Type the text the goal asks for into the focused \(name), which does not contain it yet")) } ops += [ (.pressKey, "Press a key or shortcut, e.g. Return to submit text already typed into a field, Tab, Escape, ⌘L, ⌘T"), (.scroll, "Scroll to reveal content that isn't listed yet"), (.openApp, "Open or switch to an application the goal needs that isn't frontmost"), (.WAIT, "Wait because the screen is still loading"), (.DONE, "Done: the actions already taken completed the goal, so no further operation is needed"), (.BLOCKED, "Stuck: no operation can advance the goal"), ] return ops.map { (key: $0.0.rawValue, description: $0.1) } }
private func consequenceQuestions(action: String) -> [String: DecisionClient.Noul] { [ "consequential": .init( instructions: "Would \(action) send, submit, post, delete, buy, pay, share or otherwise have an effect that is hard to undo?", yes: "Yes, it has a hard-to-undo effect", no: "No, it only navigates, selects or edits"), "authorized": .init( instructions: "Does the goal explicitly ask for that hard-to-undo effect (for example it says to send, delete or buy)?", yes: "Yes, the goal explicitly asks for it", no: "No, the goal does not ask for it"), ] }
/// Whether the user must OK the action first: it looks hard to undo and the goal didn't clearly /// ask for it, or its label names something the goal alone never authorizes (deleting, paying). private func needsApproval(_ answers: DecisionClient.Answers, label: String) -> Bool { let consequential = answers.nouls["consequential"] ?? 0 let authorized = answers.nouls["authorized"] ?? 0 let asked = authorized >= Self.minAuthorization let needs = ActionRisk.requiresApproval(label: label) || (!asked && (consequential >= 0.5 || ActionRisk.requiresApprovalUnlessAsked(label: label))) if needs { Logger.computer.notice("Asking before a risky action — c=\(consequential, privacy: .public) a=\(authorized, privacy: .public)") } return needs }
private func isRepeat( _ description: String, _ obs: Observation, _ last: inout (description: String, signature: String)?, _ repeats: inout Int ) -> Bool { if let previous = last, previous.description == description, previous.signature == obs.signature { repeats += 1 } else { repeats = 0 } last = (description, obs.signature) return repeats >= 2 }
// MARK: - State
/// Ordered from what changes least to what changes most between steps: the local model only /// re-reads the state from the first changed token on, so focus, the history and the text /// fields (whose values change as the agent types) come last. private func render(goal: String, _ obs: Observation) -> String { var lines = [ "Goal: \(goal)", ] + taughtLines + [ "Frontmost app: \(obs.appName)" + (obs.windowTitle.isEmpty ? "" : " — window \"\(obs.windowTitle)\""), ] if !obs.texts.isEmpty { lines.append("Visible text: \(obs.texts.joined(separator: " · ").prefix(1500))") } lines.append("Interactive elements:") let fieldsLast = obs.elements.filter { !$0.isEditable } + obs.elements.filter(\.isEditable) lines += fieldsLast.map { "[\($0.id)] \($0.summary) (\(obs.position(of: $0)))" } lines.append("Focused: \(obs.focused.map { $0.summary + ($0.isEditable ? " (editable)" : "") } ?? "nothing")") lines.append("Actions already taken (oldest first):") lines += history.isEmpty ? ["(none yet)"] : history.enumerated().map { "\($0 + 1). \($1)" } if let last = history.last { lines.append("Last action: \(last)") } return lines.joined(separator: "\n") }
/// The taught procedures, which stay the same from step to step. private var taughtLines: [String] { lessons.flatMap { lesson in ["The user taught Seer how to do \"\(lesson.name)\". Follow these steps in order, adapting to what is on screen:"] + lesson.steps.prefix(30).enumerated().map { " \($0 + 1). \($1)" } } }
// MARK: - Text
/// Exact quoted text from the goal when there's exactly one quote; otherwise the chat model writes it. private func textToType(goal: String, field: ScreenElement, _ obs: Observation) async throws -> String { let quoted = Self.quotedStrings(in: goal) if quoted.count == 1 { return quoted[0] }
let prompt = """ Goal: \(goal) \(taughtLines.isEmpty ? "" : taughtLines.joined(separator: "\n") + "\n")App: \(obs.appName)\(obs.windowTitle.isEmpty ? "" : " — window \"\(obs.windowTitle)\"") Field: \(field.summary) Actions already taken: \(history.isEmpty ? "(none)" : history.joined(separator: "\n")) """ let text = try await writer.complete(messages: [ APIMessage(role: "system", content: "You write the exact text to type into one field on the user's Mac so the goal moves forward. Reply with only that text: no quotes, no explanation, no markdown."), APIMessage(role: "user", content: prompt), ], model: writerModel) return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(2000)) }
private static func quotedStrings(in text: String) -> [String] { let pattern = #""([^"]+)"|“([^”]+)”"# guard let regex = try? NSRegularExpression(pattern: pattern) else { return [] } return regex.matches(in: text, range: NSRange(text.startIndex..., in: text)).compactMap { match in (1...2).lazy.compactMap { Range(match.range(at: $0), in: text).map { String(text[$0]) } }.first } }}
/// Tells the on-screen buddy where Seer is about to act so it can glide over there first.enum ActionFocus { /// `point` is in global screen coordinates with a top-left origin, like Accessibility frames. /// Returns after giving the buddy a moment to arrive. static func move(to point: CGPoint) async { NotificationCenter.default.post(name: .seerActionFocus, object: nil, userInfo: ["x": Double(point.x), "y": Double(point.y)]) try? await Task.sleep(for: .milliseconds(550)) }}
extension Notification.Name { static let seerActionFocus = Notification.Name("com.seer.actionFocus")}