anamnesis-cli 0.1.0__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.
- anamnesis/__init__.py +0 -0
- anamnesis/cli/__init__.py +0 -0
- anamnesis/cli/__main__.py +551 -0
- anamnesis/cli/app.py +567 -0
- anamnesis/cli/app.tcss +160 -0
- anamnesis/cli/archive_view.py +211 -0
- anamnesis/cli/commands.py +57 -0
- anamnesis/cli/look.py +176 -0
- anamnesis/cli/node_cmd.py +453 -0
- anamnesis/cli/setup_cmd.py +173 -0
- anamnesis/cli/widgets.py +225 -0
- anamnesis/config.py +109 -0
- anamnesis/connect.py +343 -0
- anamnesis/core/__init__.py +0 -0
- anamnesis/core/db.py +563 -0
- anamnesis/core/devices.py +639 -0
- anamnesis/core/formatting.py +51 -0
- anamnesis/core/memory.py +290 -0
- anamnesis/core/models.py +76 -0
- anamnesis/core/vector.py +289 -0
- anamnesis/ingest/__init__.py +1 -0
- anamnesis/ingest/base.py +74 -0
- anamnesis/ingest/claude_code.py +85 -0
- anamnesis/ingest/clean.py +54 -0
- anamnesis/ingest/codex.py +136 -0
- anamnesis/ingest/cursor.py +166 -0
- anamnesis/ingest/exports.py +269 -0
- anamnesis/ingest/gemini_cli.py +156 -0
- anamnesis/ingest/runner.py +194 -0
- anamnesis/memory_mcp/__init__.py +1 -0
- anamnesis/memory_mcp/__main__.py +3 -0
- anamnesis/memory_mcp/server.py +208 -0
- anamnesis/node/__init__.py +1 -0
- anamnesis/node/app.py +476 -0
- anamnesis/node/auth.py +405 -0
- anamnesis/retention.py +75 -0
- anamnesis/web/__init__.py +0 -0
- anamnesis/web/__main__.py +21 -0
- anamnesis/web/main.py +265 -0
- anamnesis/web/static/app.js +380 -0
- anamnesis/web/static/index.html +48 -0
- anamnesis/web/static/markdown.js +79 -0
- anamnesis/web/static/style.css +143 -0
- anamnesis_cli-0.1.0.dist-info/METADATA +287 -0
- anamnesis_cli-0.1.0.dist-info/RECORD +49 -0
- anamnesis_cli-0.1.0.dist-info/WHEEL +5 -0
- anamnesis_cli-0.1.0.dist-info/entry_points.txt +4 -0
- anamnesis_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- anamnesis_cli-0.1.0.dist-info/top_level.txt +1 -0
anamnesis/__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
"""`anam` command line.
|
|
2
|
+
|
|
3
|
+
anam setup guided first run: import history, connect your AI tools
|
|
4
|
+
anam open the terminal memory browser
|
|
5
|
+
anam sync [--watch] import new history from Claude Code, Codex, Gemini CLI, Cursor
|
|
6
|
+
anam import FILE... import a ChatGPT / claude.ai / Gemini (Takeout) data export
|
|
7
|
+
anam search QUERY search all memory from the shell (or just: anam QUERY)
|
|
8
|
+
anam connect [TOOL|all] give AI tools access to the memory (MCP); no TOOL = show status
|
|
9
|
+
anam disconnect TOOL|all
|
|
10
|
+
anam status your archive: what is kept, per tool, and what's missing
|
|
11
|
+
anam keep stop Claude Code deleting its own sessions after 30 days
|
|
12
|
+
anam mcp run the MCP server (started for you by connected tools)
|
|
13
|
+
anam node … your self-hosted node: deploy, link, status, activity, revoke, wipe
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import asyncio
|
|
20
|
+
import contextlib
|
|
21
|
+
import logging
|
|
22
|
+
import os
|
|
23
|
+
import sys
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from anamnesis.config import Settings, load_settings
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _log_to_file(settings: Settings, name: str = "anamnesis.log") -> None:
|
|
30
|
+
settings.data_dir.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
logging.basicConfig(
|
|
32
|
+
filename=settings.data_dir / name,
|
|
33
|
+
level=logging.INFO,
|
|
34
|
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def _with_service(settings: Settings, fn, quiet: bool = False): # type: ignore[no-untyped-def]
|
|
39
|
+
from anamnesis.core.memory import MemoryService
|
|
40
|
+
|
|
41
|
+
if not quiet:
|
|
42
|
+
print("Opening memory…", file=sys.stderr, flush=True)
|
|
43
|
+
service = await MemoryService.create(settings)
|
|
44
|
+
try:
|
|
45
|
+
return await fn(service)
|
|
46
|
+
finally:
|
|
47
|
+
await service.close()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _print_report(report) -> None: # type: ignore[no-untyped-def]
|
|
51
|
+
from anamnesis.core.models import SOURCE_LABELS
|
|
52
|
+
|
|
53
|
+
if report.messages_added:
|
|
54
|
+
|
|
55
|
+
def label(k: str) -> str:
|
|
56
|
+
if k.startswith("device:"):
|
|
57
|
+
return f"from {k.removeprefix('device:')}"
|
|
58
|
+
return SOURCE_LABELS.get(k, k)
|
|
59
|
+
|
|
60
|
+
per = ", ".join(f"{label(k)}: {v}" for k, v in report.by_source.items())
|
|
61
|
+
print(f"Imported {report.messages_added} new messages ({per}).")
|
|
62
|
+
elif not report.shared:
|
|
63
|
+
print("Memory is up to date.")
|
|
64
|
+
if report.shared:
|
|
65
|
+
print(f"Shared {report.shared} messages with your other computers.")
|
|
66
|
+
for err in report.errors:
|
|
67
|
+
print(f" warning: {err}", file=sys.stderr)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _progress(done: int, total: int) -> None:
|
|
71
|
+
end = "\n" if done >= total else ""
|
|
72
|
+
print(f"\rEmbedding for semantic search: {done}/{total}", end=end, flush=True)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
_EXPORT_HELP = """where to get an export:
|
|
76
|
+
claude.ai Settings → Privacy → Export data (also covers Claude Desktop and the app)
|
|
77
|
+
https://claude.ai/settings/data-privacy-controls
|
|
78
|
+
ChatGPT Settings → Data controls → Export data
|
|
79
|
+
https://chatgpt.com/#settings/DataControls
|
|
80
|
+
Gemini Google Takeout → only "My Activity" → "Gemini Apps", format JSON
|
|
81
|
+
https://takeout.google.com
|
|
82
|
+
|
|
83
|
+
The download link arrives by email. Importing a newer export later only adds what's new."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def cmd_sync(settings: Settings, args: argparse.Namespace) -> int:
|
|
87
|
+
from anamnesis.ingest.runner import exchange_with_devices, scan, sync_lock, watch
|
|
88
|
+
|
|
89
|
+
async def run(service): # type: ignore[no-untyped-def]
|
|
90
|
+
with sync_lock(settings.data_dir) as acquired:
|
|
91
|
+
if not acquired:
|
|
92
|
+
print("Another Anamnesis process is syncing right now; try again shortly.")
|
|
93
|
+
return 1
|
|
94
|
+
report = await scan(service, force=args.force, index=False)
|
|
95
|
+
await exchange_with_devices(service, report)
|
|
96
|
+
_print_report(report)
|
|
97
|
+
await service.backfill_index(progress=_progress)
|
|
98
|
+
if args.watch:
|
|
99
|
+
print(f"Watching for new conversations every {args.interval:.0f}s (Ctrl+C to stop)…")
|
|
100
|
+
await watch(service, interval=args.interval)
|
|
101
|
+
return 0
|
|
102
|
+
|
|
103
|
+
try:
|
|
104
|
+
return int(asyncio.run(_with_service(settings, run)))
|
|
105
|
+
except KeyboardInterrupt:
|
|
106
|
+
return 0
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def cmd_import(settings: Settings, args: argparse.Namespace) -> int:
|
|
110
|
+
from anamnesis.ingest.exports import ExportFormatError
|
|
111
|
+
from anamnesis.ingest.runner import import_file
|
|
112
|
+
|
|
113
|
+
paths = [Path(f).expanduser() for f in args.files]
|
|
114
|
+
missing = [p for p in paths if not p.is_file()]
|
|
115
|
+
for path in missing:
|
|
116
|
+
print(f"{path}: file not found", file=sys.stderr)
|
|
117
|
+
paths = [p for p in paths if p not in missing]
|
|
118
|
+
|
|
119
|
+
async def run(service): # type: ignore[no-untyped-def]
|
|
120
|
+
code = 1 if missing else 0
|
|
121
|
+
for path in paths:
|
|
122
|
+
try:
|
|
123
|
+
report = await import_file(service, path, index=False)
|
|
124
|
+
except ExportFormatError as e:
|
|
125
|
+
print(str(e), file=sys.stderr)
|
|
126
|
+
code = 1
|
|
127
|
+
continue
|
|
128
|
+
print(
|
|
129
|
+
f"{path.name}: {report.conversations} conversations, "
|
|
130
|
+
f"{report.messages_added} new messages."
|
|
131
|
+
)
|
|
132
|
+
return code
|
|
133
|
+
|
|
134
|
+
return int(asyncio.run(_with_service(settings, run)))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def cmd_search(settings: Settings, args: argparse.Namespace) -> int:
|
|
138
|
+
from rich.padding import Padding
|
|
139
|
+
from rich.text import Text
|
|
140
|
+
|
|
141
|
+
from anamnesis.cli import look
|
|
142
|
+
from anamnesis.core.models import SOURCE_LABELS, SearchHit
|
|
143
|
+
|
|
144
|
+
query = " ".join(args.query)
|
|
145
|
+
|
|
146
|
+
async def run(service): # type: ignore[no-untyped-def]
|
|
147
|
+
return await service.search(query, k=args.limit * 3, source=args.source)
|
|
148
|
+
|
|
149
|
+
best: dict[str, SearchHit] = {} # one result per conversation: its best message
|
|
150
|
+
for h in asyncio.run(_with_service(settings, run, quiet=True)):
|
|
151
|
+
best.setdefault(h.thread_id, h)
|
|
152
|
+
hits = list(best.values())[: args.limit]
|
|
153
|
+
con = look.console()
|
|
154
|
+
if not hits:
|
|
155
|
+
con.print(Text(f"No matches for “{query}”.", style=look.MUTED))
|
|
156
|
+
return 0
|
|
157
|
+
terms = look.query_terms(query)
|
|
158
|
+
con.print()
|
|
159
|
+
for i, h in enumerate(hits, 1):
|
|
160
|
+
where = " · ".join(
|
|
161
|
+
p
|
|
162
|
+
for p in (
|
|
163
|
+
look.project_name(h.project),
|
|
164
|
+
look.relative_time(h.created_at) if h.created_at else "",
|
|
165
|
+
)
|
|
166
|
+
if p
|
|
167
|
+
)
|
|
168
|
+
con.print(Text.assemble((f"{i:>2} ", look.MUTED), (h.thread_title or "Untitled", "bold")))
|
|
169
|
+
tool = SOURCE_LABELS.get(h.source or "", h.source or "")
|
|
170
|
+
con.print(
|
|
171
|
+
Text.assemble(
|
|
172
|
+
" ", look.pill(tool, look.source_color(h.source)), (f" {where}", look.MUTED)
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
body = Text(look.snippet(h.content, terms))
|
|
176
|
+
body.highlight_words(terms, style=f"bold {look.RUST}", case_sensitive=False)
|
|
177
|
+
con.print(Padding(body, (0, 2, 1, 4)), soft_wrap=False)
|
|
178
|
+
return 0
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _tilde(path: Path) -> str:
|
|
182
|
+
"""~/… for paths in your home folder (shorter, and doesn't print your username)."""
|
|
183
|
+
try:
|
|
184
|
+
return "~/" + str(path.resolve().relative_to(Path.home().resolve()))
|
|
185
|
+
except ValueError:
|
|
186
|
+
return str(path)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def tool_states() -> list[tuple[str, str]]:
|
|
190
|
+
from anamnesis.connect import targets
|
|
191
|
+
|
|
192
|
+
out = []
|
|
193
|
+
for t in targets().values():
|
|
194
|
+
if t.connected():
|
|
195
|
+
state = "connected" if t.current() else "outdated"
|
|
196
|
+
else:
|
|
197
|
+
state = "not connected" if t.installed() else "not installed"
|
|
198
|
+
out.append((t.label, state))
|
|
199
|
+
return out
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def cmd_status(settings: Settings, _: argparse.Namespace) -> int:
|
|
203
|
+
from rich.text import Text
|
|
204
|
+
|
|
205
|
+
from anamnesis.cli import archive_view
|
|
206
|
+
from anamnesis.cli.look import MUTED, console, heading
|
|
207
|
+
from anamnesis.core.devices import load_config
|
|
208
|
+
from anamnesis.retention import claude_code_cleanup_days
|
|
209
|
+
|
|
210
|
+
archive = archive_view.load(settings)
|
|
211
|
+
con = console()
|
|
212
|
+
con.print()
|
|
213
|
+
con.print(archive_view.render_archive(archive, retention_days=claude_code_cleanup_days()))
|
|
214
|
+
con.print(Text(f" {_tilde(settings.data_dir)}", style=MUTED))
|
|
215
|
+
con.print()
|
|
216
|
+
con.print(archive_view.render_lookups(archive))
|
|
217
|
+
con.print()
|
|
218
|
+
con.print(archive_view.render_tools(tool_states()))
|
|
219
|
+
missing = archive_view.missing_exports(archive)
|
|
220
|
+
if missing:
|
|
221
|
+
con.print()
|
|
222
|
+
con.print(archive_view.render_exports(missing))
|
|
223
|
+
con.print()
|
|
224
|
+
cfg = load_config(settings.data_dir)
|
|
225
|
+
if cfg is None:
|
|
226
|
+
con.print(heading("SYNC", "off: `anam node link <url>` or `anam share`", color="#4a443d"))
|
|
227
|
+
else:
|
|
228
|
+
con.print(heading("SYNC", f"through {'your node ' if cfg.node else ''}{cfg.where}"))
|
|
229
|
+
cmd_devices(settings, argparse.Namespace())
|
|
230
|
+
con.print()
|
|
231
|
+
return 0
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def cmd_keep(_: Settings, __: argparse.Namespace) -> int:
|
|
235
|
+
from anamnesis.retention import claude_code_cleanup_days, keep_claude_code_history
|
|
236
|
+
|
|
237
|
+
if claude_code_cleanup_days() is None:
|
|
238
|
+
print("Claude Code isn't used on this computer (or its settings can't be read).")
|
|
239
|
+
return 1
|
|
240
|
+
try:
|
|
241
|
+
print(f"Claude Code: {keep_claude_code_history()}")
|
|
242
|
+
except ValueError as e:
|
|
243
|
+
print(str(e), file=sys.stderr)
|
|
244
|
+
return 1
|
|
245
|
+
print("Old sessions now stay resumable in Claude Code (they use disk space in ~/.claude).")
|
|
246
|
+
return 0
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def cmd_connect(settings: Settings, args: argparse.Namespace) -> int:
|
|
250
|
+
from anamnesis.cli.node_cmd import WEB_CONNECTORS, connect_web
|
|
251
|
+
from anamnesis.connect import targets
|
|
252
|
+
|
|
253
|
+
if args.tool in WEB_CONNECTORS:
|
|
254
|
+
return connect_web(settings, args.tool)
|
|
255
|
+
all_targets = targets()
|
|
256
|
+
if not args.tool:
|
|
257
|
+
from anamnesis.cli.archive_view import render_tools
|
|
258
|
+
from anamnesis.cli.look import console
|
|
259
|
+
|
|
260
|
+
console().print(render_tools(tool_states()))
|
|
261
|
+
names = ", ".join(all_targets)
|
|
262
|
+
print(f"\nConnect with: anam connect <tool> or anam connect all ({names})")
|
|
263
|
+
print("Web apps (through your node): anam connect claude-web | chatgpt-web")
|
|
264
|
+
return 0
|
|
265
|
+
if args.tool == "all":
|
|
266
|
+
chosen = [t for t in all_targets.values() if t.installed()]
|
|
267
|
+
elif args.tool in all_targets:
|
|
268
|
+
chosen = [all_targets[args.tool]]
|
|
269
|
+
else:
|
|
270
|
+
print(
|
|
271
|
+
f"Unknown tool {args.tool!r}. Choose from: {', '.join(all_targets)}, all, "
|
|
272
|
+
+ ", ".join(WEB_CONNECTORS),
|
|
273
|
+
file=sys.stderr,
|
|
274
|
+
)
|
|
275
|
+
return 2
|
|
276
|
+
code = 0
|
|
277
|
+
for t in chosen:
|
|
278
|
+
try:
|
|
279
|
+
print(f"{t.label}: {t.connect()}")
|
|
280
|
+
except Exception as e:
|
|
281
|
+
print(f"{t.label}: failed: {e}", file=sys.stderr)
|
|
282
|
+
code = 1
|
|
283
|
+
return code
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def cmd_disconnect(_: Settings, args: argparse.Namespace) -> int:
|
|
287
|
+
from anamnesis.connect import targets
|
|
288
|
+
|
|
289
|
+
all_targets = targets()
|
|
290
|
+
if args.tool == "all":
|
|
291
|
+
chosen = [t for t in all_targets.values() if t.connected()]
|
|
292
|
+
if not chosen:
|
|
293
|
+
print("No AI tool is connected.")
|
|
294
|
+
elif args.tool in all_targets:
|
|
295
|
+
chosen = [all_targets[args.tool]]
|
|
296
|
+
else:
|
|
297
|
+
print(
|
|
298
|
+
f"Unknown tool {args.tool!r}. Choose from: {', '.join(all_targets)}, all",
|
|
299
|
+
file=sys.stderr,
|
|
300
|
+
)
|
|
301
|
+
return 2
|
|
302
|
+
for t in chosen:
|
|
303
|
+
print(f"{t.label}: {t.disconnect()}")
|
|
304
|
+
return 0
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _folder(value: str | None) -> Path:
|
|
308
|
+
from anamnesis.core.devices import default_folder
|
|
309
|
+
|
|
310
|
+
return Path(value).expanduser().resolve() if value else default_folder()
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def cmd_share(settings: Settings, args: argparse.Namespace) -> int:
|
|
314
|
+
from anamnesis.core.devices import SyncSetupError, share
|
|
315
|
+
|
|
316
|
+
folder = _folder(args.folder)
|
|
317
|
+
try:
|
|
318
|
+
code = share(settings.data_dir, folder)
|
|
319
|
+
except SyncSetupError as e:
|
|
320
|
+
print(str(e), file=sys.stderr)
|
|
321
|
+
return 1
|
|
322
|
+
print(f"Memory sync is on. Folder: {folder}")
|
|
323
|
+
print("\nPairing code (keep it private, it is the encryption key):\n")
|
|
324
|
+
print(f" {code}\n")
|
|
325
|
+
print("On your other computer, once this folder has synced there:")
|
|
326
|
+
print(f" anam join {code}" + (f" {folder}" if args.folder else ""))
|
|
327
|
+
print("\nRun `anam sync` (or just keep using your tools) to publish this computer's memory.")
|
|
328
|
+
return 0
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def cmd_join(settings: Settings, args: argparse.Namespace) -> int:
|
|
332
|
+
from anamnesis.core.devices import SyncSetupError, join
|
|
333
|
+
|
|
334
|
+
folder = _folder(args.folder)
|
|
335
|
+
try:
|
|
336
|
+
join(settings.data_dir, folder, args.code)
|
|
337
|
+
except SyncSetupError as e:
|
|
338
|
+
print(str(e), file=sys.stderr)
|
|
339
|
+
return 1
|
|
340
|
+
print(f"Joined. Pulling memory from your other computers ({folder})…")
|
|
341
|
+
code = cmd_sync(settings, argparse.Namespace(force=False, watch=False, interval=30.0))
|
|
342
|
+
print("\nNext: `anam connect all` so this computer's AI tools can use the memory.")
|
|
343
|
+
return code
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def cmd_devices(settings: Settings, _: argparse.Namespace) -> int:
|
|
347
|
+
import datetime as dt
|
|
348
|
+
|
|
349
|
+
from anamnesis.core.devices import list_devices, load_config, this_device
|
|
350
|
+
|
|
351
|
+
cfg = load_config(settings.data_dir)
|
|
352
|
+
if cfg is None:
|
|
353
|
+
print(
|
|
354
|
+
"Memory sync is off. Link a node with `anam node link <url>`, or sync through a "
|
|
355
|
+
"folder with `anam share`."
|
|
356
|
+
)
|
|
357
|
+
return 0
|
|
358
|
+
me = this_device(settings.data_dir)
|
|
359
|
+
print(f"Synced via {'your node ' if cfg.node else ''}{cfg.where}")
|
|
360
|
+
try:
|
|
361
|
+
found = list_devices(cfg)
|
|
362
|
+
except OSError as e:
|
|
363
|
+
print(f" (can't reach it right now: {e})")
|
|
364
|
+
return 0
|
|
365
|
+
for d in found:
|
|
366
|
+
when = (
|
|
367
|
+
dt.datetime.fromtimestamp(d["last_write"]).strftime("%Y-%m-%d %H:%M")
|
|
368
|
+
if d["last_write"]
|
|
369
|
+
else "never"
|
|
370
|
+
)
|
|
371
|
+
mark = " (this computer)" if d["id"] == me.id else ""
|
|
372
|
+
print(f" {d['name']:<24} last update {when}{mark}")
|
|
373
|
+
return 0
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def cmd_unshare(settings: Settings, _: argparse.Namespace) -> int:
|
|
377
|
+
from anamnesis.core.devices import disable
|
|
378
|
+
|
|
379
|
+
print(
|
|
380
|
+
"Memory sync turned off for this computer."
|
|
381
|
+
if disable(settings.data_dir)
|
|
382
|
+
else "Memory sync was not on."
|
|
383
|
+
)
|
|
384
|
+
return 0
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def cmd_mcp(_: Settings, __: argparse.Namespace) -> int:
|
|
388
|
+
from anamnesis.memory_mcp.server import main as mcp_main
|
|
389
|
+
|
|
390
|
+
mcp_main()
|
|
391
|
+
return 0
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def cmd_tui(settings: Settings, _: argparse.Namespace) -> int:
|
|
395
|
+
_log_to_file(settings) # never log to the terminal while the TUI owns it
|
|
396
|
+
from anamnesis.cli.app import AnamnesisApp
|
|
397
|
+
|
|
398
|
+
AnamnesisApp(settings).run()
|
|
399
|
+
return 0
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
403
|
+
parser = argparse.ArgumentParser(
|
|
404
|
+
prog="anam", description="Shared local memory for all your AI tools."
|
|
405
|
+
)
|
|
406
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
407
|
+
|
|
408
|
+
try:
|
|
409
|
+
ver = version("anamnesis-cli")
|
|
410
|
+
except PackageNotFoundError:
|
|
411
|
+
ver = "unknown"
|
|
412
|
+
parser.add_argument("--version", action="version", version=f"anam {ver}")
|
|
413
|
+
sub = parser.add_subparsers(dest="command")
|
|
414
|
+
p = sub.add_parser("setup", help="guided first run: import history and connect your AI tools")
|
|
415
|
+
p.add_argument("-y", "--yes", action="store_true", help="connect without asking")
|
|
416
|
+
p.add_argument("--skip-import", action="store_true", help="don't import history now")
|
|
417
|
+
p = sub.add_parser("sync", help="import new history from local AI tools")
|
|
418
|
+
p.add_argument("--watch", action="store_true", help="keep running and import continuously")
|
|
419
|
+
p.add_argument("--interval", type=float, default=30.0)
|
|
420
|
+
p.add_argument("--force", action="store_true", help="re-read every file")
|
|
421
|
+
p = sub.add_parser(
|
|
422
|
+
"import",
|
|
423
|
+
help="import ChatGPT / claude.ai / Gemini Takeout exports",
|
|
424
|
+
description="Import web chats from a data export (the .zip, or the JSON inside it).",
|
|
425
|
+
epilog=_EXPORT_HELP,
|
|
426
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
427
|
+
)
|
|
428
|
+
p.add_argument("files", nargs="+")
|
|
429
|
+
p = sub.add_parser("search", help="search memory")
|
|
430
|
+
p.add_argument("query", nargs="+")
|
|
431
|
+
p.add_argument("--source")
|
|
432
|
+
p.add_argument("--limit", type=int, default=8)
|
|
433
|
+
p = sub.add_parser("connect", help="give AI tools access to memory via MCP")
|
|
434
|
+
p.add_argument("tool", nargs="?")
|
|
435
|
+
p = sub.add_parser("disconnect", help="remove Anamnesis from an AI tool")
|
|
436
|
+
p.add_argument("tool")
|
|
437
|
+
p = sub.add_parser("share", help="sync memory across computers through a synced folder")
|
|
438
|
+
p.add_argument("folder", nargs="?", help="default: iCloud Drive/Anamnesis")
|
|
439
|
+
p = sub.add_parser("join", help="add this computer to memory shared from another one")
|
|
440
|
+
p.add_argument("code")
|
|
441
|
+
p.add_argument("folder", nargs="?", help="default: iCloud Drive/Anamnesis")
|
|
442
|
+
sub.add_parser("devices", help="computers sharing this memory")
|
|
443
|
+
sub.add_parser("unshare", help="stop syncing memory on this computer")
|
|
444
|
+
sub.add_parser("status", help="what is stored, and which tools are connected")
|
|
445
|
+
sub.add_parser("keep", help="stop Claude Code deleting its sessions after 30 days")
|
|
446
|
+
sub.add_parser("mcp", help="run the MCP server on stdio")
|
|
447
|
+
sub.add_parser("tui", help="open the terminal UI (default)")
|
|
448
|
+
from anamnesis.cli import node_cmd
|
|
449
|
+
|
|
450
|
+
node_cmd.add_parser(sub)
|
|
451
|
+
return parser
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def cmd_setup(settings: Settings, args: argparse.Namespace) -> int:
|
|
455
|
+
from anamnesis.cli import setup_cmd
|
|
456
|
+
|
|
457
|
+
return setup_cmd.run(settings, args)
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
COMMANDS = {
|
|
461
|
+
"setup": cmd_setup,
|
|
462
|
+
"sync": cmd_sync,
|
|
463
|
+
"import": cmd_import,
|
|
464
|
+
"search": cmd_search,
|
|
465
|
+
"connect": cmd_connect,
|
|
466
|
+
"disconnect": cmd_disconnect,
|
|
467
|
+
"status": cmd_status,
|
|
468
|
+
"keep": cmd_keep,
|
|
469
|
+
"share": cmd_share,
|
|
470
|
+
"join": cmd_join,
|
|
471
|
+
"devices": cmd_devices,
|
|
472
|
+
"unshare": cmd_unshare,
|
|
473
|
+
"mcp": cmd_mcp,
|
|
474
|
+
"tui": cmd_tui,
|
|
475
|
+
None: cmd_tui,
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def cmd_node(settings: Settings, args: argparse.Namespace) -> int:
|
|
480
|
+
from anamnesis.cli import node_cmd
|
|
481
|
+
|
|
482
|
+
return node_cmd.run(settings, args)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
COMMANDS["node"] = cmd_node
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _search_shorthand(argv: list[str]) -> list[str]:
|
|
489
|
+
"""`anam <words>` searches: anything that isn't a command or an option is a query.
|
|
490
|
+
|
|
491
|
+
Also splits a quoted command line, e.g. `anam "search preview environments"`.
|
|
492
|
+
"""
|
|
493
|
+
if not argv or argv[0].startswith("-"):
|
|
494
|
+
return argv
|
|
495
|
+
first, *rest = argv[0].split(maxsplit=1)
|
|
496
|
+
if first in COMMANDS:
|
|
497
|
+
return [first, *rest, *argv[1:]] if rest else argv
|
|
498
|
+
return ["search", *" ".join(argv).split()]
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def main(argv: list[str] | None = None) -> int:
|
|
502
|
+
"""Run a command. Ctrl+C and unexpected errors end in one plain line, never a traceback
|
|
503
|
+
(it goes to the log; ANAMNESIS_DEBUG=1 shows it here)."""
|
|
504
|
+
try:
|
|
505
|
+
return _run(argv)
|
|
506
|
+
except KeyboardInterrupt:
|
|
507
|
+
print("\nCancelled.", file=sys.stderr)
|
|
508
|
+
return 130
|
|
509
|
+
except BrokenPipeError: # output piped into `head` and the like
|
|
510
|
+
with contextlib.suppress(Exception):
|
|
511
|
+
sys.stdout = open(os.devnull, "w") # noqa: SIM115 (silence the flush at exit)
|
|
512
|
+
return 0
|
|
513
|
+
except Exception as e:
|
|
514
|
+
if os.environ.get("ANAMNESIS_DEBUG"):
|
|
515
|
+
raise
|
|
516
|
+
log_file = _log_crash()
|
|
517
|
+
where = f" Details: {log_file}" if log_file else ""
|
|
518
|
+
print(f"anam: {type(e).__name__}: {e}.{where}", file=sys.stderr)
|
|
519
|
+
print(f"Please report it: {ISSUES}", file=sys.stderr)
|
|
520
|
+
return 1
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
ISSUES = "https://github.com/devHaitham481/anamnesis/issues"
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _log_crash() -> Path | None:
|
|
527
|
+
import traceback
|
|
528
|
+
|
|
529
|
+
try:
|
|
530
|
+
settings = load_settings()
|
|
531
|
+
settings.data_dir.mkdir(parents=True, exist_ok=True)
|
|
532
|
+
path = settings.data_dir / "anamnesis.log"
|
|
533
|
+
with path.open("a", encoding="utf-8") as f:
|
|
534
|
+
f.write(f"\n--- anam {' '.join(sys.argv[1:])}\n{traceback.format_exc()}")
|
|
535
|
+
return path
|
|
536
|
+
except Exception:
|
|
537
|
+
return None
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _run(argv: list[str] | None) -> int:
|
|
541
|
+
argv = _search_shorthand(list(sys.argv[1:] if argv is None else argv))
|
|
542
|
+
args = build_parser().parse_args(argv)
|
|
543
|
+
settings = load_settings()
|
|
544
|
+
serving = args.command == "node" and args.node_command == "serve"
|
|
545
|
+
if args.command not in ("tui", None, "mcp") and not serving:
|
|
546
|
+
logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(name)s: %(message)s")
|
|
547
|
+
return int(COMMANDS[args.command](settings, args))
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
if __name__ == "__main__":
|
|
551
|
+
sys.exit(main())
|