basic-memory 0.7.0__py3-none-any.whl → 0.17.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of basic-memory might be problematic. Click here for more details.

Files changed (195) hide show
  1. basic_memory/__init__.py +5 -1
  2. basic_memory/alembic/alembic.ini +119 -0
  3. basic_memory/alembic/env.py +130 -20
  4. basic_memory/alembic/migrations.py +4 -9
  5. basic_memory/alembic/versions/314f1ea54dc4_add_postgres_full_text_search_support_.py +131 -0
  6. basic_memory/alembic/versions/502b60eaa905_remove_required_from_entity_permalink.py +51 -0
  7. basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +120 -0
  8. basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +112 -0
  9. basic_memory/alembic/versions/6830751f5fb6_merge_multiple_heads.py +24 -0
  10. basic_memory/alembic/versions/9d9c1cb7d8f5_add_mtime_and_size_columns_to_entity_.py +49 -0
  11. basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +49 -0
  12. basic_memory/alembic/versions/a2b3c4d5e6f7_add_search_index_entity_cascade.py +56 -0
  13. basic_memory/alembic/versions/b3c3938bacdb_relation_to_name_unique_index.py +44 -0
  14. basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +113 -0
  15. basic_memory/alembic/versions/e7e1f4367280_add_scan_watermark_tracking_to_project.py +37 -0
  16. basic_memory/alembic/versions/f8a9b2c3d4e5_add_pg_trgm_for_fuzzy_link_resolution.py +239 -0
  17. basic_memory/alembic/versions/g9a0b3c4d5e6_add_external_id_to_project_and_entity.py +173 -0
  18. basic_memory/api/app.py +87 -20
  19. basic_memory/api/container.py +133 -0
  20. basic_memory/api/routers/__init__.py +4 -1
  21. basic_memory/api/routers/directory_router.py +84 -0
  22. basic_memory/api/routers/importer_router.py +152 -0
  23. basic_memory/api/routers/knowledge_router.py +180 -23
  24. basic_memory/api/routers/management_router.py +80 -0
  25. basic_memory/api/routers/memory_router.py +9 -64
  26. basic_memory/api/routers/project_router.py +460 -0
  27. basic_memory/api/routers/prompt_router.py +260 -0
  28. basic_memory/api/routers/resource_router.py +136 -11
  29. basic_memory/api/routers/search_router.py +5 -5
  30. basic_memory/api/routers/utils.py +169 -0
  31. basic_memory/api/template_loader.py +292 -0
  32. basic_memory/api/v2/__init__.py +35 -0
  33. basic_memory/api/v2/routers/__init__.py +21 -0
  34. basic_memory/api/v2/routers/directory_router.py +93 -0
  35. basic_memory/api/v2/routers/importer_router.py +181 -0
  36. basic_memory/api/v2/routers/knowledge_router.py +427 -0
  37. basic_memory/api/v2/routers/memory_router.py +130 -0
  38. basic_memory/api/v2/routers/project_router.py +359 -0
  39. basic_memory/api/v2/routers/prompt_router.py +269 -0
  40. basic_memory/api/v2/routers/resource_router.py +286 -0
  41. basic_memory/api/v2/routers/search_router.py +73 -0
  42. basic_memory/cli/app.py +80 -10
  43. basic_memory/cli/auth.py +300 -0
  44. basic_memory/cli/commands/__init__.py +15 -2
  45. basic_memory/cli/commands/cloud/__init__.py +6 -0
  46. basic_memory/cli/commands/cloud/api_client.py +127 -0
  47. basic_memory/cli/commands/cloud/bisync_commands.py +110 -0
  48. basic_memory/cli/commands/cloud/cloud_utils.py +108 -0
  49. basic_memory/cli/commands/cloud/core_commands.py +195 -0
  50. basic_memory/cli/commands/cloud/rclone_commands.py +397 -0
  51. basic_memory/cli/commands/cloud/rclone_config.py +110 -0
  52. basic_memory/cli/commands/cloud/rclone_installer.py +263 -0
  53. basic_memory/cli/commands/cloud/upload.py +240 -0
  54. basic_memory/cli/commands/cloud/upload_command.py +124 -0
  55. basic_memory/cli/commands/command_utils.py +99 -0
  56. basic_memory/cli/commands/db.py +87 -12
  57. basic_memory/cli/commands/format.py +198 -0
  58. basic_memory/cli/commands/import_chatgpt.py +47 -223
  59. basic_memory/cli/commands/import_claude_conversations.py +48 -171
  60. basic_memory/cli/commands/import_claude_projects.py +53 -160
  61. basic_memory/cli/commands/import_memory_json.py +55 -111
  62. basic_memory/cli/commands/mcp.py +67 -11
  63. basic_memory/cli/commands/project.py +889 -0
  64. basic_memory/cli/commands/status.py +52 -34
  65. basic_memory/cli/commands/telemetry.py +81 -0
  66. basic_memory/cli/commands/tool.py +341 -0
  67. basic_memory/cli/container.py +84 -0
  68. basic_memory/cli/main.py +14 -6
  69. basic_memory/config.py +580 -26
  70. basic_memory/db.py +285 -28
  71. basic_memory/deps/__init__.py +293 -0
  72. basic_memory/deps/config.py +26 -0
  73. basic_memory/deps/db.py +56 -0
  74. basic_memory/deps/importers.py +200 -0
  75. basic_memory/deps/projects.py +238 -0
  76. basic_memory/deps/repositories.py +179 -0
  77. basic_memory/deps/services.py +480 -0
  78. basic_memory/deps.py +16 -185
  79. basic_memory/file_utils.py +318 -54
  80. basic_memory/ignore_utils.py +297 -0
  81. basic_memory/importers/__init__.py +27 -0
  82. basic_memory/importers/base.py +100 -0
  83. basic_memory/importers/chatgpt_importer.py +245 -0
  84. basic_memory/importers/claude_conversations_importer.py +192 -0
  85. basic_memory/importers/claude_projects_importer.py +184 -0
  86. basic_memory/importers/memory_json_importer.py +128 -0
  87. basic_memory/importers/utils.py +61 -0
  88. basic_memory/markdown/entity_parser.py +182 -23
  89. basic_memory/markdown/markdown_processor.py +70 -7
  90. basic_memory/markdown/plugins.py +43 -23
  91. basic_memory/markdown/schemas.py +1 -1
  92. basic_memory/markdown/utils.py +38 -14
  93. basic_memory/mcp/async_client.py +135 -4
  94. basic_memory/mcp/clients/__init__.py +28 -0
  95. basic_memory/mcp/clients/directory.py +70 -0
  96. basic_memory/mcp/clients/knowledge.py +176 -0
  97. basic_memory/mcp/clients/memory.py +120 -0
  98. basic_memory/mcp/clients/project.py +89 -0
  99. basic_memory/mcp/clients/resource.py +71 -0
  100. basic_memory/mcp/clients/search.py +65 -0
  101. basic_memory/mcp/container.py +110 -0
  102. basic_memory/mcp/project_context.py +155 -0
  103. basic_memory/mcp/prompts/__init__.py +19 -0
  104. basic_memory/mcp/prompts/ai_assistant_guide.py +70 -0
  105. basic_memory/mcp/prompts/continue_conversation.py +62 -0
  106. basic_memory/mcp/prompts/recent_activity.py +188 -0
  107. basic_memory/mcp/prompts/search.py +57 -0
  108. basic_memory/mcp/prompts/utils.py +162 -0
  109. basic_memory/mcp/resources/ai_assistant_guide.md +283 -0
  110. basic_memory/mcp/resources/project_info.py +71 -0
  111. basic_memory/mcp/server.py +61 -9
  112. basic_memory/mcp/tools/__init__.py +33 -21
  113. basic_memory/mcp/tools/build_context.py +120 -0
  114. basic_memory/mcp/tools/canvas.py +152 -0
  115. basic_memory/mcp/tools/chatgpt_tools.py +190 -0
  116. basic_memory/mcp/tools/delete_note.py +249 -0
  117. basic_memory/mcp/tools/edit_note.py +325 -0
  118. basic_memory/mcp/tools/list_directory.py +157 -0
  119. basic_memory/mcp/tools/move_note.py +549 -0
  120. basic_memory/mcp/tools/project_management.py +204 -0
  121. basic_memory/mcp/tools/read_content.py +281 -0
  122. basic_memory/mcp/tools/read_note.py +265 -0
  123. basic_memory/mcp/tools/recent_activity.py +528 -0
  124. basic_memory/mcp/tools/search.py +377 -24
  125. basic_memory/mcp/tools/utils.py +402 -16
  126. basic_memory/mcp/tools/view_note.py +78 -0
  127. basic_memory/mcp/tools/write_note.py +230 -0
  128. basic_memory/models/__init__.py +3 -2
  129. basic_memory/models/knowledge.py +82 -17
  130. basic_memory/models/project.py +93 -0
  131. basic_memory/models/search.py +68 -8
  132. basic_memory/project_resolver.py +222 -0
  133. basic_memory/repository/__init__.py +2 -0
  134. basic_memory/repository/entity_repository.py +437 -8
  135. basic_memory/repository/observation_repository.py +36 -3
  136. basic_memory/repository/postgres_search_repository.py +451 -0
  137. basic_memory/repository/project_info_repository.py +10 -0
  138. basic_memory/repository/project_repository.py +140 -0
  139. basic_memory/repository/relation_repository.py +79 -4
  140. basic_memory/repository/repository.py +148 -29
  141. basic_memory/repository/search_index_row.py +95 -0
  142. basic_memory/repository/search_repository.py +79 -268
  143. basic_memory/repository/search_repository_base.py +241 -0
  144. basic_memory/repository/sqlite_search_repository.py +437 -0
  145. basic_memory/runtime.py +61 -0
  146. basic_memory/schemas/__init__.py +22 -9
  147. basic_memory/schemas/base.py +131 -12
  148. basic_memory/schemas/cloud.py +50 -0
  149. basic_memory/schemas/directory.py +31 -0
  150. basic_memory/schemas/importer.py +35 -0
  151. basic_memory/schemas/memory.py +194 -25
  152. basic_memory/schemas/project_info.py +213 -0
  153. basic_memory/schemas/prompt.py +90 -0
  154. basic_memory/schemas/request.py +56 -2
  155. basic_memory/schemas/response.py +85 -28
  156. basic_memory/schemas/search.py +36 -35
  157. basic_memory/schemas/sync_report.py +72 -0
  158. basic_memory/schemas/v2/__init__.py +27 -0
  159. basic_memory/schemas/v2/entity.py +133 -0
  160. basic_memory/schemas/v2/resource.py +47 -0
  161. basic_memory/services/__init__.py +2 -1
  162. basic_memory/services/context_service.py +451 -138
  163. basic_memory/services/directory_service.py +310 -0
  164. basic_memory/services/entity_service.py +636 -71
  165. basic_memory/services/exceptions.py +21 -0
  166. basic_memory/services/file_service.py +402 -33
  167. basic_memory/services/initialization.py +216 -0
  168. basic_memory/services/link_resolver.py +50 -56
  169. basic_memory/services/project_service.py +888 -0
  170. basic_memory/services/search_service.py +232 -37
  171. basic_memory/sync/__init__.py +4 -2
  172. basic_memory/sync/background_sync.py +26 -0
  173. basic_memory/sync/coordinator.py +160 -0
  174. basic_memory/sync/sync_service.py +1200 -109
  175. basic_memory/sync/watch_service.py +432 -135
  176. basic_memory/telemetry.py +249 -0
  177. basic_memory/templates/prompts/continue_conversation.hbs +110 -0
  178. basic_memory/templates/prompts/search.hbs +101 -0
  179. basic_memory/utils.py +407 -54
  180. basic_memory-0.17.4.dist-info/METADATA +617 -0
  181. basic_memory-0.17.4.dist-info/RECORD +193 -0
  182. {basic_memory-0.7.0.dist-info → basic_memory-0.17.4.dist-info}/WHEEL +1 -1
  183. {basic_memory-0.7.0.dist-info → basic_memory-0.17.4.dist-info}/entry_points.txt +1 -0
  184. basic_memory/alembic/README +0 -1
  185. basic_memory/cli/commands/sync.py +0 -206
  186. basic_memory/cli/commands/tools.py +0 -157
  187. basic_memory/mcp/tools/knowledge.py +0 -68
  188. basic_memory/mcp/tools/memory.py +0 -170
  189. basic_memory/mcp/tools/notes.py +0 -202
  190. basic_memory/schemas/discovery.py +0 -28
  191. basic_memory/sync/file_change_scanner.py +0 -158
  192. basic_memory/sync/utils.py +0 -31
  193. basic_memory-0.7.0.dist-info/METADATA +0 -378
  194. basic_memory-0.7.0.dist-info/RECORD +0 -82
  195. {basic_memory-0.7.0.dist-info → basic_memory-0.17.4.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,300 @@
1
+ """WorkOS OAuth Device Authorization for CLI."""
2
+
3
+ import base64
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import secrets
8
+ import time
9
+ import webbrowser
10
+ from contextlib import asynccontextmanager
11
+ from collections.abc import AsyncIterator, Callable
12
+ from typing import AsyncContextManager
13
+
14
+ import httpx
15
+ from rich.console import Console
16
+
17
+ from basic_memory.config import ConfigManager
18
+
19
+ console = Console()
20
+
21
+
22
+ class CLIAuth:
23
+ """Handles WorkOS OAuth Device Authorization for CLI tools."""
24
+
25
+ def __init__(
26
+ self,
27
+ client_id: str,
28
+ authkit_domain: str,
29
+ http_client_factory: Callable[[], AsyncContextManager[httpx.AsyncClient]] | None = None,
30
+ ):
31
+ self.client_id = client_id
32
+ self.authkit_domain = authkit_domain
33
+ app_config = ConfigManager().config
34
+ # Store tokens in data dir
35
+ self.token_file = app_config.data_dir_path / "basic-memory-cloud.json"
36
+ # PKCE parameters
37
+ self.code_verifier = None
38
+ self.code_challenge = None
39
+ self._http_client_factory = http_client_factory
40
+
41
+ @asynccontextmanager
42
+ async def _get_http_client(self) -> AsyncIterator[httpx.AsyncClient]:
43
+ """Create an AsyncClient, optionally via injected factory.
44
+
45
+ Why: enables reliable tests without monkeypatching httpx internals while
46
+ still using real httpx request/response objects.
47
+ """
48
+ if self._http_client_factory:
49
+ async with self._http_client_factory() as client:
50
+ yield client
51
+ else:
52
+ async with httpx.AsyncClient() as client:
53
+ yield client
54
+
55
+ def generate_pkce_pair(self) -> tuple[str, str]:
56
+ """Generate PKCE code verifier and challenge."""
57
+ # Generate code verifier (43-128 characters)
58
+ code_verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).decode("utf-8")
59
+ code_verifier = code_verifier.rstrip("=")
60
+
61
+ # Generate code challenge (SHA256 hash of verifier)
62
+ challenge_bytes = hashlib.sha256(code_verifier.encode("utf-8")).digest()
63
+ code_challenge = base64.urlsafe_b64encode(challenge_bytes).decode("utf-8")
64
+ code_challenge = code_challenge.rstrip("=")
65
+
66
+ return code_verifier, code_challenge
67
+
68
+ async def request_device_authorization(self) -> dict | None:
69
+ """Request device authorization from WorkOS with PKCE."""
70
+ device_auth_url = f"{self.authkit_domain}/oauth2/device_authorization"
71
+
72
+ # Generate PKCE pair
73
+ self.code_verifier, self.code_challenge = self.generate_pkce_pair()
74
+
75
+ data = {
76
+ "client_id": self.client_id,
77
+ "scope": "openid profile email offline_access",
78
+ "code_challenge": self.code_challenge,
79
+ "code_challenge_method": "S256",
80
+ }
81
+
82
+ try:
83
+ async with self._get_http_client() as client:
84
+ response = await client.post(device_auth_url, data=data)
85
+
86
+ if response.status_code == 200:
87
+ return response.json()
88
+ else:
89
+ console.print(
90
+ f"[red]Device authorization failed: {response.status_code} - {response.text}[/red]"
91
+ )
92
+ return None
93
+ except Exception as e:
94
+ console.print(f"[red]Device authorization error: {e}[/red]")
95
+ return None
96
+
97
+ def display_user_instructions(self, device_response: dict) -> None:
98
+ """Display user instructions for device authorization."""
99
+ user_code = device_response["user_code"]
100
+ verification_uri = device_response["verification_uri"]
101
+ verification_uri_complete = device_response.get("verification_uri_complete")
102
+
103
+ console.print("\n[bold blue]Authentication Required[/bold blue]")
104
+ console.print("\nTo authenticate, please visit:")
105
+ console.print(f"[bold cyan]{verification_uri}[/bold cyan]")
106
+ console.print(f"\nAnd enter this code: [bold yellow]{user_code}[/bold yellow]")
107
+
108
+ if verification_uri_complete:
109
+ console.print("\nOr for one-click access, visit:")
110
+ console.print(f"[bold green]{verification_uri_complete}[/bold green]")
111
+
112
+ # Try to open browser automatically
113
+ try:
114
+ console.print("\n[dim]Opening browser automatically...[/dim]")
115
+ webbrowser.open(verification_uri_complete)
116
+ except Exception:
117
+ pass # Silently fail if browser can't be opened
118
+
119
+ console.print("\n[dim]Waiting for you to complete authentication in your browser...[/dim]")
120
+
121
+ async def poll_for_token(self, device_code: str, interval: int = 5) -> dict | None:
122
+ """Poll the token endpoint until user completes authentication."""
123
+ token_url = f"{self.authkit_domain}/oauth2/token"
124
+
125
+ data = {
126
+ "client_id": self.client_id,
127
+ "device_code": device_code,
128
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
129
+ "code_verifier": self.code_verifier,
130
+ }
131
+
132
+ max_attempts = 60 # 5 minutes with 5-second intervals
133
+ current_interval = interval
134
+
135
+ for _attempt in range(max_attempts):
136
+ try:
137
+ async with self._get_http_client() as client:
138
+ response = await client.post(token_url, data=data)
139
+
140
+ if response.status_code == 200:
141
+ return response.json()
142
+
143
+ # Parse error response
144
+ try:
145
+ error_data = response.json()
146
+ error = error_data.get("error")
147
+ except Exception:
148
+ error = "unknown_error"
149
+
150
+ if error == "authorization_pending":
151
+ # User hasn't completed auth yet, keep polling
152
+ pass
153
+ elif error == "slow_down":
154
+ # Increase polling interval
155
+ current_interval += 5
156
+ console.print("[yellow]Slowing down polling rate...[/yellow]")
157
+ elif error == "access_denied":
158
+ console.print("[red]Authentication was denied by user[/red]")
159
+ return None
160
+ elif error == "expired_token":
161
+ console.print("[red]Device code has expired. Please try again.[/red]")
162
+ return None
163
+ else:
164
+ console.print(f"[red]Token polling error: {error}[/red]")
165
+ return None
166
+
167
+ except Exception as e:
168
+ console.print(f"[red]Token polling request error: {e}[/red]")
169
+
170
+ # Wait before next poll
171
+ await self._async_sleep(current_interval)
172
+
173
+ console.print("[red]Authentication timeout. Please try again.[/red]")
174
+ return None
175
+
176
+ async def _async_sleep(self, seconds: int) -> None:
177
+ """Async sleep utility."""
178
+ import asyncio
179
+
180
+ await asyncio.sleep(seconds)
181
+
182
+ def save_tokens(self, tokens: dict) -> None:
183
+ """Save tokens to project root as .bm-auth.json."""
184
+ token_data = {
185
+ "access_token": tokens["access_token"],
186
+ "refresh_token": tokens.get("refresh_token"),
187
+ "expires_at": int(time.time()) + tokens.get("expires_in", 3600),
188
+ "token_type": tokens.get("token_type", "Bearer"),
189
+ }
190
+
191
+ with open(self.token_file, "w") as f:
192
+ json.dump(token_data, f, indent=2)
193
+
194
+ # Secure the token file
195
+ os.chmod(self.token_file, 0o600)
196
+
197
+ console.print(f"[green]Tokens saved to {self.token_file}[/green]")
198
+
199
+ def load_tokens(self) -> dict | None:
200
+ """Load tokens from .bm-auth.json file."""
201
+ if not self.token_file.exists():
202
+ return None
203
+
204
+ try:
205
+ with open(self.token_file) as f:
206
+ return json.load(f)
207
+ except (OSError, json.JSONDecodeError):
208
+ return None
209
+
210
+ def is_token_valid(self, tokens: dict) -> bool:
211
+ """Check if stored token is still valid."""
212
+ expires_at = tokens.get("expires_at", 0)
213
+ # Add 60 second buffer for clock skew
214
+ return time.time() < (expires_at - 60)
215
+
216
+ async def refresh_token(self, refresh_token: str) -> dict | None:
217
+ """Refresh access token using refresh token."""
218
+ token_url = f"{self.authkit_domain}/oauth2/token"
219
+
220
+ data = {
221
+ "client_id": self.client_id,
222
+ "grant_type": "refresh_token",
223
+ "refresh_token": refresh_token,
224
+ }
225
+
226
+ try:
227
+ async with self._get_http_client() as client:
228
+ response = await client.post(token_url, data=data)
229
+
230
+ if response.status_code == 200:
231
+ return response.json()
232
+ else:
233
+ console.print(
234
+ f"[red]Token refresh failed: {response.status_code} - {response.text}[/red]"
235
+ )
236
+ return None
237
+ except Exception as e:
238
+ console.print(f"[red]Token refresh error: {e}[/red]")
239
+ return None
240
+
241
+ async def get_valid_token(self) -> str | None:
242
+ """Get valid access token, refresh if needed."""
243
+ tokens = self.load_tokens()
244
+ if not tokens:
245
+ return None
246
+
247
+ if self.is_token_valid(tokens):
248
+ return tokens["access_token"]
249
+
250
+ # Token expired - try to refresh if we have a refresh token
251
+ refresh_token = tokens.get("refresh_token")
252
+ if refresh_token:
253
+ console.print("[yellow]Access token expired, refreshing...[/yellow]")
254
+
255
+ new_tokens = await self.refresh_token(refresh_token)
256
+ if new_tokens:
257
+ # Save new tokens (may include rotated refresh token)
258
+ self.save_tokens(new_tokens)
259
+ console.print("[green]Token refreshed successfully[/green]")
260
+ return new_tokens["access_token"]
261
+ else:
262
+ console.print("[yellow]Token refresh failed. Please run 'login' again.[/yellow]")
263
+ return None
264
+ else:
265
+ console.print("[yellow]No refresh token available. Please run 'login' again.[/yellow]")
266
+ return None
267
+
268
+ async def login(self) -> bool:
269
+ """Perform OAuth Device Authorization login flow."""
270
+ console.print("[blue]Initiating authentication...[/blue]")
271
+
272
+ # Step 1: Request device authorization
273
+ device_response = await self.request_device_authorization()
274
+ if not device_response:
275
+ return False
276
+
277
+ # Step 2: Display user instructions
278
+ self.display_user_instructions(device_response)
279
+
280
+ # Step 3: Poll for token
281
+ device_code = device_response["device_code"]
282
+ interval = device_response.get("interval", 5)
283
+
284
+ tokens = await self.poll_for_token(device_code, interval)
285
+ if not tokens:
286
+ return False
287
+
288
+ # Step 4: Save tokens
289
+ self.save_tokens(tokens)
290
+
291
+ console.print("\n[green]Successfully authenticated with Basic Memory Cloud![/green]")
292
+ return True
293
+
294
+ def logout(self) -> None:
295
+ """Remove stored authentication tokens."""
296
+ if self.token_file.exists():
297
+ self.token_file.unlink()
298
+ console.print("[green]Logged out successfully[/green]")
299
+ else:
300
+ console.print("[yellow]No stored authentication found[/yellow]")
@@ -1,5 +1,18 @@
1
1
  """CLI commands for basic-memory."""
