forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryExportExecutor.swift
More file actions
442 lines (386 loc) · 17.4 KB
/
Copy pathMemoryExportExecutor.swift
File metadata and controls
442 lines (386 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
import AppKit
@preconcurrency import ApplicationServices
import Foundation
/// Shared "Execute" logic for connector setup. Used by both the Execute button in
/// the connector sheet AND the automation bridge (`POST /execute-export`) so
/// headless e2e runs drive the exact same path — no separate execution flow.
///
/// Execution modes are explicit because local CLI setup and cloud-browser setup
/// have very different preflight requirements.
@MainActor
enum MemoryExportExecutor {
enum Mode: Sendable { case autonomous, assisted, completed }
struct Outcome: Sendable {
let taskTitle: String
let mode: Mode
}
enum ExecutorError: LocalizedError {
case unsupported(String)
case browserSetupRequired(String)
var errorDescription: String? {
switch self {
case .unsupported(let name): return "\(name) does not support an MCP execution task."
case .browserSetupRequired(let message): return message
}
}
}
static func run(_ destination: MemoryExportDestination) async throws -> Outcome {
if case .directoryApp = destination.mcpExecuteKind {
guard let directoryURL = destination.directoryInstallURL else {
throw ExecutorError.unsupported(destination.title)
}
NSWorkspace.shared.open(directoryURL)
return Outcome(
taskTitle: "Opened Omi in ChatGPT. Add Omi and authorize it there, then return to Omi.",
mode: .assisted)
}
if requiresAccessibilityPreflight(destination), !isAccessibilityReadyForBrowserSetup() {
requestAccessibilityApprovalForCloudSetup()
throw ExecutorError.browserSetupRequired(cloudSetupAccessibilityPermissionMessage)
}
let key = try await hostedMCPKey(for: destination)
if MemoryBankConnector.handles(destination) {
if canSkipLocalSetupWhenConfigMatches(destination),
MemoryExportConnectionDetector.hasExistingConnection(for: destination, matchingKey: key)
{
return Outcome(taskTitle: "\(destination.title) is already connected.", mode: .completed)
}
let message = try MemoryBankConnector.connect(destination, key: key)
await MemoryExportService.shared.markConnected(destination)
return Outcome(taskTitle: message, mode: .completed)
}
switch destination.mcpExecuteKind {
case .directoryApp:
throw ExecutorError.unsupported(destination.title)
case .localAutonomous:
guard let task = destination.omiExecutionTask(key: key) else {
throw ExecutorError.unsupported(destination.title)
}
await spawnSetupAgent(task: task)
return Outcome(taskTitle: task.title, mode: .autonomous)
case .browserAutonomous:
return try await runBrowserAutonomous(destination, key: key)
case .assisted:
guard destination.omiExecutionTask(key: key) != nil else {
throw ExecutorError.unsupported(destination.title)
}
return await runAssisted(destination, key: key)
}
}
private static func canSkipLocalSetupWhenConfigMatches(_ destination: MemoryExportDestination) -> Bool {
switch destination {
case .claudeCode, .codex:
return true
case .openclaw, .hermes:
return false
case .notion, .obsidian, .chatgpt, .claude, .gemini, .agents:
return false
}
}
private static func hostedMCPKey(for destination: MemoryExportDestination) async throws -> String {
guard destination.requiresHostedMCPKeyForSetup else { return "" }
if MemoryBankConnector.handles(destination) {
return try await MemoryExportService.shared.mcpKeyForLocalConnectorSetup()
}
return try await MemoryExportService.shared.ensureMCPKey()
}
static func requiresAccessibilityPreflight(_ destination: MemoryExportDestination) -> Bool {
destination == .claude && destination.mcpExecuteKind == .browserAutonomous
}
static func accessibilityPreflightMissing(for destination: MemoryExportDestination) -> Bool {
requiresAccessibilityPreflight(destination) && !isAccessibilityReadyForBrowserSetup()
}
private static func isAccessibilityReadyForBrowserSetup() -> Bool {
AXIsProcessTrusted()
}
/// PARKED: no destination currently maps to `.browserAutonomous` — ChatGPT and
/// Claude cloud moved to the assisted flow because AX/OCR automation of other
/// people's web UIs proved too brittle across browsers and machines. Kept so a
/// future DOM-perception rebuild has the routing to slot into. Do not remap a
/// destination here without reading docs/cloud-connectors-roadmap.md.
private static func runBrowserAutonomous(
_ destination: MemoryExportDestination,
key: String
) async throws -> Outcome {
guard let setup = destination.mcpSetup(key: key), let openURL = setup.openURL else {
throw ExecutorError.unsupported(destination.title)
}
if destination == .claude {
return try await runClaudeNativeCloudSetup(setup: setup, openURL: openURL)
}
let browser = BrowserAutomationTargetResolver.defaultTarget(for: openURL)
let browserName = browser?.name ?? "your default browser"
guard let task = destination.guidedBrowserSetupTask(key: key, browserName: browserName) else {
throw ExecutorError.unsupported(destination.title)
}
let pasteboardText =
destination.requiresHostedMCPKeyForSetup
? "Server URL: \(setup.serverURL)\nKey: \(key)"
: "Server URL: \(setup.serverURL)"
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(pasteboardText, forType: .string)
if let browser {
BrowserAutomationTargetResolver.open(openURL, in: browser)
} else {
NSWorkspace.shared.open(openURL)
}
await spawnSetupAgent(task: task)
return Outcome(taskTitle: task.title, mode: .autonomous)
}
private static func runClaudeNativeCloudSetup(
setup: MCPSetup,
openURL: URL
) async throws -> Outcome {
CloudConnectorFormAutomation.dismissGuidanceOverlay()
let args: [String: Any] = [
"provider": "claude",
"name": "Omi Memory",
"server_url": setup.serverURL,
"oauth_client_id": MemoryExportDestination.claude.cloudOAuthClientID ?? "",
"submit": true,
]
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(
"""
Name: Omi Memory
Remote MCP server URL: \(setup.serverURL)
OAuth Client ID: \(MemoryExportDestination.claude.cloudOAuthClientID ?? "")
OAuth Client Secret: leave blank
""",
forType: .string)
// For cloud setup, use the user's system default browser. Do not reuse the
// Playwright/extension browser preference: that can point at Chrome even
// when the user is signed into Claude in Atlas/Arc/another default browser.
log("Claude cloud setup: opening connector page in default browser for native automation")
NSWorkspace.shared.open(openURL)
var lastResult = ""
for attempt in 1...12 {
try? await Task.sleep(nanoseconds: attempt == 1 ? 1_500_000_000 : 750_000_000)
lastResult = await CloudConnectorFormAutomation.fill(args)
log(
"Claude cloud setup: native automation attempt \(attempt) result=\(cloudFormFillResultSummary(lastResult))"
)
if cloudFormFillSucceeded(lastResult) {
CloudConnectorFormAutomation.dismissGuidanceOverlay()
if lastResult.contains("Claude connector connected.") {
await MemoryExportService.shared.markConnected(.claude)
}
return Outcome(
taskTitle:
"Claude connector form submitted. If Claude shows a final consent prompt, approve Omi Memory.",
mode: .completed)
}
if cloudFormFillRequiresAccessibilityApproval(lastResult) {
requestAccessibilityApprovalForCloudSetup()
throw ExecutorError.browserSetupRequired(cloudSetupAccessibilityPermissionMessage)
}
if cloudFormFillNeedsManualClaudeAdd(lastResult),
CloudConnectorFormAutomation.showClaudeAddGuidanceOverlay()
{
throw ExecutorError.browserSetupRequired(cloudSetupManualClaudeAddMessage)
}
if cloudFormFillRequiresScreenRecordingApproval(lastResult) {
if CloudConnectorFormAutomation.showClaudeConnectGuidanceOverlay() {
throw ExecutorError.browserSetupRequired(cloudSetupManualClaudeConnectMessage)
} else {
// We could not anchor to Claude. Send the user to grant Screen Recording, but
// never leave them on a bare settings pane: show an instruction card too.
requestScreenRecordingApprovalForCloudSetup()
await CloudConnectorFormAutomation.showScreenRecordingSettingsInstructionOverlay(
actionLabel: "Connect")
throw ExecutorError.browserSetupRequired(cloudSetupScreenRecordingPermissionMessage)
}
}
if !cloudFormFillShouldRetry(lastResult) {
break
}
}
log(
"Claude cloud setup: stopping without agent fallback result=\(cloudFormFillResultSummary(lastResult))"
)
throw ExecutorError.browserSetupRequired(cloudSetupNativeAutomationBlockedMessage)
}
nonisolated static func cloudFormFillSucceeded(_ result: String) -> Bool {
let cleanResult =
!result.contains("Missing:")
&& !result.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix("Error:")
return cleanResult
&& (result.contains("Submitted with button: Connect")
|| result.contains("Submitted with button: Create")
|| result.contains("Submitted with button: Save")
|| result.contains("Claude connector connected."))
}
static func cloudFormFillRequiresAccessibilityApproval(_ result: String) -> Bool {
result.lowercased().contains("accessibility permission is not available")
}
static func cloudFormFillRequiresScreenRecordingApproval(_ result: String) -> Bool {
result.lowercased().contains("screen recording permission is not available")
}
nonisolated static func cloudFormFillShouldRetry(_ result: String) -> Bool {
result.contains("Could not find a visible")
|| result.contains("Submit skipped: no enabled")
|| result.contains("set failed")
|| result.contains("Submitted with button: Add")
}
private static func cloudFormFillResultSummary(_ result: String) -> String {
let sanitized =
result
.split(separator: "\n")
.filter { !$0.lowercased().contains("oauth client secret") }
.joined(separator: " | ")
return String(sanitized.prefix(500))
}
static func cloudFormFillNeedsManualClaudeAdd(_ result: String) -> Bool {
let lower = result.lowercased()
return lower.contains("hidden add button")
|| lower.contains("claude add connector button is not exposed")
|| (lower.contains("claude add") && lower.contains("not exposed to accessibility"))
|| (lower.contains("add connector button") && lower.contains("refusing blind"))
}
private static var cloudSetupNativeAutomationBlockedMessage: String {
"""
Omi opened Claude in your default browser, but Claude still needs one manual step.
Finish the connector setup in the Claude window that is already open. If the connector form is filled, click Add. If Claude asks for permission, approve Omi Memory.
If nothing is waiting in Claude, click "Do it for me" again or use the manual installation steps below.
"""
}
private static var cloudSetupAccessibilityPermissionMessage: String {
"""
Omi needs Accessibility permission to finish Claude setup automatically.
Approve Accessibility for this Omi app in System Settings, then click "Do it for me" again. If you do not want to grant it, use the manual installation steps below.
"""
}
private static var cloudSetupScreenRecordingPermissionMessage: String {
"""
Omi needs Screen Recording permission to finish Claude setup automatically.
I added the Claude connector, but Claude hides the final Connect button from Accessibility in this browser. Approve Screen Recording for this Omi app in System Settings, then click "Do it for me" again.
"""
}
private static var cloudSetupManualClaudeConnectMessage: String {
"""
Claude is waiting for one final click.
I added the connector and pointed to the Connect button in your browser.
"""
}
private static var cloudSetupManualClaudeAddMessage: String {
"""
Claude is waiting for one click.
I filled the connector form and pointed to the Add button in your browser.
"""
}
private static func requestAccessibilityApprovalForCloudSetup() {
let options =
[kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
let trusted = AXIsProcessTrustedWithOptions(options)
guard !trusted,
let url = URL(
string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
else { return }
NSWorkspace.shared.open(url)
}
private static func requestScreenRecordingApprovalForCloudSetup() {
// Actually request access first. CGRequestScreenCaptureAccess() both shows the
// system consent prompt AND registers this app in the Screen Recording list with a
// ready-to-flip toggle. Without it the app never appears in the list, so opening
// Settings alone left the user with nothing to turn on.
ScreenCaptureService.requestAllScreenCapturePermissions()
guard
let url = URL(
string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")
else { return }
NSWorkspace.shared.open(url)
}
/// Assisted setup: everything deterministic happens in code (copy the full
/// field payload, open the deep link), then an on-screen card tells the user
/// the one thing left to do. This is the primary path for ChatGPT/Claude cloud
/// connectors — see docs/cloud-connectors-roadmap.md for why autonomous
/// browser automation is parked and what replaces it.
private static func runAssisted(_ destination: MemoryExportDestination, key: String) async -> Outcome {
if let url = destination.mcpSetup(key: key)?.openURL {
NSWorkspace.shared.open(url)
}
if let hint = destination.assistedOverlayHint,
let sections = destination.assistedSetupSections(key: key)
{
CloudConnectorGuidanceOverlay.shared.presentFieldCopyCard(
title: hint.title, subtitle: hint.subtitle, sections: sections, near: nil)
return Outcome(
taskTitle:
"Opened \(destination.title) — copy each value from the on-screen card into the form.",
mode: .assisted)
}
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(key, forType: .string)
_ = await TasksStore.shared.createTask(
description: "Finish connecting \(destination.title) to Omi (page opened, key copied)",
dueAt: Date(), priority: "medium", tags: ["mcp-setup"])
return Outcome(
taskTitle: "Opened \(destination.title) and copied your key — finish with the steps below.",
mode: .assisted)
}
private static func spawnSetupAgent(task: (title: String, body: String)) async {
_ = await TasksStore.shared.createTask(
description: task.title, dueAt: Date(), priority: "high", tags: ["mcp-setup"])
let model =
ShortcutSettings.shared.selectedModel.isEmpty
? "claude-sonnet-4-6" : ShortcutSettings.shared.selectedModel
let query = ProactiveTaskExecute.buildQuery(title: task.title, message: task.body)
_ = AgentPillsManager.shared.spawn(
query: query,
model: model,
originSurface: .mainChat,
systemPromptSuffix: ProactiveTaskExecute.systemPromptSuffix)
}
}
/// Detects running Claude Code CLI sessions so the post-setup UI can offer to
/// stop them (new MCP config only loads at session start). Stopping is safe-ish:
/// Claude Code persists conversations, so `claude --continue` resumes them.
enum ClaudeCodeSessions {
/// The CLI binary is ".../bin/claude" (native install) or ".../bin/claude.exe"
/// (pnpm/bun bundle). Claude Desktop and its helpers are capitalized
/// ("Claude", "Claude Helper") and must never match.
static func isClaudeCLI(executablePath: String) -> Bool {
let name = (executablePath as NSString).lastPathComponent
return name == "claude" || name == "claude.exe"
}
static func completionSubtitle(sessionCount: Int, didStop: Bool) -> String {
if didStop {
return "Sessions stopped — run claude --continue in your terminal to pick up where you left off."
}
if sessionCount == 0 {
return "You're all set — Omi Memory loads automatically in your next Claude Code session."
}
return "Restart Claude Code to load Omi Memory."
}
/// Current user's running Claude Code CLI processes.
static func runningPIDs() -> [pid_t] {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/ps")
process.arguments = ["-axo", "pid=,uid=,comm="]
let pipe = Pipe()
process.standardOutput = pipe
do { try process.run() } catch { return [] }
let data = pipe.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
guard let output = String(data: data, encoding: .utf8) else { return [] }
let uid = getuid()
var pids: [pid_t] = []
for line in output.split(separator: "\n") {
// comm may contain spaces — keep everything after pid and uid as the path.
let fields = line.split(separator: " ", maxSplits: 2, omittingEmptySubsequences: true)
guard fields.count == 3,
let pid = pid_t(fields[0]),
let lineUID = uid_t(fields[1]),
lineUID == uid,
isClaudeCLI(executablePath: String(fields[2]))
else { continue }
pids.append(pid)
}
return pids
}
static func stop(_ pids: [pid_t]) {
for pid in pids where pid > 0 {
kill(pid, SIGTERM)
}
}
}