basic-memory 0.2.12__py3-none-any.whl → 0.16.1__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.
- basic_memory/__init__.py +5 -1
- basic_memory/alembic/alembic.ini +119 -0
- basic_memory/alembic/env.py +27 -3
- basic_memory/alembic/migrations.py +4 -9
- basic_memory/alembic/versions/502b60eaa905_remove_required_from_entity_permalink.py +51 -0
- basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +108 -0
- basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +104 -0
- basic_memory/alembic/versions/9d9c1cb7d8f5_add_mtime_and_size_columns_to_entity_.py +49 -0
- basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +49 -0
- basic_memory/alembic/versions/b3c3938bacdb_relation_to_name_unique_index.py +44 -0
- basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +100 -0
- basic_memory/alembic/versions/e7e1f4367280_add_scan_watermark_tracking_to_project.py +37 -0
- basic_memory/api/app.py +63 -31
- basic_memory/api/routers/__init__.py +4 -1
- basic_memory/api/routers/directory_router.py +84 -0
- basic_memory/api/routers/importer_router.py +152 -0
- basic_memory/api/routers/knowledge_router.py +165 -28
- basic_memory/api/routers/management_router.py +80 -0
- basic_memory/api/routers/memory_router.py +28 -67
- basic_memory/api/routers/project_router.py +406 -0
- basic_memory/api/routers/prompt_router.py +260 -0
- basic_memory/api/routers/resource_router.py +219 -14
- basic_memory/api/routers/search_router.py +21 -13
- basic_memory/api/routers/utils.py +130 -0
- basic_memory/api/template_loader.py +292 -0
- basic_memory/cli/app.py +52 -1
- basic_memory/cli/auth.py +277 -0
- basic_memory/cli/commands/__init__.py +13 -2
- basic_memory/cli/commands/cloud/__init__.py +6 -0
- basic_memory/cli/commands/cloud/api_client.py +112 -0
- basic_memory/cli/commands/cloud/bisync_commands.py +110 -0
- basic_memory/cli/commands/cloud/cloud_utils.py +101 -0
- basic_memory/cli/commands/cloud/core_commands.py +195 -0
- basic_memory/cli/commands/cloud/rclone_commands.py +301 -0
- basic_memory/cli/commands/cloud/rclone_config.py +110 -0
- basic_memory/cli/commands/cloud/rclone_installer.py +249 -0
- basic_memory/cli/commands/cloud/upload.py +233 -0
- basic_memory/cli/commands/cloud/upload_command.py +124 -0
- basic_memory/cli/commands/command_utils.py +51 -0
- basic_memory/cli/commands/db.py +26 -7
- basic_memory/cli/commands/import_chatgpt.py +83 -0
- basic_memory/cli/commands/import_claude_conversations.py +86 -0
- basic_memory/cli/commands/import_claude_projects.py +85 -0
- basic_memory/cli/commands/import_memory_json.py +35 -92
- basic_memory/cli/commands/mcp.py +84 -10
- basic_memory/cli/commands/project.py +876 -0
- basic_memory/cli/commands/status.py +47 -30
- basic_memory/cli/commands/tool.py +341 -0
- basic_memory/cli/main.py +13 -6
- basic_memory/config.py +481 -22
- basic_memory/db.py +192 -32
- basic_memory/deps.py +252 -22
- basic_memory/file_utils.py +113 -58
- basic_memory/ignore_utils.py +297 -0
- basic_memory/importers/__init__.py +27 -0
- basic_memory/importers/base.py +79 -0
- basic_memory/importers/chatgpt_importer.py +232 -0
- basic_memory/importers/claude_conversations_importer.py +177 -0
- basic_memory/importers/claude_projects_importer.py +148 -0
- basic_memory/importers/memory_json_importer.py +108 -0
- basic_memory/importers/utils.py +58 -0
- basic_memory/markdown/entity_parser.py +143 -23
- basic_memory/markdown/markdown_processor.py +3 -3
- basic_memory/markdown/plugins.py +39 -21
- basic_memory/markdown/schemas.py +1 -1
- basic_memory/markdown/utils.py +28 -13
- basic_memory/mcp/async_client.py +134 -4
- basic_memory/mcp/project_context.py +141 -0
- basic_memory/mcp/prompts/__init__.py +19 -0
- basic_memory/mcp/prompts/ai_assistant_guide.py +70 -0
- basic_memory/mcp/prompts/continue_conversation.py +62 -0
- basic_memory/mcp/prompts/recent_activity.py +188 -0
- basic_memory/mcp/prompts/search.py +57 -0
- basic_memory/mcp/prompts/utils.py +162 -0
- basic_memory/mcp/resources/ai_assistant_guide.md +283 -0
- basic_memory/mcp/resources/project_info.py +71 -0
- basic_memory/mcp/server.py +7 -13
- basic_memory/mcp/tools/__init__.py +33 -21
- basic_memory/mcp/tools/build_context.py +120 -0
- basic_memory/mcp/tools/canvas.py +130 -0
- basic_memory/mcp/tools/chatgpt_tools.py +187 -0
- basic_memory/mcp/tools/delete_note.py +225 -0
- basic_memory/mcp/tools/edit_note.py +320 -0
- basic_memory/mcp/tools/list_directory.py +167 -0
- basic_memory/mcp/tools/move_note.py +545 -0
- basic_memory/mcp/tools/project_management.py +200 -0
- basic_memory/mcp/tools/read_content.py +271 -0
- basic_memory/mcp/tools/read_note.py +255 -0
- basic_memory/mcp/tools/recent_activity.py +534 -0
- basic_memory/mcp/tools/search.py +369 -14
- basic_memory/mcp/tools/utils.py +374 -16
- basic_memory/mcp/tools/view_note.py +77 -0
- basic_memory/mcp/tools/write_note.py +207 -0
- basic_memory/models/__init__.py +3 -2
- basic_memory/models/knowledge.py +67 -15
- basic_memory/models/project.py +87 -0
- basic_memory/models/search.py +10 -6
- basic_memory/repository/__init__.py +2 -0
- basic_memory/repository/entity_repository.py +229 -7
- basic_memory/repository/observation_repository.py +35 -3
- basic_memory/repository/project_info_repository.py +10 -0
- basic_memory/repository/project_repository.py +103 -0
- basic_memory/repository/relation_repository.py +21 -2
- basic_memory/repository/repository.py +147 -29
- basic_memory/repository/search_repository.py +437 -59
- basic_memory/schemas/__init__.py +22 -9
- basic_memory/schemas/base.py +97 -8
- basic_memory/schemas/cloud.py +50 -0
- basic_memory/schemas/directory.py +30 -0
- basic_memory/schemas/importer.py +35 -0
- basic_memory/schemas/memory.py +188 -23
- basic_memory/schemas/project_info.py +211 -0
- basic_memory/schemas/prompt.py +90 -0
- basic_memory/schemas/request.py +57 -3
- basic_memory/schemas/response.py +9 -1
- basic_memory/schemas/search.py +33 -35
- basic_memory/schemas/sync_report.py +72 -0
- basic_memory/services/__init__.py +2 -1
- basic_memory/services/context_service.py +251 -106
- basic_memory/services/directory_service.py +295 -0
- basic_memory/services/entity_service.py +595 -60
- basic_memory/services/exceptions.py +21 -0
- basic_memory/services/file_service.py +284 -30
- basic_memory/services/initialization.py +191 -0
- basic_memory/services/link_resolver.py +50 -56
- basic_memory/services/project_service.py +863 -0
- basic_memory/services/search_service.py +172 -34
- basic_memory/sync/__init__.py +3 -2
- basic_memory/sync/background_sync.py +26 -0
- basic_memory/sync/sync_service.py +1176 -96
- basic_memory/sync/watch_service.py +412 -135
- basic_memory/templates/prompts/continue_conversation.hbs +110 -0
- basic_memory/templates/prompts/search.hbs +101 -0
- basic_memory/utils.py +388 -28
- basic_memory-0.16.1.dist-info/METADATA +493 -0
- basic_memory-0.16.1.dist-info/RECORD +148 -0
- {basic_memory-0.2.12.dist-info → basic_memory-0.16.1.dist-info}/entry_points.txt +1 -0
- basic_memory/alembic/README +0 -1
- basic_memory/cli/commands/sync.py +0 -203
- basic_memory/mcp/tools/knowledge.py +0 -56
- basic_memory/mcp/tools/memory.py +0 -151
- basic_memory/mcp/tools/notes.py +0 -122
- basic_memory/schemas/discovery.py +0 -28
- basic_memory/sync/file_change_scanner.py +0 -158
- basic_memory/sync/utils.py +0 -34
- basic_memory-0.2.12.dist-info/METADATA +0 -291
- basic_memory-0.2.12.dist-info/RECORD +0 -78
- {basic_memory-0.2.12.dist-info → basic_memory-0.16.1.dist-info}/WHEEL +0 -0
- {basic_memory-0.2.12.dist-info → basic_memory-0.16.1.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""Template loading and rendering utilities for the Basic Memory API.
|
|
2
|
+
|
|
3
|
+
This module handles the loading and rendering of Handlebars templates from the
|
|
4
|
+
templates directory, providing a consistent interface for all prompt-related
|
|
5
|
+
formatting needs.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import textwrap
|
|
9
|
+
from typing import Dict, Any, Optional, Callable
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import json
|
|
12
|
+
import datetime
|
|
13
|
+
|
|
14
|
+
import pybars
|
|
15
|
+
from loguru import logger
|
|
16
|
+
|
|
17
|
+
# Get the base path of the templates directory
|
|
18
|
+
TEMPLATES_DIR = Path(__file__).parent.parent / "templates"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# Custom helpers for Handlebars
|
|
22
|
+
def _date_helper(this, *args):
|
|
23
|
+
"""Format a date using the given format string."""
|
|
24
|
+
if len(args) < 1: # pragma: no cover
|
|
25
|
+
return ""
|
|
26
|
+
|
|
27
|
+
timestamp = args[0]
|
|
28
|
+
format_str = args[1] if len(args) > 1 else "%Y-%m-%d %H:%M"
|
|
29
|
+
|
|
30
|
+
if hasattr(timestamp, "strftime"):
|
|
31
|
+
result = timestamp.strftime(format_str)
|
|
32
|
+
elif isinstance(timestamp, str):
|
|
33
|
+
try:
|
|
34
|
+
dt = datetime.datetime.fromisoformat(timestamp)
|
|
35
|
+
result = dt.strftime(format_str)
|
|
36
|
+
except ValueError:
|
|
37
|
+
result = timestamp
|
|
38
|
+
else:
|
|
39
|
+
result = str(timestamp) # pragma: no cover
|
|
40
|
+
|
|
41
|
+
return pybars.strlist([result])
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _default_helper(this, *args):
|
|
45
|
+
"""Return a default value if the given value is None or empty."""
|
|
46
|
+
if len(args) < 2: # pragma: no cover
|
|
47
|
+
return ""
|
|
48
|
+
|
|
49
|
+
value = args[0]
|
|
50
|
+
default_value = args[1]
|
|
51
|
+
|
|
52
|
+
result = default_value if value is None or value == "" else value
|
|
53
|
+
# Use strlist for consistent handling of HTML escaping
|
|
54
|
+
return pybars.strlist([str(result)])
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _capitalize_helper(this, *args):
|
|
58
|
+
"""Capitalize the first letter of a string."""
|
|
59
|
+
if len(args) < 1: # pragma: no cover
|
|
60
|
+
return ""
|
|
61
|
+
|
|
62
|
+
text = args[0]
|
|
63
|
+
if not text or not isinstance(text, str): # pragma: no cover
|
|
64
|
+
result = ""
|
|
65
|
+
else:
|
|
66
|
+
result = text.capitalize()
|
|
67
|
+
|
|
68
|
+
return pybars.strlist([result])
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _round_helper(this, *args):
|
|
72
|
+
"""Round a number to the specified number of decimal places."""
|
|
73
|
+
if len(args) < 1:
|
|
74
|
+
return ""
|
|
75
|
+
|
|
76
|
+
value = args[0]
|
|
77
|
+
decimal_places = args[1] if len(args) > 1 else 2
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
result = str(round(float(value), int(decimal_places)))
|
|
81
|
+
except (ValueError, TypeError):
|
|
82
|
+
result = str(value)
|
|
83
|
+
|
|
84
|
+
return pybars.strlist([result])
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _size_helper(this, *args):
|
|
88
|
+
"""Return the size/length of a collection."""
|
|
89
|
+
if len(args) < 1:
|
|
90
|
+
return 0
|
|
91
|
+
|
|
92
|
+
value = args[0]
|
|
93
|
+
if value is None:
|
|
94
|
+
result = "0"
|
|
95
|
+
elif isinstance(value, (list, tuple, dict, str)):
|
|
96
|
+
result = str(len(value)) # pragma: no cover
|
|
97
|
+
else: # pragma: no cover
|
|
98
|
+
result = "0"
|
|
99
|
+
|
|
100
|
+
return pybars.strlist([result])
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _json_helper(this, *args):
|
|
104
|
+
"""Convert a value to a JSON string."""
|
|
105
|
+
if len(args) < 1: # pragma: no cover
|
|
106
|
+
return "{}"
|
|
107
|
+
|
|
108
|
+
value = args[0]
|
|
109
|
+
# For pybars, we need to return a SafeString to prevent HTML escaping
|
|
110
|
+
result = json.dumps(value) # pragma: no cover
|
|
111
|
+
# Safe string implementation to prevent HTML escaping
|
|
112
|
+
return pybars.strlist([result])
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _math_helper(this, *args):
|
|
116
|
+
"""Perform basic math operations."""
|
|
117
|
+
if len(args) < 3:
|
|
118
|
+
return pybars.strlist(["Math error: Insufficient arguments"])
|
|
119
|
+
|
|
120
|
+
lhs = args[0]
|
|
121
|
+
operator = args[1]
|
|
122
|
+
rhs = args[2]
|
|
123
|
+
|
|
124
|
+
try:
|
|
125
|
+
lhs = float(lhs)
|
|
126
|
+
rhs = float(rhs)
|
|
127
|
+
if operator == "+":
|
|
128
|
+
result = str(lhs + rhs)
|
|
129
|
+
elif operator == "-":
|
|
130
|
+
result = str(lhs - rhs)
|
|
131
|
+
elif operator == "*":
|
|
132
|
+
result = str(lhs * rhs)
|
|
133
|
+
elif operator == "/":
|
|
134
|
+
result = str(lhs / rhs)
|
|
135
|
+
else:
|
|
136
|
+
result = f"Unsupported operator: {operator}"
|
|
137
|
+
except (ValueError, TypeError) as e:
|
|
138
|
+
result = f"Math error: {e}"
|
|
139
|
+
|
|
140
|
+
return pybars.strlist([result])
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _lt_helper(this, *args):
|
|
144
|
+
"""Check if left hand side is less than right hand side."""
|
|
145
|
+
if len(args) < 2:
|
|
146
|
+
return False
|
|
147
|
+
|
|
148
|
+
lhs = args[0]
|
|
149
|
+
rhs = args[1]
|
|
150
|
+
|
|
151
|
+
try:
|
|
152
|
+
return float(lhs) < float(rhs)
|
|
153
|
+
except (ValueError, TypeError):
|
|
154
|
+
# Fall back to string comparison for non-numeric values
|
|
155
|
+
return str(lhs) < str(rhs)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _if_cond_helper(this, options, condition):
|
|
159
|
+
"""Block helper for custom if conditionals."""
|
|
160
|
+
if condition:
|
|
161
|
+
return options["fn"](this)
|
|
162
|
+
elif "inverse" in options:
|
|
163
|
+
return options["inverse"](this)
|
|
164
|
+
return "" # pragma: no cover
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _dedent_helper(this, options):
|
|
168
|
+
"""Dedent a block of text to remove common leading whitespace.
|
|
169
|
+
|
|
170
|
+
Usage:
|
|
171
|
+
{{#dedent}}
|
|
172
|
+
This text will have its
|
|
173
|
+
common leading whitespace removed
|
|
174
|
+
while preserving relative indentation.
|
|
175
|
+
{{/dedent}}
|
|
176
|
+
"""
|
|
177
|
+
if "fn" not in options: # pragma: no cover
|
|
178
|
+
return ""
|
|
179
|
+
|
|
180
|
+
# Get the content from the block
|
|
181
|
+
content = options["fn"](this)
|
|
182
|
+
|
|
183
|
+
# Convert to string if it's a strlist
|
|
184
|
+
if (
|
|
185
|
+
isinstance(content, list)
|
|
186
|
+
or hasattr(content, "__iter__")
|
|
187
|
+
and not isinstance(content, (str, bytes))
|
|
188
|
+
):
|
|
189
|
+
content_str = "".join(str(item) for item in content) # pragma: no cover
|
|
190
|
+
else:
|
|
191
|
+
content_str = str(content) # pragma: no cover
|
|
192
|
+
|
|
193
|
+
# Add trailing and leading newlines to ensure proper dedenting
|
|
194
|
+
# This is critical for textwrap.dedent to work correctly with mixed content
|
|
195
|
+
content_str = "\n" + content_str + "\n"
|
|
196
|
+
|
|
197
|
+
# Use textwrap to dedent the content and remove the extra newlines we added
|
|
198
|
+
dedented = textwrap.dedent(content_str)[1:-1]
|
|
199
|
+
|
|
200
|
+
# Return as a SafeString to prevent HTML escaping
|
|
201
|
+
return pybars.strlist([dedented]) # pragma: no cover
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class TemplateLoader:
|
|
205
|
+
"""Loader for Handlebars templates.
|
|
206
|
+
|
|
207
|
+
This class is responsible for loading templates from disk and rendering
|
|
208
|
+
them with the provided context data.
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
def __init__(self, template_dir: Optional[str] = None):
|
|
212
|
+
"""Initialize the template loader.
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
template_dir: Optional custom template directory path
|
|
216
|
+
"""
|
|
217
|
+
self.template_dir = Path(template_dir) if template_dir else TEMPLATES_DIR
|
|
218
|
+
self.template_cache: Dict[str, Callable] = {}
|
|
219
|
+
self.compiler = pybars.Compiler()
|
|
220
|
+
|
|
221
|
+
# Set up standard helpers
|
|
222
|
+
self.helpers = {
|
|
223
|
+
"date": _date_helper,
|
|
224
|
+
"default": _default_helper,
|
|
225
|
+
"capitalize": _capitalize_helper,
|
|
226
|
+
"round": _round_helper,
|
|
227
|
+
"size": _size_helper,
|
|
228
|
+
"json": _json_helper,
|
|
229
|
+
"math": _math_helper,
|
|
230
|
+
"lt": _lt_helper,
|
|
231
|
+
"if_cond": _if_cond_helper,
|
|
232
|
+
"dedent": _dedent_helper,
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
logger.debug(f"Initialized template loader with directory: {self.template_dir}")
|
|
236
|
+
|
|
237
|
+
def get_template(self, template_path: str) -> Callable:
|
|
238
|
+
"""Get a template by path, using cache if available.
|
|
239
|
+
|
|
240
|
+
Args:
|
|
241
|
+
template_path: The path to the template, relative to the templates directory
|
|
242
|
+
|
|
243
|
+
Returns:
|
|
244
|
+
The compiled Handlebars template
|
|
245
|
+
|
|
246
|
+
Raises:
|
|
247
|
+
FileNotFoundError: If the template doesn't exist
|
|
248
|
+
"""
|
|
249
|
+
if template_path in self.template_cache:
|
|
250
|
+
return self.template_cache[template_path]
|
|
251
|
+
|
|
252
|
+
# Convert from Liquid-style path to Handlebars extension
|
|
253
|
+
if template_path.endswith(".liquid"):
|
|
254
|
+
template_path = template_path.replace(".liquid", ".hbs")
|
|
255
|
+
elif not template_path.endswith(".hbs"):
|
|
256
|
+
template_path = f"{template_path}.hbs"
|
|
257
|
+
|
|
258
|
+
full_path = self.template_dir / template_path
|
|
259
|
+
|
|
260
|
+
if not full_path.exists():
|
|
261
|
+
raise FileNotFoundError(f"Template not found: {full_path}")
|
|
262
|
+
|
|
263
|
+
with open(full_path, "r", encoding="utf-8") as f:
|
|
264
|
+
template_str = f.read()
|
|
265
|
+
|
|
266
|
+
template = self.compiler.compile(template_str)
|
|
267
|
+
self.template_cache[template_path] = template
|
|
268
|
+
|
|
269
|
+
logger.debug(f"Loaded template: {template_path}")
|
|
270
|
+
return template
|
|
271
|
+
|
|
272
|
+
async def render(self, template_path: str, context: Dict[str, Any]) -> str:
|
|
273
|
+
"""Render a template with the given context.
|
|
274
|
+
|
|
275
|
+
Args:
|
|
276
|
+
template_path: The path to the template, relative to the templates directory
|
|
277
|
+
context: The context data to pass to the template
|
|
278
|
+
|
|
279
|
+
Returns:
|
|
280
|
+
The rendered template as a string
|
|
281
|
+
"""
|
|
282
|
+
template = self.get_template(template_path)
|
|
283
|
+
return template(context, helpers=self.helpers)
|
|
284
|
+
|
|
285
|
+
def clear_cache(self) -> None:
|
|
286
|
+
"""Clear the template cache."""
|
|
287
|
+
self.template_cache.clear()
|
|
288
|
+
logger.debug("Template cache cleared")
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
# Global template loader instance
|
|
292
|
+
template_loader = TemplateLoader()
|
basic_memory/cli/app.py
CHANGED
|
@@ -1,3 +1,54 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
1
3
|
import typer
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
from basic_memory.config import ConfigManager
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def version_callback(value: bool) -> None:
|
|
9
|
+
"""Show version and exit."""
|
|
10
|
+
if value: # pragma: no cover
|
|
11
|
+
import basic_memory
|
|
12
|
+
|
|
13
|
+
typer.echo(f"Basic Memory version: {basic_memory.__version__}")
|
|
14
|
+
raise typer.Exit()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
app = typer.Typer(name="basic-memory")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@app.callback()
|
|
21
|
+
def app_callback(
|
|
22
|
+
ctx: typer.Context,
|
|
23
|
+
version: Optional[bool] = typer.Option(
|
|
24
|
+
None,
|
|
25
|
+
"--version",
|
|
26
|
+
"-v",
|
|
27
|
+
help="Show version and exit.",
|
|
28
|
+
callback=version_callback,
|
|
29
|
+
is_eager=True,
|
|
30
|
+
),
|
|
31
|
+
) -> None:
|
|
32
|
+
"""Basic Memory - Local-first personal knowledge management."""
|
|
33
|
+
|
|
34
|
+
# Run initialization for every command unless --version was specified
|
|
35
|
+
if not version and ctx.invoked_subcommand is not None:
|
|
36
|
+
from basic_memory.services.initialization import ensure_initialization
|
|
37
|
+
|
|
38
|
+
app_config = ConfigManager().config
|
|
39
|
+
ensure_initialization(app_config)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
## import
|
|
43
|
+
# Register sub-command groups
|
|
44
|
+
import_app = typer.Typer(help="Import data from various sources")
|
|
45
|
+
app.add_typer(import_app, name="import")
|
|
46
|
+
|
|
47
|
+
claude_app = typer.Typer(help="Import Conversations from Claude JSON export.")
|
|
48
|
+
import_app.add_typer(claude_app, name="claude")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
## cloud
|
|
52
|
+
|
|
53
|
+
cloud_app = typer.Typer(help="Access Basic Memory Cloud")
|
|
54
|
+
app.add_typer(cloud_app, name="cloud")
|
basic_memory/cli/auth.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
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
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
from rich.console import Console
|
|
13
|
+
|
|
14
|
+
from basic_memory.config import ConfigManager
|
|
15
|
+
|
|
16
|
+
console = Console()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CLIAuth:
|
|
20
|
+
"""Handles WorkOS OAuth Device Authorization for CLI tools."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, client_id: str, authkit_domain: str):
|
|
23
|
+
self.client_id = client_id
|
|
24
|
+
self.authkit_domain = authkit_domain
|
|
25
|
+
app_config = ConfigManager().config
|
|
26
|
+
# Store tokens in data dir
|
|
27
|
+
self.token_file = app_config.data_dir_path / "basic-memory-cloud.json"
|
|
28
|
+
# PKCE parameters
|
|
29
|
+
self.code_verifier = None
|
|
30
|
+
self.code_challenge = None
|
|
31
|
+
|
|
32
|
+
def generate_pkce_pair(self) -> tuple[str, str]:
|
|
33
|
+
"""Generate PKCE code verifier and challenge."""
|
|
34
|
+
# Generate code verifier (43-128 characters)
|
|
35
|
+
code_verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).decode("utf-8")
|
|
36
|
+
code_verifier = code_verifier.rstrip("=")
|
|
37
|
+
|
|
38
|
+
# Generate code challenge (SHA256 hash of verifier)
|
|
39
|
+
challenge_bytes = hashlib.sha256(code_verifier.encode("utf-8")).digest()
|
|
40
|
+
code_challenge = base64.urlsafe_b64encode(challenge_bytes).decode("utf-8")
|
|
41
|
+
code_challenge = code_challenge.rstrip("=")
|
|
42
|
+
|
|
43
|
+
return code_verifier, code_challenge
|
|
44
|
+
|
|
45
|
+
async def request_device_authorization(self) -> dict | None:
|
|
46
|
+
"""Request device authorization from WorkOS with PKCE."""
|
|
47
|
+
device_auth_url = f"{self.authkit_domain}/oauth2/device_authorization"
|
|
48
|
+
|
|
49
|
+
# Generate PKCE pair
|
|
50
|
+
self.code_verifier, self.code_challenge = self.generate_pkce_pair()
|
|
51
|
+
|
|
52
|
+
data = {
|
|
53
|
+
"client_id": self.client_id,
|
|
54
|
+
"scope": "openid profile email offline_access",
|
|
55
|
+
"code_challenge": self.code_challenge,
|
|
56
|
+
"code_challenge_method": "S256",
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
async with httpx.AsyncClient() as client:
|
|
61
|
+
response = await client.post(device_auth_url, data=data)
|
|
62
|
+
|
|
63
|
+
if response.status_code == 200:
|
|
64
|
+
return response.json()
|
|
65
|
+
else:
|
|
66
|
+
console.print(
|
|
67
|
+
f"[red]Device authorization failed: {response.status_code} - {response.text}[/red]"
|
|
68
|
+
)
|
|
69
|
+
return None
|
|
70
|
+
except Exception as e:
|
|
71
|
+
console.print(f"[red]Device authorization error: {e}[/red]")
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
def display_user_instructions(self, device_response: dict) -> None:
|
|
75
|
+
"""Display user instructions for device authorization."""
|
|
76
|
+
user_code = device_response["user_code"]
|
|
77
|
+
verification_uri = device_response["verification_uri"]
|
|
78
|
+
verification_uri_complete = device_response.get("verification_uri_complete")
|
|
79
|
+
|
|
80
|
+
console.print("\n[bold blue]Authentication Required[/bold blue]")
|
|
81
|
+
console.print("\nTo authenticate, please visit:")
|
|
82
|
+
console.print(f"[bold cyan]{verification_uri}[/bold cyan]")
|
|
83
|
+
console.print(f"\nAnd enter this code: [bold yellow]{user_code}[/bold yellow]")
|
|
84
|
+
|
|
85
|
+
if verification_uri_complete:
|
|
86
|
+
console.print("\nOr for one-click access, visit:")
|
|
87
|
+
console.print(f"[bold green]{verification_uri_complete}[/bold green]")
|
|
88
|
+
|
|
89
|
+
# Try to open browser automatically
|
|
90
|
+
try:
|
|
91
|
+
console.print("\n[dim]Opening browser automatically...[/dim]")
|
|
92
|
+
webbrowser.open(verification_uri_complete)
|
|
93
|
+
except Exception:
|
|
94
|
+
pass # Silently fail if browser can't be opened
|
|
95
|
+
|
|
96
|
+
console.print("\n[dim]Waiting for you to complete authentication in your browser...[/dim]")
|
|
97
|
+
|
|
98
|
+
async def poll_for_token(self, device_code: str, interval: int = 5) -> dict | None:
|
|
99
|
+
"""Poll the token endpoint until user completes authentication."""
|
|
100
|
+
token_url = f"{self.authkit_domain}/oauth2/token"
|
|
101
|
+
|
|
102
|
+
data = {
|
|
103
|
+
"client_id": self.client_id,
|
|
104
|
+
"device_code": device_code,
|
|
105
|
+
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
|
|
106
|
+
"code_verifier": self.code_verifier,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
max_attempts = 60 # 5 minutes with 5-second intervals
|
|
110
|
+
current_interval = interval
|
|
111
|
+
|
|
112
|
+
for _attempt in range(max_attempts):
|
|
113
|
+
try:
|
|
114
|
+
async with httpx.AsyncClient() as client:
|
|
115
|
+
response = await client.post(token_url, data=data)
|
|
116
|
+
|
|
117
|
+
if response.status_code == 200:
|
|
118
|
+
return response.json()
|
|
119
|
+
|
|
120
|
+
# Parse error response
|
|
121
|
+
try:
|
|
122
|
+
error_data = response.json()
|
|
123
|
+
error = error_data.get("error")
|
|
124
|
+
except Exception:
|
|
125
|
+
error = "unknown_error"
|
|
126
|
+
|
|
127
|
+
if error == "authorization_pending":
|
|
128
|
+
# User hasn't completed auth yet, keep polling
|
|
129
|
+
pass
|
|
130
|
+
elif error == "slow_down":
|
|
131
|
+
# Increase polling interval
|
|
132
|
+
current_interval += 5
|
|
133
|
+
console.print("[yellow]Slowing down polling rate...[/yellow]")
|
|
134
|
+
elif error == "access_denied":
|
|
135
|
+
console.print("[red]Authentication was denied by user[/red]")
|
|
136
|
+
return None
|
|
137
|
+
elif error == "expired_token":
|
|
138
|
+
console.print("[red]Device code has expired. Please try again.[/red]")
|
|
139
|
+
return None
|
|
140
|
+
else:
|
|
141
|
+
console.print(f"[red]Token polling error: {error}[/red]")
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
except Exception as e:
|
|
145
|
+
console.print(f"[red]Token polling request error: {e}[/red]")
|
|
146
|
+
|
|
147
|
+
# Wait before next poll
|
|
148
|
+
await self._async_sleep(current_interval)
|
|
149
|
+
|
|
150
|
+
console.print("[red]Authentication timeout. Please try again.[/red]")
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
async def _async_sleep(self, seconds: int) -> None:
|
|
154
|
+
"""Async sleep utility."""
|
|
155
|
+
import asyncio
|
|
156
|
+
|
|
157
|
+
await asyncio.sleep(seconds)
|
|
158
|
+
|
|
159
|
+
def save_tokens(self, tokens: dict) -> None:
|
|
160
|
+
"""Save tokens to project root as .bm-auth.json."""
|
|
161
|
+
token_data = {
|
|
162
|
+
"access_token": tokens["access_token"],
|
|
163
|
+
"refresh_token": tokens.get("refresh_token"),
|
|
164
|
+
"expires_at": int(time.time()) + tokens.get("expires_in", 3600),
|
|
165
|
+
"token_type": tokens.get("token_type", "Bearer"),
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
with open(self.token_file, "w") as f:
|
|
169
|
+
json.dump(token_data, f, indent=2)
|
|
170
|
+
|
|
171
|
+
# Secure the token file
|
|
172
|
+
os.chmod(self.token_file, 0o600)
|
|
173
|
+
|
|
174
|
+
console.print(f"[green]Tokens saved to {self.token_file}[/green]")
|
|
175
|
+
|
|
176
|
+
def load_tokens(self) -> dict | None:
|
|
177
|
+
"""Load tokens from .bm-auth.json file."""
|
|
178
|
+
if not self.token_file.exists():
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
try:
|
|
182
|
+
with open(self.token_file) as f:
|
|
183
|
+
return json.load(f)
|
|
184
|
+
except (OSError, json.JSONDecodeError):
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
def is_token_valid(self, tokens: dict) -> bool:
|
|
188
|
+
"""Check if stored token is still valid."""
|
|
189
|
+
expires_at = tokens.get("expires_at", 0)
|
|
190
|
+
# Add 60 second buffer for clock skew
|
|
191
|
+
return time.time() < (expires_at - 60)
|
|
192
|
+
|
|
193
|
+
async def refresh_token(self, refresh_token: str) -> dict | None:
|
|
194
|
+
"""Refresh access token using refresh token."""
|
|
195
|
+
token_url = f"{self.authkit_domain}/oauth2/token"
|
|
196
|
+
|
|
197
|
+
data = {
|
|
198
|
+
"client_id": self.client_id,
|
|
199
|
+
"grant_type": "refresh_token",
|
|
200
|
+
"refresh_token": refresh_token,
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
try:
|
|
204
|
+
async with httpx.AsyncClient() as client:
|
|
205
|
+
response = await client.post(token_url, data=data)
|
|
206
|
+
|
|
207
|
+
if response.status_code == 200:
|
|
208
|
+
return response.json()
|
|
209
|
+
else:
|
|
210
|
+
console.print(
|
|
211
|
+
f"[red]Token refresh failed: {response.status_code} - {response.text}[/red]"
|
|
212
|
+
)
|
|
213
|
+
return None
|
|
214
|
+
except Exception as e:
|
|
215
|
+
console.print(f"[red]Token refresh error: {e}[/red]")
|
|
216
|
+
return None
|
|
217
|
+
|
|
218
|
+
async def get_valid_token(self) -> str | None:
|
|
219
|
+
"""Get valid access token, refresh if needed."""
|
|
220
|
+
tokens = self.load_tokens()
|
|
221
|
+
if not tokens:
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
if self.is_token_valid(tokens):
|
|
225
|
+
return tokens["access_token"]
|
|
226
|
+
|
|
227
|
+
# Token expired - try to refresh if we have a refresh token
|
|
228
|
+
refresh_token = tokens.get("refresh_token")
|
|
229
|
+
if refresh_token:
|
|
230
|
+
console.print("[yellow]Access token expired, refreshing...[/yellow]")
|
|
231
|
+
|
|
232
|
+
new_tokens = await self.refresh_token(refresh_token)
|
|
233
|
+
if new_tokens:
|
|
234
|
+
# Save new tokens (may include rotated refresh token)
|
|
235
|
+
self.save_tokens(new_tokens)
|
|
236
|
+
console.print("[green]Token refreshed successfully[/green]")
|
|
237
|
+
return new_tokens["access_token"]
|
|
238
|
+
else:
|
|
239
|
+
console.print("[yellow]Token refresh failed. Please run 'login' again.[/yellow]")
|
|
240
|
+
return None
|
|
241
|
+
else:
|
|
242
|
+
console.print("[yellow]No refresh token available. Please run 'login' again.[/yellow]")
|
|
243
|
+
return None
|
|
244
|
+
|
|
245
|
+
async def login(self) -> bool:
|
|
246
|
+
"""Perform OAuth Device Authorization login flow."""
|
|
247
|
+
console.print("[blue]Initiating authentication...[/blue]")
|
|
248
|
+
|
|
249
|
+
# Step 1: Request device authorization
|
|
250
|
+
device_response = await self.request_device_authorization()
|
|
251
|
+
if not device_response:
|
|
252
|
+
return False
|
|
253
|
+
|
|
254
|
+
# Step 2: Display user instructions
|
|
255
|
+
self.display_user_instructions(device_response)
|
|
256
|
+
|
|
257
|
+
# Step 3: Poll for token
|
|
258
|
+
device_code = device_response["device_code"]
|
|
259
|
+
interval = device_response.get("interval", 5)
|
|
260
|
+
|
|
261
|
+
tokens = await self.poll_for_token(device_code, interval)
|
|
262
|
+
if not tokens:
|
|
263
|
+
return False
|
|
264
|
+
|
|
265
|
+
# Step 4: Save tokens
|
|
266
|
+
self.save_tokens(tokens)
|
|
267
|
+
|
|
268
|
+
console.print("\n[green]Successfully authenticated with Basic Memory Cloud![/green]")
|
|
269
|
+
return True
|
|
270
|
+
|
|
271
|
+
def logout(self) -> None:
|
|
272
|
+
"""Remove stored authentication tokens."""
|
|
273
|
+
if self.token_file.exists():
|
|
274
|
+
self.token_file.unlink()
|
|
275
|
+
console.print("[green]Logged out successfully[/green]")
|
|
276
|
+
else:
|
|
277
|
+
console.print("[yellow]No stored authentication found[/yellow]")
|
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
"""CLI commands for basic-memory."""
|
|
2
2
|
|
|
3
|
-
from . import status,
|
|
3
|
+
from . import status, db, import_memory_json, mcp, import_claude_conversations
|
|
4
|
+
from . import import_claude_projects, import_chatgpt, tool, project
|
|
4
5
|
|
|
5
|
-
__all__ = [
|
|
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
|
+
]
|
|
@@ -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
|