2
2
 
3
- from . import status, sync, db, import_memory_json, mcp
3
+ from . import status, db, import_memory_json, mcp, import_claude_conversations
4
+ from . import import_claude_projects, import_chatgpt, tool, project, format, telemetry
4
5
 
5
- __all__ = ["status", "sync", "db", "import_memory_json", "mcp"]
6
+ __all__ = [
7
+ "status",
8
+ "db",
9
+ "import_memory_json",
10
+ "mcp",
11
+ "import_claude_conversations",
12
+ "import_claude_projects",
13
+ "import_chatgpt",
14
+ "tool",
15
+ "project",
16
+ "format",
17
+ "telemetry",
18
+ ]
@@ -0,0 +1,6 @@
1
+ """Cloud commands package."""
2
+
3
+ # Import all commands to register them with typer
4
+ from basic_memory.cli.commands.cloud.core_commands import * # noqa: F401,F403
5
+ from basic_memory.cli.commands.cloud.api_client import get_authenticated_headers, get_cloud_config # noqa: F401
6
+ from basic_memory.cli.commands.cloud.upload_command import * # noqa: F401,F403
@@ -0,0 +1,127 @@
1
+ """Cloud API client utilities."""
2
+
3
+ from collections.abc import AsyncIterator
4
+ from typing import Optional
5
+ from contextlib import asynccontextmanager
6
+ from typing import AsyncContextManager, Callable
7
+
8
+ import httpx
9
+ import typer
10
+ from rich.console import Console
11
+
12
+ from basic_memory.cli.auth import CLIAuth
13
+ from basic_memory.config import ConfigManager
14
+
15
+ console = Console()
16
+
17
+ HttpClientFactory = Callable[[], AsyncContextManager[httpx.AsyncClient]]
18
+
19
+
20
+ class CloudAPIError(Exception):
21
+ """Exception raised for cloud API errors."""
22
+
23
+ def __init__(
24
+ self, message: str, status_code: Optional[int] = None, detail: Optional[dict] = None
25
+ ):
26
+ super().__init__(message)
27
+ self.status_code = status_code
28
+ self.detail = detail or {}
29
+
30
+
31
+ class SubscriptionRequiredError(CloudAPIError):
32
+ """Exception raised when user needs an active subscription."""
33
+
34
+ def __init__(self, message: str, subscribe_url: str):
35
+ super().__init__(message, status_code=403, detail={"error": "subscription_required"})
36
+ self.subscribe_url = subscribe_url
37
+
38
+
39
+ def get_cloud_config() -> tuple[str, str, str]:
40
+ """Get cloud OAuth configuration from config."""
41
+ config_manager = ConfigManager()
42
+ config = config_manager.config
43
+ return config.cloud_client_id, config.cloud_domain, config.cloud_host
44
+
45
+
46
+ async def get_authenticated_headers(auth: CLIAuth | None = None) -> dict[str, str]:
47
+ """
48
+ Get authentication headers with JWT token.
49
+ handles jwt refresh if needed.
50
+ """
51
+ client_id, domain, _ = get_cloud_config()
52
+ auth_obj = auth or CLIAuth(client_id=client_id, authkit_domain=domain)
53
+ token = await auth_obj.get_valid_token()
54
+ if not token:
55
+ console.print("[red]Not authenticated. Please run 'basic-memory cloud login' first.[/red]")
56
+ raise typer.Exit(1)
57
+
58
+ return {"Authorization": f"Bearer {token}"}
59
+
60
+
61
+ @asynccontextmanager
62
+ async def _default_http_client(timeout: float) -> AsyncIterator[httpx.AsyncClient]:
63
+ async with httpx.AsyncClient(timeout=timeout) as client:
64
+ yield client
65
+
66
+
67
+ async def make_api_request(
68
+ method: str,
69
+ url: str,
70
+ headers: Optional[dict] = None,
71
+ json_data: Optional[dict] = None,
72
+ timeout: float = 30.0,
73
+ *,
74
+ auth: CLIAuth | None = None,
75
+ http_client_factory: HttpClientFactory | None = None,
76
+ ) -> httpx.Response:
77
+ """Make an API request to the cloud service."""
78
+ headers = headers or {}
79
+ auth_headers = await get_authenticated_headers(auth=auth)
80
+ headers.update(auth_headers)
81
+ # Add debug headers to help with compression issues
82
+ headers.setdefault("Accept-Encoding", "identity") # Disable compression for debugging
83
+
84
+ client_factory = http_client_factory or (lambda: _default_http_client(timeout))
85
+ async with client_factory() as client:
86
+ try:
87
+ response = await client.request(method=method, url=url, headers=headers, json=json_data)
88
+ response.raise_for_status()
89
+ return response
90
+ except httpx.HTTPError as e:
91
+ # Check if this is a response error with response details
92
+ if hasattr(e, "response") and e.response is not None: # pyright: ignore [reportAttributeAccessIssue]
93
+ response = e.response # type: ignore
94
+
95
+ # Try to parse error detail from response
96
+ error_detail = None
97
+ try:
98
+ error_detail = response.json()
99
+ except Exception:
100
+ # If JSON parsing fails, we'll handle it as a generic error
101
+ pass
102
+
103
+ # Check for subscription_required error (403)
104
+ if response.status_code == 403 and isinstance(error_detail, dict):
105
+ # Handle both FastAPI HTTPException format (nested under "detail")
106
+ # and direct format
107
+ detail_obj = error_detail.get("detail", error_detail)
108
+ if (
109
+ isinstance(detail_obj, dict)
110
+ and detail_obj.get("error") == "subscription_required"
111
+ ):
112
+ message = detail_obj.get("message", "Active subscription required")
113
+ subscribe_url = detail_obj.get(
114
+ "subscribe_url", "https://basicmemory.com/subscribe"
115
+ )
116
+ raise SubscriptionRequiredError(
117
+ message=message, subscribe_url=subscribe_url
118
+ ) from e
119
+
120
+ # Raise generic CloudAPIError with status code and detail
121
+ raise CloudAPIError(
122
+ f"API request failed: {e}",
123
+ status_code=response.status_code,
124
+ detail=error_detail if isinstance(error_detail, dict) else {},
125
+ ) from e
126
+
127
+ raise CloudAPIError(f"API request failed: {e}") from e
@@ -0,0 +1,110 @@
1
+ """Cloud bisync utility functions for Basic Memory CLI."""
2
+
3
+ from pathlib import Path
4
+
5
+ from basic_memory.cli.commands.cloud.api_client import make_api_request
6
+ from basic_memory.config import ConfigManager
7
+ from basic_memory.ignore_utils import create_default_bmignore, get_bmignore_path
8
+ from basic_memory.schemas.cloud import MountCredentials, TenantMountInfo
9
+
10
+
11
+ class BisyncError(Exception):
12
+ """Exception raised for bisync-related errors."""
13
+
14
+ pass
15
+
16
+
17
+ async def get_mount_info() -> TenantMountInfo:
18
+ """Get current tenant information from cloud API."""
19
+ try:
20
+ config_manager = ConfigManager()
21
+ config = config_manager.config
22
+ host_url = config.cloud_host.rstrip("/")
23
+
24
+ response = await make_api_request(method="GET", url=f"{host_url}/tenant/mount/info")
25
+
26
+ return TenantMountInfo.model_validate(response.json())
27
+ except Exception as e:
28
+ raise BisyncError(f"Failed to get tenant info: {e}") from e
29
+
30
+
31
+ async def generate_mount_credentials(tenant_id: str) -> MountCredentials:
32
+ """Generate scoped credentials for syncing."""
33
+ try:
34
+ config_manager = ConfigManager()
35
+ config = config_manager.config
36
+ host_url = config.cloud_host.rstrip("/")
37
+
38
+ response = await make_api_request(method="POST", url=f"{host_url}/tenant/mount/credentials")
39
+
40
+ return MountCredentials.model_validate(response.json())
41
+ except Exception as e:
42
+ raise BisyncError(f"Failed to generate credentials: {e}") from e
43
+
44
+
45
+ def convert_bmignore_to_rclone_filters() -> Path:
46
+ """Convert .bmignore patterns to rclone filter format.
47
+
48
+ Reads ~/.basic-memory/.bmignore (gitignore-style) and converts to
49
+ ~/.basic-memory/.bmignore.rclone (rclone filter format).
50
+
51
+ Only regenerates if .bmignore has been modified since last conversion.
52
+
53
+ Returns:
54
+ Path to converted rclone filter file
55
+ """
56
+ # Ensure .bmignore exists
57
+ create_default_bmignore()
58
+
59
+ bmignore_path = get_bmignore_path()
60
+ # Create rclone filter path: ~/.basic-memory/.bmignore -> ~/.basic-memory/.bmignore.rclone
61
+ rclone_filter_path = bmignore_path.parent / f"{bmignore_path.name}.rclone"
62
+
63
+ # Skip regeneration if rclone file is newer than bmignore
64
+ if rclone_filter_path.exists():
65
+ bmignore_mtime = bmignore_path.stat().st_mtime
66
+ rclone_mtime = rclone_filter_path.stat().st_mtime
67
+ if rclone_mtime >= bmignore_mtime:
68
+ return rclone_filter_path
69
+
70
+ # Read .bmignore patterns
71
+ patterns = []
72
+ try:
73
+ with bmignore_path.open("r", encoding="utf-8") as f:
74
+ for line in f:
75
+ line = line.strip()
76
+ # Keep comments and empty lines
77
+ if not line or line.startswith("#"):
78
+ patterns.append(line)
79
+ continue
80
+
81
+ # Convert gitignore pattern to rclone filter syntax
82
+ # gitignore: node_modules → rclone: - node_modules/**
83
+ # gitignore: *.pyc → rclone: - *.pyc
84
+ if "*" in line:
85
+ # Pattern already has wildcard, just add exclude prefix
86
+ patterns.append(f"- {line}")
87
+ else:
88
+ # Directory pattern - add /** for recursive exclude
89
+ patterns.append(f"- {line}/**")
90
+
91
+ except Exception:
92
+ # If we can't read the file, create a minimal filter
93
+ patterns = ["# Error reading .bmignore, using minimal filters", "- .git/**"]
94
+
95
+ # Write rclone filter file
96
+ rclone_filter_path.write_text("\n".join(patterns) + "\n")
97
+
98
+ return rclone_filter_path
99
+
100
+
101
+ def get_bisync_filter_path() -> Path:
102
+ """Get path to bisync filter file.
103
+
104
+ Uses ~/.basic-memory/.bmignore (converted to rclone format).
105
+ The file is automatically created with default patterns on first use.
106
+
107
+ Returns:
108
+ Path to rclone filter file
109
+ """
110
+ return convert_bmignore_to_rclone_filters()
@@ -0,0 +1,108 @@
1
+ """Shared utilities for cloud operations."""
2
+
3
+ from basic_memory.cli.commands.cloud.api_client import make_api_request
4
+ from basic_memory.config import ConfigManager
5
+ from basic_memory.schemas.cloud import (
6
+ CloudProjectList,
7
+ CloudProjectCreateRequest,
8
+ CloudProjectCreateResponse,
9
+ )
10
+ from basic_memory.utils import generate_permalink
11
+
12
+
13
+ class CloudUtilsError(Exception):
14
+ """Exception raised for cloud utility errors."""
15
+
16
+ pass
17
+
18
+
19
+ async def fetch_cloud_projects(
20
+ *,
21
+ api_request=make_api_request,
22
+ ) -> CloudProjectList:
23
+ """Fetch list of projects from cloud API.
24
+
25
+ Returns:
26
+ CloudProjectList with projects from cloud
27
+ """
28
+ try:
29
+ config_manager = ConfigManager()
30
+ config = config_manager.config
31
+ host_url = config.cloud_host.rstrip("/")
32
+
33
+ response = await api_request(method="GET", url=f"{host_url}/proxy/projects/projects")
34
+
35
+ return CloudProjectList.model_validate(response.json())
36
+ except Exception as e:
37
+ raise CloudUtilsError(f"Failed to fetch cloud projects: {e}") from e
38
+
39
+
40
+ async def create_cloud_project(
41
+ project_name: str,
42
+ *,
43
+ api_request=make_api_request,
44
+ ) -> CloudProjectCreateResponse:
45
+ """Create a new project on cloud.
46
+
47
+ Args:
48
+ project_name: Name of project to create
49
+
50
+ Returns:
51
+ CloudProjectCreateResponse with project details from API
52
+ """
53
+ try:
54
+ config_manager = ConfigManager()
55
+ config = config_manager.config
56
+ host_url = config.cloud_host.rstrip("/")
57
+
58
+ # Use generate_permalink to ensure consistent naming
59
+ project_path = generate_permalink(project_name)
60
+
61
+ project_data = CloudProjectCreateRequest(
62
+ name=project_name,
63
+ path=project_path,
64
+ set_default=False,
65
+ )
66
+
67
+ response = await api_request(
68
+ method="POST",
69
+ url=f"{host_url}/proxy/projects/projects",
70
+ headers={"Content-Type": "application/json"},
71
+ json_data=project_data.model_dump(),
72
+ )
73
+
74
+ return CloudProjectCreateResponse.model_validate(response.json())
75
+ except Exception as e:
76
+ raise CloudUtilsError(f"Failed to create cloud project '{project_name}': {e}") from e
77
+
78
+
79
+ async def sync_project(project_name: str, force_full: bool = False) -> None:
80
+ """Trigger sync for a specific project on cloud.
81
+
82
+ Args:
83
+ project_name: Name of project to sync
84
+ force_full: If True, force a full scan bypassing watermark optimization
85
+ """
86
+ try:
87
+ from basic_memory.cli.commands.command_utils import run_sync
88
+
89
+ await run_sync(project=project_name, force_full=force_full)
90
+ except Exception as e:
91
+ raise CloudUtilsError(f"Failed to sync project '{project_name}': {e}") from e
92
+
93
+
94
+ async def project_exists(project_name: str, *, api_request=make_api_request) -> bool:
95
+ """Check if a project exists on cloud.
96
+
97
+ Args:
98
+ project_name: Name of project to check
99
+
100
+ Returns:
101
+ True if project exists, False otherwise
102
+ """
103
+ try:
104
+ projects = await fetch_cloud_projects(api_request=api_request)
105
+ project_names = {p.name for p in projects.projects}
106
+ return project_name in project_names
107
+ except Exception:
108
+ return False