forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryExportService.swift
More file actions
1593 lines (1420 loc) · 58.2 KB
/
Copy pathMemoryExportService.swift
File metadata and controls
1593 lines (1420 loc) · 58.2 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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import AppKit
import Foundation
import OmiSupport
enum MemoryExportDestination: String, CaseIterable, Identifiable, Sendable {
case notion
case obsidian
case chatgpt
case claude
case gemini
case agents
case claudeCode
case codex
case openclaw
case hermes
var id: String { rawValue }
/// Base of the hosted Omi API for this build — stable channel hits prod
/// (api.omi.me), beta hits dev (api.omiapi.com). Always ends with "/".
static var mcpBaseURL: String {
DesktopBackendEnvironment.pythonBaseURL()
}
/// The hosted Omi MCP SSE endpoint every client connects to.
static var mcpServerURL: String { "\(mcpBaseURL)v1/mcp/sse" }
/// OAuth endpoints exposed by the same backend for MCP custom-connector setup.
static var mcpAuthorizeURL: String { "\(mcpBaseURL)authorize" }
static var mcpTokenURL: String { "\(mcpBaseURL)token" }
/// Registered OAuth client for ChatGPT custom connectors on this backend.
/// Prod registers `omi-chatgpt-prod` as a PUBLIC PKCE client — the token
/// endpoint rejects any client secret for it, so setup must leave the
/// secret blank. Dev registers `omi-chatgpt-dev`.
static var chatgptOAuthClientID: String {
mcpBaseURL.contains("api.omi.me") ? "omi-chatgpt-prod" : "omi-chatgpt-dev"
}
/// The approved ChatGPT directory listing. This is the primary ChatGPT
/// connection path; the custom-connector flow remains an advanced fallback.
static let chatGPTDirectoryInstallURL = URL(
string: "https://chatgpt.com/plugins/plugin_asdk_app_6a1490df4c588191b9339ae21978c873?q=omi")!
var cloudOAuthClientID: String? {
switch self {
case .chatgpt: return Self.chatgptOAuthClientID
case .claude: return "omi-claude-prod"
case .notion, .obsidian, .gemini, .agents, .claudeCode, .codex, .openclaw, .hermes:
return nil
}
}
/// Client IDs that count as "authorized" when scanning OAuth grants — NOT the
/// same as `cloudOAuthClientID` (the setup form's per-backend value). The
/// ChatGPT directory is one global plugin that always grants under
/// `omi-chatgpt-prod`, even on a dev-backend build, so verification must accept
/// it or ChatGPT never connects on Beta. Mirrors backend `PUBLIC_CHATGPT_CLIENT_IDS`.
var cloudOAuthGrantClientIDs: Set<String> {
switch self {
case .chatgpt: return ["omi-chatgpt-prod", "omi-chatgpt-dev"]
case .claude: return ["omi-claude-prod"]
case .notion, .obsidian, .gemini, .agents, .claudeCode, .codex, .openclaw, .hermes:
return []
}
}
var cloudOAuthClientSecret: String? {
switch self {
case .chatgpt, .claude:
return nil
case .notion, .obsidian, .gemini, .agents, .claudeCode, .codex, .openclaw, .hermes:
return nil
}
}
var cloudTokenAuthMethod: String? {
switch self {
case .chatgpt: return "none"
case .claude:
return nil
case .notion, .obsidian, .gemini, .agents, .claudeCode, .codex, .openclaw, .hermes:
return nil
}
}
var usesPublicCloudOAuthClient: Bool {
cloudOAuthClientID != nil && cloudOAuthClientSecret == nil
}
var requiresHostedMCPKeyForSetup: Bool {
!usesPublicCloudOAuthClient
}
var title: String {
switch self {
case .notion: return "Notion"
case .obsidian: return "Obsidian"
case .chatgpt: return "ChatGPT"
case .claude: return "Claude"
case .gemini: return "Gemini"
case .agents: return "AI Agents"
case .claudeCode: return "Claude Code"
case .codex: return "Codex"
case .openclaw: return "OpenClaw"
case .hermes: return "Hermes"
}
}
var subtitle: String {
switch self {
case .notion: return "Live page in your workspace"
case .obsidian: return "Choose once, refresh anytime"
case .chatgpt: return "Add Omi from the ChatGPT directory"
case .claude: return "Live MCP or memory pack"
case .gemini: return "Prompt + memory pack"
case .agents: return "One prompt for your agent"
case .claudeCode: return "Connect via MCP"
case .codex: return "Connect via MCP"
case .openclaw: return "Memory bank for OpenClaw"
case .hermes: return "Memory bank for Hermes"
}
}
var description: String {
switch self {
case .notion: return "Connect once and Omi keeps an Omi Memories page fresh in your workspace."
case .obsidian: return "Write Omi memories into your Obsidian vault."
case .chatgpt:
return "Add Omi in ChatGPT, authorize once, and use your memories in every ChatGPT chat."
case .claude:
return "Connect over MCP so Claude reads your memories live, or copy a memory pack."
case .gemini: return "Copy the prompt and memory pack, then open Gemini."
case .agents: return "Give your agent one prompt that connects Omi memories and this Mac."
case .claudeCode: return "Add Omi as an MCP server so Claude Code always reads your memories."
case .codex: return "Add Omi as an MCP server so Codex always reads your memories."
case .openclaw: return "Wire Omi memory into OpenClaw so your agent reads your memories."
case .hermes: return "Wire Omi memory into Hermes so your agent reads your memories."
}
}
var brand: ConnectorBrand {
switch self {
case .notion: return .notion
case .obsidian: return .obsidian
case .chatgpt: return .chatgpt
case .claude: return .claude
case .gemini: return .gemini
case .agents: return .agents
case .claudeCode: return .claudeCode
case .codex: return .codex
case .openclaw: return .openclaw
case .hermes: return .hermes
}
}
var isAutomated: Bool {
switch self {
case .obsidian:
return true
case .notion, .chatgpt, .claude, .gemini, .agents, .claudeCode, .codex, .openclaw, .hermes:
return false
}
}
/// Whether this destination offers the live MCP connector flow.
var supportsMCP: Bool {
switch self {
case .chatgpt, .claude, .claudeCode, .codex, .openclaw, .hermes:
return true
case .notion, .obsidian, .gemini, .agents:
return false
}
}
/// How the primary connection button performs setup.
/// - `.directoryApp`: opens an approved provider directory listing. Provider
/// consent completes the connection, then Omi refreshes the OAuth grant.
/// - `.localAutonomous`: deterministic local CLI/config/file work.
/// - `.browserAutonomous`: open the cloud connector in the user's default
/// signed-in browser and use native macOS automation, with assisted fallback
/// on blockers. Currently unmapped: ChatGPT/Claude moved to `.assisted`
/// because cross-browser AX automation is too brittle — see
/// docs/cloud-connectors-roadmap.md before mapping anything back here.
/// - `.assisted`: deterministic open + copy, with an on-screen guidance card
/// for cloud connectors. The user performs the final paste/click.
enum MCPExecuteKind: Equatable { case directoryApp, localAutonomous, browserAutonomous, assisted }
var mcpExecuteKind: MCPExecuteKind {
switch self {
case .chatgpt: return .directoryApp
case .claudeCode, .codex, .openclaw, .hermes: return .localAutonomous
case .claude, .notion, .obsidian, .gemini, .agents: return .assisted
}
}
var supportsAgentSetup: Bool {
self == .agents
}
var hasLocallyVerifiableLiveSetup: Bool {
switch self {
case .agents, .claudeCode, .codex, .openclaw, .hermes:
return true
case .notion, .obsidian, .chatgpt, .claude, .gemini:
return false
}
}
/// Whether this destination offers the classic copy/paste memory-pack export.
var supportsMemoryPack: Bool {
switch self {
case .notion, .obsidian, .chatgpt, .claude, .gemini:
return true
case .agents, .claudeCode, .codex, .openclaw, .hermes:
return false
}
}
var browserURL: URL? {
switch self {
case .notion:
return URL(string: "https://www.notion.so/")
case .obsidian:
return nil
case .chatgpt:
return URL(string: "https://chatgpt.com/")
case .claude:
return URL(string: "https://claude.ai/new")
case .gemini:
return URL(string: "https://gemini.google.com/app")
case .agents, .claudeCode, .codex, .openclaw, .hermes:
return nil
}
}
var directoryInstallURL: URL? {
self == .chatgpt ? Self.chatGPTDirectoryInstallURL : nil
}
var manualPrompt: String {
switch self {
case .notion, .agents, .claudeCode, .codex, .openclaw, .hermes:
return ""
case .chatgpt:
return """
I’m attaching an Omi memory export. Read it carefully and keep the durable facts, preferences, projects, relationships, and goals as working context for future conversations with me. Start by giving me a concise profile summary of what you learned.
"""
case .claude:
return """
I’m attaching an Omi memory export. Absorb the durable facts about me, including projects, habits, preferences, relationships, and goals, and use them as context for future conversations. Start by summarizing the most important things you learned about me.
"""
case .gemini:
return """
I’m attaching an Omi memory export. Read it as persistent context about me and keep the durable facts, preferences, projects, and goals in mind for future chats. Start with a short profile summary of what stands out.
"""
case .obsidian:
return ""
}
}
func clipboardText(for markdown: String) -> String {
switch self {
case .notion, .obsidian, .agents, .claudeCode, .codex, .openclaw, .hermes:
return markdown
case .chatgpt, .claude, .gemini:
return """
\(manualPrompt)
---
\(markdown)
"""
}
}
// MARK: - MCP connection setup
/// Per-client instructions for wiring Omi memory in over MCP, rendered with the user's key.
func mcpSetup(key: String) -> MCPSetup? {
let url = Self.mcpServerURL
switch self {
case .claude:
return MCPSetup(
serverURL: url,
copyTitle: nil,
copyText: nil,
steps: [
"Open Claude → Customize → Connectors → Add custom connector",
"Copy Name and Remote MCP server URL into the first two Claude fields",
"Open Advanced settings, set OAuth Client ID “\(cloudOAuthClientID ?? "")”, and leave OAuth Client Secret blank",
"Click Add, then Connect. Syncs to Claude desktop + mobile automatically.",
],
openURL: URL(string: "https://claude.ai/customize/connectors?modal=add-custom-connector"),
openTitle: "Add Claude Connector"
)
case .chatgpt:
return MCPSetup(
serverURL: url,
copyTitle: nil,
copyText: nil,
steps: [
"Open ChatGPT → Settings → Apps → Advanced, then enable Developer mode",
"Click Create app, then fill the first visible fields: Name “Omi Memory”, Connection / server URL, and Authentication OAuth",
"Paste OAuth Client ID “\(cloudOAuthClientID ?? "")”, leave Client Secret blank, set token auth method “\(cloudTokenAuthMethod ?? "none")”, Auth URL, and Token URL",
"Click Create app, then Connect. Syncs to ChatGPT desktop + mobile automatically.",
],
openURL: URL(string: "https://chatgpt.com/#settings/Connectors"),
openTitle: "Open ChatGPT"
)
case .claudeCode:
return MCPSetup(
serverURL: url,
copyTitle: "Copy command",
copyText:
"claude mcp add --scope user --transport http omi-memory \(url) --header \"Authorization: Bearer \(key)\"",
steps: [
"Run the command below in your terminal",
"It registers Omi at user scope, so every Claude Code project reads your memories",
],
openURL: nil,
openTitle: nil
)
case .codex:
return MCPSetup(
serverURL: url,
copyTitle: "Copy config",
copyText: """
[mcp_servers.omi-memory]
command = "npx"
args = ["-y", "mcp-remote", "\(url)", "--header", "Authorization: Bearer \(key)"]
""",
steps: [
"Add the block below to ~/.codex/config.toml",
"Restart Codex — it will read your Omi memories over MCP",
],
openURL: nil,
openTitle: nil
)
case .hermes:
return MCPSetup(
serverURL: url,
copyTitle: "Copy config",
copyText: """
omi-memory:
command: npx
args: ["-y", "mcp-remote", "\(url)", "--header", "Authorization: Bearer \(key)"]
""",
steps: [
"Add the block below under mcp_servers: in ~/.hermes/config.yaml",
"Restart Hermes — it reads your Omi memories over MCP and searches them first",
],
openURL: nil,
openTitle: nil
)
case .openclaw:
let serverJSON =
#"{"enabled":true,"url":"\#(url)","transport":"streamable-http","headers":{"Authorization":"Bearer \#(key)"}}"#
return MCPSetup(
serverURL: url,
copyTitle: "Copy command",
copyText: """
openclaw mcp set omi-memory \(Self.shellQuote(serverJSON))
openclaw mcp reload
""",
steps: [
"Run the command below to add the Omi MCP server to ~/.openclaw/openclaw.json",
"Reload OpenClaw MCP so open sessions rebuild their tool list",
"Add a SOUL.md note asking OpenClaw to search Omi memory first",
],
openURL: nil,
openTitle: nil
)
case .notion, .obsidian, .gemini, .agents:
return nil
}
}
var mcpSetupCompletionSummary: MCPSetupCompletionSummary {
switch self {
case .codex:
return MCPSetupCompletionSummary(
title: "Setup complete",
subtitle: "Restart Codex to load Omi Memory."
)
case .claudeCode:
return MCPSetupCompletionSummary(
title: "Setup complete",
subtitle: "Restart Claude Code to load Omi Memory."
)
case .hermes:
return MCPSetupCompletionSummary(
title: "Setup complete",
subtitle: "Restart Hermes to load Omi Memory."
)
case .openclaw:
return MCPSetupCompletionSummary(
title: "Connected",
subtitle: "OpenClaw is ready to read Omi Memory."
)
case .chatgpt:
return MCPSetupCompletionSummary(
title: "Authorized in ChatGPT",
subtitle: "ChatGPT can now use your Omi memories."
)
case .claude:
return MCPSetupCompletionSummary(
title: "Connected",
subtitle: "\(title) can read Omi Memory."
)
case .notion, .obsidian, .gemini, .agents:
return MCPSetupCompletionSummary(
title: "Setup complete",
subtitle: "\(title) is ready."
)
}
}
private static func shellQuote(_ value: String) -> String {
"'\(value.replacingOccurrences(of: "'", with: "'\\''"))'"
}
/// Title + body for an Omi task that asks Omi to perform this connection
/// autonomously (driving the browser/terminal) via the standard execute flow.
func omiExecutionTask(key: String) -> (title: String, body: String)? {
guard let setup = mcpSetup(key: key) else { return nil }
let clientName = title
let taskTitle = "Connect my Omi memory to \(clientName) over MCP"
var lines = [
"Set up the Omi memory MCP connector in \(clientName) end-to-end for me so it can read my Omi memories. Complete this autonomously if the user is already signed in and the UI allows it. Hand back only if sign-in, missing workspace permission, security confirmation, or changed UI blocks you.",
"",
]
if self == .claude {
lines.append(contentsOf: [
"Claude custom connector fields:",
"Name: Omi Memory",
"Remote MCP server URL: \(setup.serverURL)",
"OAuth Client ID: \(cloudOAuthClientID ?? "")",
"Leave OAuth Client Secret blank.",
"",
])
} else {
lines.append(contentsOf: [
"MCP server URL: \(setup.serverURL)",
"My Omi MCP key: \(key)",
"",
])
}
lines.append("Steps:")
for (index, step) in setup.steps.enumerated() {
lines.append("\(index + 1). \(step)")
}
if let copyText = setup.copyText {
lines.append("")
lines.append("Command/config to run:")
lines.append(copyText)
}
return (taskTitle, lines.joined(separator: "\n"))
}
func guidedBrowserSetupTask(key: String, browserName: String) -> (title: String, body: String)? {
guard let setup = mcpSetup(key: key), let openURL = setup.openURL else { return nil }
let taskTitle = "Connect my Omi memory to \(title) over MCP"
let values: [String]
switch self {
case .chatgpt:
values = [
"Name: Omi Memory",
"Remote MCP server URL: \(setup.serverURL)",
"Authentication: OAuth",
"OAuth Client ID: \(cloudOAuthClientID ?? "")",
"Token auth method: \(cloudTokenAuthMethod ?? "")",
"Auth URL: \(Self.mcpAuthorizeURL)",
"Token URL: \(Self.mcpTokenURL)",
]
case .claude:
values = [
"Name: Omi Memory",
"Remote MCP server URL: \(setup.serverURL)",
"OAuth Client ID: \(cloudOAuthClientID ?? "")",
]
default:
return nil
}
let valuesJSON =
"{"
+ values.map { line -> String? in
let parts = line.split(separator: ":", maxSplits: 1).map(String.init)
guard parts.count == 2 else { return nil }
let key = parts[0].trimmingCharacters(in: .whitespaces)
let value = parts[1].trimmingCharacters(in: .whitespaces)
return "\"\(Self.jsonEscaped(key))\":\"\(Self.jsonEscaped(value))\""
}
.compactMap { $0 }
.joined(separator: ",")
+ "}"
var nativeToolArgs: [(String, String)] = [
("provider", rawValue),
("name", "Omi Memory"),
("server_url", setup.serverURL),
("submit", "true"),
]
if let clientID = cloudOAuthClientID {
nativeToolArgs.append(("oauth_client_id", clientID))
}
if let clientSecret = cloudOAuthClientSecret {
nativeToolArgs.append(("oauth_client_secret", clientSecret))
}
if self == .chatgpt {
// Public PKCE client — no client secret; the token endpoint rejects one.
// oauth_client_secret is required by the tool schema — pass empty string.
nativeToolArgs.append(contentsOf: [
("authentication", "OAuth"),
("token_auth_method", cloudTokenAuthMethod ?? "none"),
("auth_url", Self.mcpAuthorizeURL),
("token_url", Self.mcpTokenURL),
])
}
let nativeToolJSON =
"{"
+ nativeToolArgs.map { key, value in
if key == "submit" {
return "\"\(key)\":\(value)"
}
return "\"\(key)\":\"\(Self.jsonEscaped(value))\""
}
.joined(separator: ",")
+ "}"
var lines = [
"Finish connecting Omi memory to \(title) in \(browserName).",
"FIRST ACTION: call the `fill_cloud_connector_form` tool with this exact JSON, then read its result before doing anything else:",
nativeToolJSON,
"Only fall back to bash, osascript, screenshots, or keyboard automation if that tool reports a missing form, missing required field, or missing permission.",
"Use macOS UI automation first: Accessibility, System Events, AppleScript/osascript, screenshots, keyboard shortcuts, and pasteboard are available. Use browser tools only if they are already available; do not require the user to install a browser extension.",
"This is an autonomous setup attempt. Do not stop after opening the page; navigate and fill the connector/app form if the user is already signed in.",
"Use a new browser tab when possible, keep all work in that tab, and do not disturb the user's other tabs.",
"Before every click, key press, or paste, verify the frontmost app is \(browserName), the visible URL is the expected \(title) setup page, and the next control/state is clearly identified. Do not use blind coordinate clicks or repeated Tab/Enter loops on an unverified page.",
"If the user is signed out, developer/custom connector permission is missing, a CAPTCHA/security prompt appears, or the UI no longer has the expected controls, stop and report the exact blocker plus the next click/value needed.",
"",
"Start URL: \(openURL.absoluteString)",
"Setup values JSON: \(valuesJSON)",
"Leave OAuth Client Secret blank if the form shows it.",
"",
"Values to enter:",
]
lines.append(contentsOf: values.map { "- \($0)" })
lines.append("")
lines.append("Automation ladder:")
lines.append(
"1. Bring \(browserName) forward and use keyboard shortcuts/System Events to navigate if needed. Prefer Cmd-L, paste the Start URL, Enter, then wait for the page to load."
)
lines.append(
"2. If \(browserName) has a Chrome-style AppleScript dictionary, use osascript to set the active tab URL and `execute javascript` to inspect labels, find inputs/buttons, and fill matching fields."
)
lines.append(
"3. If JavaScript execution is unavailable, use screenshots plus Accessibility/System Events: click by visible labels, use Tab/Shift-Tab to move through fields, paste exact values from the setup JSON, and read visible text after each major step."
)
lines.append(
"4. Keep using the browser that is already open/signed in. Do not launch a clean Playwright profile unless the user is already signed in there."
)
lines.append(
"5. Do not install browser extensions. If the only blocker is lack of extension-based browser tools, continue with System Events instead."
)
lines.append("")
lines.append("Expected path:")
for (index, step) in setup.steps.enumerated() {
lines.append("\(index + 1). \(step)")
}
lines.append("")
lines.append(
"After setup, verify that \(title) shows Omi Memory as connected or available. If a final OAuth consent/connect button appears, click it only when it is clearly for Omi Memory."
)
return (taskTitle, lines.joined(separator: "\n"))
}
/// Field-by-field payload for assisted cloud setup — rendered as copy rows on
/// the on-screen guidance card so the user transfers one value at a time.
func assistedSetupFields(key: String) -> [CloudConnectorCopyField]? {
assistedSetupSections(key: key).map(CloudConnectorCopySection.flattenedFields)
}
/// Sectioned field payload for assisted cloud setup. Use sections when the
/// provider form hides some fields behind an advanced disclosure.
func assistedSetupSections(key: String) -> [CloudConnectorCopySection]? {
guard let setup = mcpSetup(key: key) else { return nil }
switch self {
case .claude:
// Public OAuth client: match the manual setup copy and native automation.
// Claude may render a secret field, but the backend expects it to stay blank.
return [
CloudConnectorCopySection(
id: "main_fields",
title: "Main fields",
fields: [
CloudConnectorCopyField(id: "name", label: "Name", value: "Omi Memory"),
CloudConnectorCopyField(
id: "server_url", label: "Remote MCP server URL", value: setup.serverURL),
]),
CloudConnectorCopySection(
id: "advanced_settings",
title: "Advanced settings",
fields: [
CloudConnectorCopyField(
id: "oauth_client_id", label: "OAuth Client ID", value: cloudOAuthClientID ?? ""),
CloudConnectorCopyField(
id: "oauth_client_secret", label: "OAuth Client Secret", value: "", masksValue: false),
]),
]
case .chatgpt:
// Public PKCE client: the backend rejects token requests that carry a
// client secret, so the form's Client Secret field must stay empty.
return [
CloudConnectorCopySection(
id: "visible_fields",
title: "Main fields",
fields: [
CloudConnectorCopyField(id: "name", label: "Name", value: "Omi Memory"),
CloudConnectorCopyField(
id: "server_url", label: "Connection / server URL", value: setup.serverURL),
CloudConnectorCopyField(id: "authentication", label: "Authentication", value: "OAuth"),
]),
CloudConnectorCopySection(
id: "advanced_oauth_settings",
title: "Advanced OAuth settings",
fields: [
CloudConnectorCopyField(
id: "oauth_client_id", label: "OAuth Client ID", value: Self.chatgptOAuthClientID),
CloudConnectorCopyField(
id: "oauth_client_secret", label: "OAuth Client Secret", value: "", masksValue: false),
CloudConnectorCopyField(
id: "token_auth_method", label: "Token auth method", value: cloudTokenAuthMethod ?? "none",
masksValue: false),
CloudConnectorCopyField(id: "auth_url", label: "Auth URL", value: Self.mcpAuthorizeURL),
CloudConnectorCopyField(
id: "token_url", label: "Token URL", value: Self.mcpTokenURL, masksValue: false),
]),
]
default:
return nil
}
}
/// Short on-screen guidance card shown right after Omi opens the provider page.
var assistedOverlayHint: (title: String, subtitle: String)? {
switch self {
case .claude:
return (
"Finish in Claude",
"Copy each value into the Add custom connector form, then click Add and Connect."
)
case .chatgpt:
return nil
default:
return nil
}
}
private static func jsonEscaped(_ value: String) -> String {
value
.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "\"", with: "\\\"")
.replacingOccurrences(of: "\n", with: "\\n")
}
fileprivate var notionTokenKey: String { "memoryExportNotionToken" }
fileprivate var notionParentPageKey: String { "memoryExportNotionParentPageID" }
fileprivate var obsidianVaultPathKey: String { "memoryExportObsidianVaultPath" }
fileprivate var exportedCountKey: String { "memoryExportExportedCount.\(rawValue)" }
fileprivate var lastExportedAtKey: String { "memoryExportLastExportedAt.\(rawValue)" }
fileprivate var detailKey: String { "memoryExportDetail.\(rawValue)" }
fileprivate var lastExportPathKey: String { "memoryExportLastExportPath.\(rawValue)" }
fileprivate var connectedAtKey: String { "memoryExportConnectedAt.\(rawValue)" }
}
struct MemoryExportStatus: Sendable {
let exportedCount: Int
let lastExportedAt: Date?
let detailText: String?
let isConfigured: Bool
let hasConnection: Bool
}
struct MCPSetupCompletionSummary: Equatable, Sendable {
let title: String
let subtitle: String
}
struct MemoryExportConnectionPresentation: Equatable {
let primaryActionTitle: String?
let completion: MCPSetupCompletionSummary?
static func make(
destination: MemoryExportDestination,
status: MemoryExportStatus?,
isRunning: Bool,
accessibilityPreflightMissing: Bool = false
) -> MemoryExportConnectionPresentation {
if status?.hasConnection == true {
return MemoryExportConnectionPresentation(
primaryActionTitle: nil,
completion: destination.mcpSetupCompletionSummary
)
}
let title: String
if isRunning {
title = "Connecting…"
} else {
switch destination.mcpExecuteKind {
case .directoryApp:
title = "Add Omi to ChatGPT"
case .localAutonomous:
title = "Do it for me"
case .browserAutonomous:
title = accessibilityPreflightMissing ? "Grant Accessibility" : "Do it for me"
case .assisted:
title = destination.assistedOverlayHint != nil ? "Open & guide me" : "Open & copy key"
}
}
return MemoryExportConnectionPresentation(primaryActionTitle: title, completion: nil)
}
}
/// Rendered MCP connection instructions for a single client.
struct MCPSetup: Sendable {
let serverURL: String
let copyTitle: String?
let copyText: String?
let steps: [String]
let openURL: URL?
let openTitle: String?
}
struct MemoryExportResult: Sendable {
let memoryCount: Int
let detailText: String?
let destinationURL: URL?
let fileURL: URL?
let clipboardText: String?
}
struct AgentConnectionTestResult: Sendable {
let hostedMemoryCount: Int
let localToolCount: Int
var summary: String {
"Connection looks good: Omi returned \(hostedMemoryCount) hosted memories, and Desktop shared \(localToolCount) local tools."
}
}
enum MemoryExportError: LocalizedError {
case noMemories
case invalidNotionConfiguration
case invalidNotionResponse
case invalidObsidianVault
case requestFailed(String)
var errorDescription: String? {
switch self {
case .noMemories:
return "There are no memories available to export yet."
case .invalidNotionConfiguration:
return "Enter both a Notion integration token and a parent page ID."
case .invalidNotionResponse:
return "Notion returned an unexpected response."
case .invalidObsidianVault:
return "Choose a valid Obsidian vault folder first."
case .requestFailed(let message):
return message
}
}
}
actor MemoryExportService {
static let shared = MemoryExportService()
private static let authUserIDDefaultsKey = "auth_userId"
private static let mcpKeyDefaultsKey = "memoryExportMCPApiKey"
private static let mcpKeyOwnerDefaultsKey = "memoryExportMCPApiKeyOwnerUserId"
private static let mcpKeyCreatedAtDefaultsKey = "memoryExportMCPApiKeyCreatedAt"
private let defaults = UserDefaults.standard
private let notionVersion = "2026-03-11"
private let notionBaseURL = URL(string: "https://api.notion.com/v1")!
private var mcpKeyWarmTask: (ownerUserId: String, id: UUID, task: Task<String, Error>)?
private struct OAuthGrant: Decodable {
let clientID: String
let status: String?
let revokedAt: String?
enum CodingKeys: String, CodingKey {
case clientID = "client_id"
case status
case revokedAt = "revoked_at"
}
var isActive: Bool {
revokedAt == nil && status != "revoked"
}
}
private struct OAuthGrantsResponse: Decodable {
let grants: [OAuthGrant]
}
func status(for destination: MemoryExportDestination) -> MemoryExportStatus {
let currentMCPKey = storedMCPKey()
let localConnections: Set<MemoryExportDestination> =
destination.supportsMCP
? MemoryExportConnectionDetector.scanLocalMCPConnections(for: destination, matchingKey: currentMCPKey)
: []
return status(for: destination, localMCPConnections: localConnections)
}
private func status(
for destination: MemoryExportDestination,
localMCPConnections: Set<MemoryExportDestination>
) -> MemoryExportStatus {
let exportedCount = max(defaults.integer(forKey: destination.exportedCountKey), 0)
let lastExportedAt: Date?
if defaults.object(forKey: destination.lastExportedAtKey) != nil {
let timestamp = defaults.double(forKey: destination.lastExportedAtKey)
lastExportedAt = timestamp > 0 ? Date(timeIntervalSince1970: timestamp) : nil
} else {
lastExportedAt = nil
}
let detailText = defaults.string(forKey: destination.detailKey)
let hasLocalMCPConnection = localMCPConnections.contains(destination)
let hasConnectedTimestamp = defaults.double(forKey: destination.connectedAtKey) > 0
let hasConnection: Bool
switch destination {
case .claudeCode, .codex, .openclaw, .hermes:
hasConnection = hasLocalMCPConnection
case .claude:
hasConnection = exportedCount > 0 || hasConnectedTimestamp || hasLocalMCPConnection
case .chatgpt:
// A copied memory pack is not an OAuth authorization. ChatGPT's status
// is only changed by the provider-backed grant refresh below.
hasConnection = hasConnectedTimestamp || hasLocalMCPConnection
case .notion, .obsidian, .gemini, .agents:
hasConnection = exportedCount > 0 || hasConnectedTimestamp || hasLocalMCPConnection
}
let isConfigured: Bool
switch destination {
case .obsidian:
isConfigured = !(defaults.string(forKey: destination.obsidianVaultPathKey) ?? "").isEmpty
case .agents:
isConfigured =
hasStoredMCPKey && LocalAgentAPISettings.isEnabled
&& LocalAgentAPISettings.storedToken() != nil
case .claudeCode, .codex, .openclaw, .hermes:
isConfigured = hasConnection
case .chatgpt, .claude:
isConfigured = hasConnection
case .notion, .gemini:
isConfigured = destination == .notion ? NotionMCPConnector.shared.isConnected : exportedCount > 0
}
return MemoryExportStatus(
exportedCount: exportedCount,
lastExportedAt: lastExportedAt,
detailText: detailText,
isConfigured: isConfigured,
hasConnection: hasConnection
)
}
func allStatuses() -> [MemoryExportDestination: MemoryExportStatus] {
let localConnections = MemoryExportConnectionDetector.scanLocalMCPConnections(matchingKey: storedMCPKey())
return Dictionary(
lastWriteWins: MemoryExportDestination.allCases.map { destination in
(destination, status(for: destination, localMCPConnections: localConnections))
})
}
/// Refreshes the authoritative connection state for a cloud OAuth connector
/// (ChatGPT/Claude) after the user authorizes in the browser — only the backend
/// grant list knows the truth. Network failures intentionally retain the last
/// known state rather than presenting an authorization as revoked.
func refreshCloudGrantConnectionStatus(for destination: MemoryExportDestination) async -> MemoryExportStatus {
let clientIDs = destination.cloudOAuthGrantClientIDs
guard !clientIDs.isEmpty else { return status(for: destination) }
do {
let response: OAuthGrantsResponse = try await APIClient.shared.get(
"v1/mcp/oauth/grants", includeBYOK: false)
let isAuthorized = response.grants.contains { clientIDs.contains($0.clientID) && $0.isActive }
if isAuthorized {
defaults.set(Date().timeIntervalSince1970, forKey: destination.connectedAtKey)
defaults.set("Authorized through \(destination.title)", forKey: destination.detailKey)
} else {
defaults.removeObject(forKey: destination.connectedAtKey)
defaults.removeObject(forKey: destination.detailKey)
}
} catch {
log("MemoryExportService: \(destination.title) OAuth grant refresh failed: \(error.localizedDescription)")
}
return status(for: destination)
}
func notionConfiguration() -> (token: String, parentPageID: String) {
(
defaults.string(forKey: MemoryExportDestination.notion.notionTokenKey) ?? "",
defaults.string(forKey: MemoryExportDestination.notion.notionParentPageKey) ?? ""
)
}
func obsidianVaultPath() -> String {
defaults.string(forKey: MemoryExportDestination.obsidian.obsidianVaultPathKey) ?? ""
}
// MARK: - MCP key
nonisolated var hasStoredMCPKey: Bool {
let defaults = UserDefaults.standard
guard
let userId = Self.normalizedDefaultsString(defaults.string(forKey: Self.authUserIDDefaultsKey)),
let ownerUserId = Self.normalizedDefaultsString(defaults.string(forKey: Self.mcpKeyOwnerDefaultsKey)),
ownerUserId == userId
else {
return false
}
return Self.normalizedDefaultsString(defaults.string(forKey: Self.mcpKeyDefaultsKey)) != nil
}
func storedMCPKey() -> String? {
guard
let userId = currentAuthUserId(),
let ownerUserId = Self.normalizedDefaultsString(defaults.string(forKey: Self.mcpKeyOwnerDefaultsKey)),
ownerUserId == userId
else {
return nil
}
return Self.normalizedDefaultsString(defaults.string(forKey: Self.mcpKeyDefaultsKey))
}
/// Returns the cached MCP key, minting a fresh one via the backend on first use.
func ensureMCPKey() async throws -> String {
if let existing = storedMCPKey() {
return existing
}
let ownerUserId = try requireCurrentAuthUserId()
if let inFlight = mcpKeyWarmTask {
if inFlight.ownerUserId == ownerUserId {
return try await finishMCPKeyTask(inFlight.task, id: inFlight.id, ownerUserId: ownerUserId)
}
inFlight.task.cancel()
mcpKeyWarmTask = nil
}
let task = Task<String, Error> {
try await APIClient.shared.createMCPKey(name: "Omi Desktop")
}
let id = UUID()
mcpKeyWarmTask = (ownerUserId, id, task)
return try await finishMCPKeyTask(task, id: id, ownerUserId: ownerUserId)
}
/// Returns the key for a user-triggered local connector setup. Uses an
/// existing cached key or in-flight warmup first, and mints only when warmup
/// did not prepare a key in time.
func mcpKeyForLocalConnectorSetup() async throws -> String {
if let existing = storedMCPKey() {
return existing
}
let ownerUserId = try requireCurrentAuthUserId()
if let inFlight = mcpKeyWarmTask, inFlight.ownerUserId == ownerUserId {
return try await finishMCPKeyTask(inFlight.task, id: inFlight.id, ownerUserId: ownerUserId)
}
return try await ensureMCPKey()
}
func warmMCPKeyForCurrentUser() async {
do {
_ = try await ensureMCPKey()
log("MemoryExportService: hosted MCP key ready for current user")
} catch {
log("MemoryExportService: hosted MCP key warmup failed: \(error.localizedDescription)")
}
}
/// Mint a fresh hosted MCP key and make future setup prompts use it.
func createNewMCPKey() async throws -> String {
let ownerUserId = try requireCurrentAuthUserId()
mcpKeyWarmTask?.task.cancel()
mcpKeyWarmTask = nil
let key = try await APIClient.shared.createMCPKey(name: "Omi Desktop")
storeMCPKey(key, ownerUserId: ownerUserId)
return key
}
private func finishMCPKeyTask(
_ task: Task<String, Error>,