feat(cli): add event commands, --json/--agent flag, agent output sanitization, and edge-case hardening for CLI SDKs (#4649)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+137
-15
@@ -3,6 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json as _json
|
||||
import os
|
||||
import stat as _stat_mod
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
@@ -43,7 +45,14 @@ entity_app = typer.Typer(
|
||||
no_args_is_help=True,
|
||||
rich_markup_mode="rich",
|
||||
)
|
||||
# entity_app registered after Memory commands to control panel ordering
|
||||
|
||||
event_app = typer.Typer(
|
||||
name="event",
|
||||
help="Inspect background processing events.",
|
||||
no_args_is_help=True,
|
||||
rich_markup_mode="rich",
|
||||
)
|
||||
# entity_app and event_app registered after Memory commands to control panel ordering
|
||||
|
||||
|
||||
# ── Helpers ───────────────────────────────────────────────────────────────
|
||||
@@ -114,9 +123,22 @@ def _resolve_ids(
|
||||
}
|
||||
|
||||
|
||||
def _stdin_is_piped() -> bool:
|
||||
"""Return True only when stdin is an actual pipe or file redirect — not a bare open fd."""
|
||||
from mem0_cli.state import is_agent_mode
|
||||
|
||||
if is_agent_mode():
|
||||
return False
|
||||
try:
|
||||
mode = os.fstat(sys.stdin.fileno()).st_mode
|
||||
return _stat_mod.S_ISFIFO(mode) or _stat_mod.S_ISREG(mode)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _read_stdin() -> str | None:
|
||||
"""Read from stdin if it is piped (not a TTY)."""
|
||||
if not sys.stdin.isatty():
|
||||
"""Read from stdin if it is an actual pipe or file redirect (not a TTY, not agent mode)."""
|
||||
if _stdin_is_piped():
|
||||
return sys.stdin.read().strip() or None
|
||||
return None
|
||||
|
||||
@@ -128,7 +150,18 @@ def _read_stdin() -> str | None:
|
||||
def main_callback(
|
||||
ctx: typer.Context,
|
||||
version: bool = typer.Option(False, "--version", help="Show version and exit."),
|
||||
json_agent: bool = typer.Option(
|
||||
False,
|
||||
"--json",
|
||||
"--agent",
|
||||
help="Output as JSON for agent/programmatic use.",
|
||||
is_eager=False,
|
||||
),
|
||||
) -> None:
|
||||
if json_agent:
|
||||
from mem0_cli.state import set_agent_mode
|
||||
|
||||
set_agent_mode(True)
|
||||
if version:
|
||||
from mem0_cli.commands.utils import cmd_version
|
||||
|
||||
@@ -273,7 +306,7 @@ def search(
|
||||
None, "--base-url", help="Override API base URL.", rich_help_panel="Connection"
|
||||
),
|
||||
) -> None:
|
||||
"""Search memories by semantic query.
|
||||
"""Query your memory store — semantic, keyword, or hybrid retrieval.
|
||||
|
||||
Examples:
|
||||
mem0 search "preferences" --user-id alice
|
||||
@@ -702,6 +735,70 @@ def entity_delete(
|
||||
app.add_typer(entity_app, name="entity", rich_help_panel="Management")
|
||||
|
||||
|
||||
# ── Event subcommands ─────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@event_app.command("list")
|
||||
def event_list(
|
||||
output: str = typer.Option(
|
||||
"table", "--output", "-o", help="Output: table, json.", rich_help_panel="Output"
|
||||
),
|
||||
api_key: str | None = typer.Option(
|
||||
None,
|
||||
"--api-key",
|
||||
help="Override API key.",
|
||||
envvar="MEM0_API_KEY",
|
||||
rich_help_panel="Connection",
|
||||
),
|
||||
base_url: str | None = typer.Option(
|
||||
None, "--base-url", help="Override API base URL.", rich_help_panel="Connection"
|
||||
),
|
||||
) -> None:
|
||||
"""List recent background processing events.
|
||||
|
||||
Examples:
|
||||
mem0 event list
|
||||
mem0 event list -o json
|
||||
"""
|
||||
from mem0_cli.commands.events_cmd import cmd_event_list
|
||||
|
||||
backend = _get_backend(api_key, base_url)
|
||||
cmd_event_list(backend, output=output)
|
||||
|
||||
|
||||
@event_app.command("status")
|
||||
def event_status(
|
||||
event_id: str = typer.Argument(..., help="Event ID to inspect."),
|
||||
output: str = typer.Option(
|
||||
"text", "--output", "-o", help="Output: text, json.", rich_help_panel="Output"
|
||||
),
|
||||
api_key: str | None = typer.Option(
|
||||
None,
|
||||
"--api-key",
|
||||
help="Override API key.",
|
||||
envvar="MEM0_API_KEY",
|
||||
rich_help_panel="Connection",
|
||||
),
|
||||
base_url: str | None = typer.Option(
|
||||
None, "--base-url", help="Override API base URL.", rich_help_panel="Connection"
|
||||
),
|
||||
) -> None:
|
||||
"""Check the status of a specific background event.
|
||||
|
||||
Examples:
|
||||
mem0 event status <event-id>
|
||||
mem0 event status <event-id> -o json
|
||||
"""
|
||||
from mem0_cli.commands.events_cmd import cmd_event_status
|
||||
|
||||
backend = _get_backend(api_key, base_url)
|
||||
cmd_event_status(backend, event_id, output=output)
|
||||
|
||||
|
||||
# ── Event subgroup ──
|
||||
app.add_typer(event_app, name="event", rich_help_panel="Management")
|
||||
|
||||
|
||||
# ── Management commands ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -715,6 +812,9 @@ def init(
|
||||
code: str | None = typer.Option(
|
||||
None, "--code", help="Verification code (use with --email for non-interactive login)."
|
||||
),
|
||||
force: bool = typer.Option(
|
||||
False, "--force", help="Overwrite existing config without confirmation."
|
||||
),
|
||||
) -> None:
|
||||
"""Interactive setup wizard for mem0 CLI.
|
||||
|
||||
@@ -726,7 +826,7 @@ def init(
|
||||
"""
|
||||
from mem0_cli.commands.init_cmd import run_init
|
||||
|
||||
run_init(api_key=api_key, user_id=user_id, email=email, code=code)
|
||||
run_init(api_key=api_key, user_id=user_id, email=email, code=code, force=force)
|
||||
|
||||
|
||||
# (entity_app registered at module level, below sub-group definitions)
|
||||
@@ -831,7 +931,7 @@ def _build_help_json() -> dict:
|
||||
},
|
||||
},
|
||||
"search": {
|
||||
"description": "Search memories by semantic query.",
|
||||
"description": "Query your memory store — semantic, keyword, or hybrid retrieval.",
|
||||
"usage": "mem0 search <query> [OPTIONS]",
|
||||
"arguments": {"query": {"description": "Search query.", "required": False}},
|
||||
"options": {
|
||||
@@ -935,6 +1035,24 @@ def _build_help_json() -> dict:
|
||||
"value": {"description": "Value to set.", "required": True},
|
||||
},
|
||||
},
|
||||
"event": {
|
||||
"description": "Inspect background processing events.",
|
||||
"subcommands": {
|
||||
"list": {
|
||||
"description": "List recent background processing events.",
|
||||
"usage": "mem0 event list [OPTIONS]",
|
||||
"options": {"--output, -o": "Output format: table, json."},
|
||||
},
|
||||
"status": {
|
||||
"description": "Check the status of a specific background event.",
|
||||
"usage": "mem0 event status <event_id> [OPTIONS]",
|
||||
"arguments": {
|
||||
"event_id": {"description": "Event ID to inspect.", "required": True}
|
||||
},
|
||||
"options": {"--output, -o": "Output format: text, json."},
|
||||
},
|
||||
},
|
||||
},
|
||||
"entity": {
|
||||
"description": "Manage entities.",
|
||||
"subcommands": {
|
||||
@@ -986,6 +1104,7 @@ def _build_help_json() -> dict:
|
||||
"global_options": {
|
||||
"--api-key": "Override API key (env: MEM0_API_KEY).",
|
||||
"--base-url": "Override API base URL.",
|
||||
"--json / --agent": "Output as JSON for agent/programmatic use.",
|
||||
"--help": "Show help for a command.",
|
||||
"--version": "Show version and exit.",
|
||||
},
|
||||
@@ -1015,7 +1134,7 @@ def help(
|
||||
console.print("Usage: mem0 <command> [OPTIONS]\n")
|
||||
console.print("[bold]Commands:[/]")
|
||||
console.print(" add Add a memory from text, messages, file, or stdin")
|
||||
console.print(" search Search memories by semantic query")
|
||||
console.print(" search Query your memory store (semantic, keyword, hybrid)")
|
||||
console.print(" get Get a specific memory by ID")
|
||||
console.print(" list List memories with optional filters")
|
||||
console.print(" update Update a memory's text or metadata")
|
||||
@@ -1023,6 +1142,7 @@ def help(
|
||||
console.print(" import Import memories from a JSON file")
|
||||
console.print(" config Manage configuration (show, get, set)")
|
||||
console.print(" entity Manage entities (list, delete)")
|
||||
console.print(" event Inspect background events (list, status)")
|
||||
console.print(" init Interactive setup wizard")
|
||||
console.print(" status Check connectivity and authentication")
|
||||
console.print()
|
||||
@@ -1031,14 +1151,6 @@ def help(
|
||||
console.print()
|
||||
|
||||
|
||||
@app.command(rich_help_panel="Utility")
|
||||
def version() -> None:
|
||||
"""Show version and exit."""
|
||||
from mem0_cli.commands.utils import cmd_version
|
||||
|
||||
cmd_version()
|
||||
|
||||
|
||||
# Register config subgroup here so it appears after help in Management panel
|
||||
app.add_typer(config_app, name="config", rich_help_panel="Management")
|
||||
|
||||
@@ -1047,4 +1159,14 @@ app.add_typer(config_app, name="config", rich_help_panel="Management")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
import sys
|
||||
|
||||
# Allow --json/--agent anywhere in the command line (not just before subcommand).
|
||||
_json_flags = {"--json", "--agent"}
|
||||
if any(a in _json_flags for a in sys.argv[1:]):
|
||||
from mem0_cli.state import set_agent_mode
|
||||
|
||||
set_agent_mode(True)
|
||||
sys.argv = [sys.argv[0]] + [a for a in sys.argv[1:] if a not in _json_flags]
|
||||
|
||||
app()
|
||||
|
||||
@@ -104,6 +104,12 @@ class Backend(ABC):
|
||||
@abstractmethod
|
||||
def entities(self, entity_type: str) -> list[dict]: ...
|
||||
|
||||
@abstractmethod
|
||||
def list_events(self) -> list[dict]: ...
|
||||
|
||||
@abstractmethod
|
||||
def get_event(self, event_id: str) -> dict: ...
|
||||
|
||||
|
||||
def get_backend(config: Mem0Config) -> Backend:
|
||||
"""Return the Platform backend."""
|
||||
|
||||
@@ -265,18 +265,21 @@ class PlatformBackend(Backend):
|
||||
app_id: str | None = None,
|
||||
run_id: str | None = None,
|
||||
) -> dict:
|
||||
params: dict[str, str] = {}
|
||||
if user_id:
|
||||
params["user_id"] = user_id
|
||||
if agent_id:
|
||||
params["agent_id"] = agent_id
|
||||
if app_id:
|
||||
params["app_id"] = app_id
|
||||
if run_id:
|
||||
params["run_id"] = run_id
|
||||
if not params:
|
||||
# v2 endpoint: DELETE /v2/entities/{entity_type}/{entity_id}/
|
||||
type_map = {
|
||||
"user": user_id,
|
||||
"agent": agent_id,
|
||||
"app": app_id,
|
||||
"run": run_id,
|
||||
}
|
||||
entities = {t: v for t, v in type_map.items() if v}
|
||||
if not entities:
|
||||
raise ValueError("At least one entity ID is required for delete_entities.")
|
||||
return self._request("DELETE", "/v1/entities/", params=params)
|
||||
# Delete each provided entity via the v2 path-based endpoint
|
||||
result: dict = {}
|
||||
for entity_type, entity_id in entities.items():
|
||||
result = self._request("DELETE", f"/v2/entities/{entity_type}/{entity_id}/")
|
||||
return result
|
||||
|
||||
def status(
|
||||
self,
|
||||
@@ -284,19 +287,9 @@ class PlatformBackend(Backend):
|
||||
user_id: str | None = None,
|
||||
agent_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Check connectivity by making a lightweight API call."""
|
||||
"""Check connectivity using the ping endpoint."""
|
||||
try:
|
||||
# If entity IDs are available, validate with a minimal memories list
|
||||
if user_id or agent_id:
|
||||
payload: dict[str, Any] = {}
|
||||
params = {"page": "1", "page_size": "1"}
|
||||
api_filters = self._build_filters(user_id=user_id, agent_id=agent_id)
|
||||
if api_filters:
|
||||
payload["filters"] = api_filters
|
||||
self._request("POST", "/v2/memories/", json=payload, params=params)
|
||||
else:
|
||||
# No entity IDs — use entities endpoint to validate API key
|
||||
self._request("GET", "/v1/entities/")
|
||||
self._request("GET", "/v1/ping/")
|
||||
return {"connected": True, "backend": "platform", "base_url": self.base_url}
|
||||
except Exception as e:
|
||||
return {"connected": False, "backend": "platform", "error": str(e)}
|
||||
@@ -311,6 +304,13 @@ class PlatformBackend(Backend):
|
||||
items = [e for e in items if e.get("type", "").lower() == target_type]
|
||||
return items
|
||||
|
||||
def list_events(self) -> list[dict]:
|
||||
result = self._request("GET", "/v1/events/")
|
||||
return result if isinstance(result, list) else result.get("results", [])
|
||||
|
||||
def get_event(self, event_id: str) -> dict:
|
||||
return self._request("GET", f"/v1/event/{event_id}/")
|
||||
|
||||
|
||||
class AuthError(Exception):
|
||||
pass
|
||||
|
||||
@@ -43,6 +43,10 @@ def _sym(fancy: str, plain: str) -> str:
|
||||
|
||||
def print_banner(console: Console) -> None:
|
||||
"""Print the mem0 welcome banner."""
|
||||
from mem0_cli.state import is_agent_mode
|
||||
|
||||
if is_agent_mode():
|
||||
return
|
||||
logo_text = Text(LOGO, style=f"bold {BRAND_COLOR}")
|
||||
tagline = Text(f" {TAGLINE}\n", style=f"{ACCENT_COLOR}")
|
||||
|
||||
@@ -61,11 +65,28 @@ def print_banner(console: Console) -> None:
|
||||
|
||||
|
||||
def print_success(console: Console, message: str) -> None:
|
||||
from mem0_cli.state import is_agent_mode
|
||||
|
||||
if is_agent_mode():
|
||||
return
|
||||
sym = _sym("✓", "[ok]")
|
||||
console.print(f"[{SUCCESS_COLOR}]{sym}[/] {message}")
|
||||
|
||||
|
||||
def print_error(console: Console, message: str, hint: str | None = None) -> None:
|
||||
from mem0_cli.state import get_current_command, is_agent_mode
|
||||
|
||||
if is_agent_mode():
|
||||
import json as _json
|
||||
|
||||
envelope = {
|
||||
"status": "error",
|
||||
"command": get_current_command(),
|
||||
"error": message,
|
||||
"data": None,
|
||||
}
|
||||
print(_json.dumps(envelope))
|
||||
return
|
||||
sym = _sym("✗", "[error]")
|
||||
console.print(f"[{ERROR_COLOR}]{sym} Error:[/] {message}")
|
||||
if hint:
|
||||
@@ -73,11 +94,19 @@ def print_error(console: Console, message: str, hint: str | None = None) -> None
|
||||
|
||||
|
||||
def print_warning(console: Console, message: str) -> None:
|
||||
from mem0_cli.state import is_agent_mode
|
||||
|
||||
if is_agent_mode():
|
||||
return
|
||||
sym = _sym("⚠", "[warn]")
|
||||
console.print(f"[{WARNING_COLOR}]{sym}[/] {message}")
|
||||
|
||||
|
||||
def print_info(console: Console, message: str) -> None:
|
||||
from mem0_cli.state import is_agent_mode
|
||||
|
||||
if is_agent_mode():
|
||||
return
|
||||
sym = _sym("◆", "*")
|
||||
console.print(f"[{BRAND_COLOR}]{sym}[/] {message}")
|
||||
|
||||
@@ -89,7 +118,9 @@ def timed_status(console: Console, message: str):
|
||||
The spinner and timing output are sent to stderr (via ``_err``) so they
|
||||
never contaminate machine-readable stdout. The *console* parameter is
|
||||
kept for backward compatibility but is not used for spinner output.
|
||||
In agent mode the spinner is suppressed entirely.
|
||||
"""
|
||||
from mem0_cli.state import is_agent_mode
|
||||
|
||||
class _Ctx:
|
||||
def __init__(self):
|
||||
@@ -97,6 +128,13 @@ def timed_status(console: Console, message: str):
|
||||
self.error_msg = ""
|
||||
|
||||
ctx = _Ctx()
|
||||
if is_agent_mode():
|
||||
try:
|
||||
yield ctx
|
||||
except Exception:
|
||||
raise
|
||||
return
|
||||
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
with Status(f"[{DIM_COLOR}]{message}[/]", console=_err):
|
||||
@@ -105,6 +143,11 @@ def timed_status(console: Console, message: str):
|
||||
elapsed = time.perf_counter() - start
|
||||
if ctx.error_msg:
|
||||
print_error(_err, f"{ctx.error_msg} ({elapsed:.2f}s)")
|
||||
if "Authentication failed" in ctx.error_msg:
|
||||
_err.print(
|
||||
f" [{DIM_COLOR}]Run [bold]mem0 init[/bold] to reconfigure your API key"
|
||||
f" · [bold]https://app.mem0.ai/dashboard/api-keys[/bold][/]"
|
||||
)
|
||||
raise
|
||||
else:
|
||||
elapsed = time.perf_counter() - start
|
||||
@@ -114,11 +157,14 @@ def timed_status(console: Console, message: str):
|
||||
|
||||
def print_scope(console: Console, **ids: str | None) -> None:
|
||||
"""Show active entity scope if any IDs are set."""
|
||||
from mem0_cli.state import is_agent_mode
|
||||
|
||||
if is_agent_mode():
|
||||
return
|
||||
parts = []
|
||||
for key, val in ids.items():
|
||||
if val:
|
||||
label = key.replace("_", " ").replace("id", "ID").strip()
|
||||
parts.append(f"{label}={val}")
|
||||
parts.append(f"{key}={val}")
|
||||
if parts:
|
||||
scope_str = ", ".join(parts)
|
||||
console.print(f" [{DIM_COLOR}]Scope: {scope_str}[/]")
|
||||
|
||||
@@ -20,12 +20,17 @@ err_console = Console(stderr=True)
|
||||
|
||||
def cmd_config_show(*, output: str = "text") -> None:
|
||||
"""Display current configuration (secrets redacted)."""
|
||||
from mem0_cli.output import format_json_envelope
|
||||
from mem0_cli.output import format_agent_envelope
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("config show")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
|
||||
config = load_config()
|
||||
|
||||
if output == "json":
|
||||
format_json_envelope(
|
||||
if output in ("json", "agent"):
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="config show",
|
||||
data={
|
||||
@@ -84,25 +89,44 @@ def cmd_config_show(*, output: str = "text") -> None:
|
||||
|
||||
def cmd_config_get(key: str) -> None:
|
||||
"""Get a config value."""
|
||||
from mem0_cli.output import format_agent_envelope
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("config get")
|
||||
config = load_config()
|
||||
value = get_nested_value(config, key)
|
||||
|
||||
if value is None:
|
||||
print_error(err_console, f"Unknown config key: {key}")
|
||||
return
|
||||
|
||||
display_value = (
|
||||
redact_key(str(value)) if ("api_key" in key or "key" in key.split(".")[-1:]) else str(value)
|
||||
)
|
||||
|
||||
if is_agent_mode():
|
||||
format_agent_envelope(
|
||||
console, command="config get", data={"key": key, "value": display_value}
|
||||
)
|
||||
else:
|
||||
# Redact secrets
|
||||
if "api_key" in key or "key" in key.split(".")[-1:]:
|
||||
console.print(redact_key(str(value)))
|
||||
else:
|
||||
console.print(str(value))
|
||||
console.print(display_value)
|
||||
|
||||
|
||||
def cmd_config_set(key: str, value: str) -> None:
|
||||
"""Set a config value."""
|
||||
from mem0_cli.output import format_agent_envelope
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("config set")
|
||||
config = load_config()
|
||||
if set_nested_value(config, key, value):
|
||||
save_config(config)
|
||||
display = redact_key(value) if "key" in key else value
|
||||
print_success(console, f"{key} = {display}")
|
||||
if is_agent_mode():
|
||||
format_agent_envelope(
|
||||
console, command="config set", data={"key": key, "value": display}
|
||||
)
|
||||
else:
|
||||
print_success(console, f"{key} = {display}")
|
||||
else:
|
||||
print_error(err_console, f"Unknown config key: {key}")
|
||||
|
||||
@@ -18,7 +18,7 @@ from mem0_cli.branding import (
|
||||
print_success,
|
||||
timed_status,
|
||||
)
|
||||
from mem0_cli.output import format_json
|
||||
from mem0_cli.output import format_agent_envelope, format_json
|
||||
|
||||
console = Console()
|
||||
err_console = Console(stderr=True)
|
||||
@@ -26,6 +26,11 @@ err_console = Console(stderr=True)
|
||||
|
||||
def cmd_entities_list(backend: Backend, entity_type: str, *, output: str) -> None:
|
||||
"""List entities of a given type."""
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("entity list")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
valid_types = {"users", "agents", "apps", "runs"}
|
||||
if entity_type not in valid_types:
|
||||
print_error(
|
||||
@@ -42,6 +47,16 @@ def cmd_entities_list(backend: Backend, entity_type: str, *, output: str) -> Non
|
||||
raise typer.Exit(1) from None
|
||||
_elapsed = _time.perf_counter() - _start
|
||||
|
||||
if output == "agent":
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="entity list",
|
||||
data=results,
|
||||
count=len(results),
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
return
|
||||
|
||||
if output == "json":
|
||||
format_json(console, results)
|
||||
return
|
||||
@@ -77,41 +92,39 @@ def cmd_entities_delete(
|
||||
output: str,
|
||||
) -> None:
|
||||
"""Delete an entity and all its memories (cascade delete)."""
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("entity delete")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
if not force:
|
||||
print_error(err_console, "Destructive operation requires --force in agent mode.")
|
||||
raise typer.Exit(1)
|
||||
if not any([user_id, agent_id, app_id, run_id]):
|
||||
print_error(
|
||||
err_console, "Provide at least one of --user-id, --agent-id, --app-id, --run-id."
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
scope_parts = []
|
||||
if user_id:
|
||||
scope_parts.append(f"user={user_id}")
|
||||
if agent_id:
|
||||
scope_parts.append(f"agent={agent_id}")
|
||||
if app_id:
|
||||
scope_parts.append(f"app={app_id}")
|
||||
if run_id:
|
||||
scope_parts.append(f"run={run_id}")
|
||||
scope_str = ", ".join(scope_parts)
|
||||
|
||||
if dry_run:
|
||||
scope_parts = []
|
||||
if user_id:
|
||||
scope_parts.append(f"user={user_id}")
|
||||
if agent_id:
|
||||
scope_parts.append(f"agent={agent_id}")
|
||||
if app_id:
|
||||
scope_parts.append(f"app={app_id}")
|
||||
if run_id:
|
||||
scope_parts.append(f"run={run_id}")
|
||||
scope = ", ".join(scope_parts)
|
||||
print_info(console, f"Would delete entity {scope} and all its memories.")
|
||||
print_info(console, f"Would delete entity {scope_str} and all its memories.")
|
||||
print_info(console, "No changes made (dry run).")
|
||||
return
|
||||
|
||||
if not force:
|
||||
scope_parts = []
|
||||
if user_id:
|
||||
scope_parts.append(f"user={user_id}")
|
||||
if agent_id:
|
||||
scope_parts.append(f"agent={agent_id}")
|
||||
if app_id:
|
||||
scope_parts.append(f"app={app_id}")
|
||||
if run_id:
|
||||
scope_parts.append(f"run={run_id}")
|
||||
scope = ", ".join(scope_parts)
|
||||
|
||||
confirm = typer.confirm(
|
||||
f"\n \u26a0 Delete entity {scope} AND all its memories? This cannot be undone."
|
||||
f"\n \u26a0 Delete entity {scope_str} AND all its memories? This cannot be undone."
|
||||
)
|
||||
if not confirm:
|
||||
print_info(console, "Cancelled.")
|
||||
@@ -131,7 +144,25 @@ def cmd_entities_delete(
|
||||
raise typer.Exit(1) from None
|
||||
_elapsed = _time.perf_counter() - _start
|
||||
|
||||
if output == "json":
|
||||
scope = {
|
||||
k: v
|
||||
for k, v in {
|
||||
"user_id": user_id,
|
||||
"agent_id": agent_id,
|
||||
"app_id": app_id,
|
||||
"run_id": run_id,
|
||||
}.items()
|
||||
if v
|
||||
}
|
||||
if output == "agent":
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="entity delete",
|
||||
data={"deleted": True},
|
||||
scope=scope or None,
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
elif output == "json":
|
||||
format_json(console, result)
|
||||
elif output != "quiet":
|
||||
print_success(console, f"Entity deleted with all memories ({_elapsed:.2f}s)")
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Event commands: list and status."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.panel import Panel
|
||||
from rich.table import Table
|
||||
|
||||
from mem0_cli.backend.base import Backend
|
||||
from mem0_cli.branding import (
|
||||
ACCENT_COLOR,
|
||||
BRAND_COLOR,
|
||||
DIM_COLOR,
|
||||
ERROR_COLOR,
|
||||
SUCCESS_COLOR,
|
||||
WARNING_COLOR,
|
||||
print_info,
|
||||
timed_status,
|
||||
)
|
||||
from mem0_cli.output import format_agent_envelope, format_json
|
||||
|
||||
console = Console()
|
||||
err_console = Console(stderr=True)
|
||||
|
||||
_STATUS_STYLE = {
|
||||
"SUCCEEDED": f"[{SUCCESS_COLOR}]SUCCEEDED[/]",
|
||||
"PENDING": f"[{ACCENT_COLOR}]PENDING[/]",
|
||||
"FAILED": f"[{ERROR_COLOR}]FAILED[/]",
|
||||
"PROCESSING": f"[{WARNING_COLOR}]PROCESSING[/]",
|
||||
}
|
||||
|
||||
|
||||
def _status_styled(status: str) -> str:
|
||||
return _STATUS_STYLE.get(status.upper(), status)
|
||||
|
||||
|
||||
def cmd_event_list(backend: Backend, *, output: str = "table") -> None:
|
||||
"""List recent background events."""
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("event list")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
import time as _time
|
||||
|
||||
_start = _time.perf_counter()
|
||||
with timed_status(err_console, "Fetching events...") as _ts:
|
||||
try:
|
||||
results = backend.list_events()
|
||||
except Exception as e:
|
||||
_ts.error_msg = str(e)
|
||||
raise typer.Exit(1) from None
|
||||
|
||||
_elapsed = _time.perf_counter() - _start
|
||||
|
||||
if output == "agent":
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="event list",
|
||||
data=results,
|
||||
count=len(results),
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
return
|
||||
|
||||
if output == "json":
|
||||
format_json(console, results)
|
||||
return
|
||||
|
||||
if not results:
|
||||
console.print()
|
||||
print_info(console, "No events found.")
|
||||
console.print()
|
||||
return
|
||||
|
||||
table = Table(
|
||||
border_style=BRAND_COLOR,
|
||||
header_style=f"bold {ACCENT_COLOR}",
|
||||
row_styles=["", "dim"],
|
||||
padding=(0, 1),
|
||||
)
|
||||
table.add_column("Event ID", style="dim", max_width=10, no_wrap=True)
|
||||
table.add_column("Type", max_width=14)
|
||||
table.add_column("Status", max_width=12)
|
||||
table.add_column("Latency", max_width=10, justify="right")
|
||||
table.add_column("Created", max_width=20)
|
||||
|
||||
for ev in results:
|
||||
ev_id = str(ev.get("id", ""))[:8]
|
||||
ev_type = str(ev.get("event_type", "—"))
|
||||
status = str(ev.get("status", "—"))
|
||||
latency = ev.get("latency")
|
||||
latency_str = f"{latency:.0f}ms" if isinstance(latency, (int, float)) else "—"
|
||||
created = str(ev.get("created_at", "—"))[:19].replace("T", " ")
|
||||
table.add_row(ev_id, ev_type, _status_styled(status), latency_str, created)
|
||||
|
||||
console.print()
|
||||
console.print(table)
|
||||
console.print(f" [{DIM_COLOR}]{len(results)} event{'s' if len(results) != 1 else ''}[/]")
|
||||
console.print()
|
||||
|
||||
|
||||
def cmd_event_status(backend: Backend, event_id: str, *, output: str = "text") -> None:
|
||||
"""Get the status of a specific background event."""
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("event status")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
import time as _time
|
||||
|
||||
_start = _time.perf_counter()
|
||||
with timed_status(err_console, "Fetching event...") as _ts:
|
||||
try:
|
||||
ev = backend.get_event(event_id)
|
||||
except Exception as e:
|
||||
_ts.error_msg = str(e)
|
||||
raise typer.Exit(1) from None
|
||||
|
||||
_elapsed = _time.perf_counter() - _start
|
||||
|
||||
if output == "agent":
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="event status",
|
||||
data=ev,
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
return
|
||||
|
||||
if output == "json":
|
||||
format_json(console, ev)
|
||||
return
|
||||
|
||||
status = str(ev.get("status", "—"))
|
||||
ev_type = str(ev.get("event_type", "—"))
|
||||
latency = ev.get("latency")
|
||||
latency_str = f"{latency:.0f}ms" if isinstance(latency, (int, float)) else "—"
|
||||
created = str(ev.get("created_at", "—"))[:19].replace("T", " ")
|
||||
updated = str(ev.get("updated_at", "—"))[:19].replace("T", " ")
|
||||
results = ev.get("results")
|
||||
|
||||
lines = []
|
||||
lines.append(f" [{DIM_COLOR}]Event ID:[/] {event_id}")
|
||||
lines.append(f" [{DIM_COLOR}]Type:[/] {ev_type}")
|
||||
lines.append(f" [{DIM_COLOR}]Status:[/] {_status_styled(status)}")
|
||||
lines.append(f" [{DIM_COLOR}]Latency:[/] {latency_str}")
|
||||
lines.append(f" [{DIM_COLOR}]Created:[/] {created}")
|
||||
lines.append(f" [{DIM_COLOR}]Updated:[/] {updated}")
|
||||
|
||||
if results:
|
||||
lines.append("")
|
||||
lines.append(f" [{DIM_COLOR}]Results ({len(results)}):[/]")
|
||||
for r in results:
|
||||
mem_id = str(r.get("id", ""))[:8]
|
||||
data = r.get("data", {})
|
||||
memory = data.get("memory", "") if isinstance(data, dict) else str(data)
|
||||
ev_name = str(r.get("event", ""))
|
||||
user = str(r.get("user_id", ""))
|
||||
detail = f"{ev_name} {memory}"
|
||||
if user:
|
||||
detail += f" [{DIM_COLOR}](user_id={user})[/]"
|
||||
lines.append(f" [{SUCCESS_COLOR}]·[/] {detail} [{DIM_COLOR}]({mem_id})[/]")
|
||||
|
||||
content = "\n".join(lines)
|
||||
panel = Panel(
|
||||
content,
|
||||
title=f"[{BRAND_COLOR}]Event Status[/]",
|
||||
title_align="left",
|
||||
border_style=BRAND_COLOR,
|
||||
padding=(1, 1),
|
||||
)
|
||||
console.print()
|
||||
console.print(panel)
|
||||
console.print()
|
||||
@@ -19,7 +19,7 @@ from mem0_cli.branding import (
|
||||
print_info,
|
||||
print_success,
|
||||
)
|
||||
from mem0_cli.config import DEFAULT_BASE_URL, Mem0Config, save_config
|
||||
from mem0_cli.config import CONFIG_FILE, DEFAULT_BASE_URL, Mem0Config, load_config, save_config
|
||||
|
||||
console = Console()
|
||||
err_console = Console(stderr=True)
|
||||
@@ -169,6 +169,7 @@ def run_init(
|
||||
user_id: str | None = None,
|
||||
email: str | None = None,
|
||||
code: str | None = None,
|
||||
force: bool = False,
|
||||
) -> None:
|
||||
"""Interactive setup wizard for mem0 CLI.
|
||||
|
||||
@@ -184,6 +185,29 @@ def run_init(
|
||||
print_error(err_console, "--code requires --email.")
|
||||
raise typer.Exit(1)
|
||||
|
||||
# Warn if an existing config with an API key would be overwritten
|
||||
if not force and CONFIG_FILE.exists():
|
||||
existing = load_config()
|
||||
if existing.platform.api_key:
|
||||
from mem0_cli.config import redact_key
|
||||
|
||||
console.print(
|
||||
f"\n [{BRAND_COLOR}]Existing configuration found[/] "
|
||||
f"[{DIM_COLOR}](API key: {redact_key(existing.platform.api_key)})[/]"
|
||||
)
|
||||
if sys.stdin.isatty():
|
||||
confirm = typer.confirm(" Overwrite existing config? This cannot be undone.")
|
||||
if not confirm:
|
||||
print_info(console, "Cancelled. Use --force to skip this check.")
|
||||
raise typer.Exit(0)
|
||||
else:
|
||||
print_error(
|
||||
err_console,
|
||||
"Existing config would be overwritten.",
|
||||
hint="Use --force to overwrite.",
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
# ── Email login flow ──────────────────────────────────────────────
|
||||
if email:
|
||||
if api_key:
|
||||
@@ -205,7 +229,9 @@ def run_init(
|
||||
raise typer.Exit(1)
|
||||
config.platform.api_key = api_key_val
|
||||
config.platform.base_url = base_url
|
||||
config.defaults.user_id = user_id or "mem0-cli"
|
||||
config.defaults.user_id = (
|
||||
user_id or os.environ.get("USER") or os.environ.get("USERNAME") or "mem0-cli"
|
||||
)
|
||||
|
||||
save_config(config)
|
||||
|
||||
@@ -220,6 +246,17 @@ def run_init(
|
||||
|
||||
# ── API key flow (existing) ───────────────────────────────────────
|
||||
|
||||
# Non-TTY: resolve defaults so partial flags work in pipelines / CI
|
||||
if not sys.stdin.isatty():
|
||||
if not api_key:
|
||||
print_error(
|
||||
err_console,
|
||||
"Non-interactive terminal detected and --api-key is required.",
|
||||
hint="Run: mem0 init --api-key <key> [--user-id <id>]",
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
user_id = user_id or os.environ.get("USER") or os.environ.get("USERNAME") or "mem0-cli"
|
||||
|
||||
# Fully non-interactive when both flags provided
|
||||
if api_key and user_id:
|
||||
config.platform.api_key = api_key
|
||||
@@ -229,15 +266,6 @@ def run_init(
|
||||
print_success(console, "Configuration saved to ~/.mem0/config.json")
|
||||
return
|
||||
|
||||
# Non-TTY without full flags -> error
|
||||
if not sys.stdin.isatty() and (not api_key or not user_id):
|
||||
print_error(
|
||||
err_console,
|
||||
"Non-interactive terminal detected and required flags missing.",
|
||||
hint="Run: mem0 init --api-key <key> --user-id <id>",
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
print_banner(console)
|
||||
console.print()
|
||||
print_info(console, "Welcome! Let's set up your mem0 CLI.\n")
|
||||
@@ -271,7 +299,9 @@ def run_init(
|
||||
raise typer.Exit(1)
|
||||
config.platform.api_key = api_key_val
|
||||
config.platform.base_url = base_url
|
||||
config.defaults.user_id = user_id or "mem0-cli"
|
||||
config.defaults.user_id = (
|
||||
user_id or os.environ.get("USER") or os.environ.get("USERNAME") or "mem0-cli"
|
||||
)
|
||||
|
||||
save_config(config)
|
||||
|
||||
@@ -331,9 +361,10 @@ def _setup_defaults(config: Mem0Config) -> None:
|
||||
console.print()
|
||||
print_info(console, "Set default entity IDs (press Enter to skip).\n")
|
||||
|
||||
_default_user = os.environ.get("USER") or os.environ.get("USERNAME") or "mem0-cli"
|
||||
user_id = Prompt.ask(
|
||||
f" [{BRAND_COLOR}]Default User ID[/] [{DIM_COLOR}](recommended)[/]",
|
||||
default="mem0-cli",
|
||||
default=_default_user,
|
||||
)
|
||||
if user_id:
|
||||
config.defaults.user_id = user_id
|
||||
@@ -357,7 +388,7 @@ def _validate_platform(config: Mem0Config) -> None:
|
||||
print_error(
|
||||
err_console,
|
||||
f"Could not connect: {status.get('error', 'Unknown error')}",
|
||||
hint="Check your API key and try again.",
|
||||
hint="Visit https://app.mem0.ai/dashboard/api-keys to get a new key, then run mem0 init again.",
|
||||
)
|
||||
except Exception as e:
|
||||
print_error(err_console, f"Connection test failed: {e}")
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat as _stat_mod
|
||||
import sys
|
||||
import time as _time
|
||||
from pathlib import Path
|
||||
@@ -20,6 +22,7 @@ from mem0_cli.branding import (
|
||||
)
|
||||
from mem0_cli.output import (
|
||||
format_add_result,
|
||||
format_agent_envelope,
|
||||
format_json,
|
||||
format_memories_table,
|
||||
format_memories_text,
|
||||
@@ -31,6 +34,19 @@ console = Console()
|
||||
err_console = Console(stderr=True)
|
||||
|
||||
|
||||
def _stdin_is_piped() -> bool:
|
||||
"""Return True only when stdin is an actual pipe or file redirect."""
|
||||
from mem0_cli.state import is_agent_mode
|
||||
|
||||
if is_agent_mode():
|
||||
return False
|
||||
try:
|
||||
mode = os.fstat(sys.stdin.fileno()).st_mode
|
||||
return _stat_mod.S_ISFIFO(mode) or _stat_mod.S_ISREG(mode)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def cmd_add(
|
||||
backend: Backend,
|
||||
text: str | None,
|
||||
@@ -50,6 +66,11 @@ def cmd_add(
|
||||
output: str = "text",
|
||||
) -> None:
|
||||
"""Add a memory."""
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("add")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
msgs = None
|
||||
content = text
|
||||
|
||||
@@ -70,8 +91,8 @@ def cmd_add(
|
||||
print_error(err_console, f"Invalid JSON in --messages: {e}")
|
||||
raise typer.Exit(1) from None
|
||||
|
||||
# Read from stdin if no text and stdin is piped
|
||||
elif not content and not sys.stdin.isatty():
|
||||
# Read from stdin only if stdin is an actual pipe or file redirect
|
||||
elif not content and _stdin_is_piped():
|
||||
content = sys.stdin.read().strip()
|
||||
|
||||
if not content and not msgs:
|
||||
@@ -133,18 +154,61 @@ def cmd_add(
|
||||
if output == "quiet":
|
||||
return
|
||||
|
||||
# Deduplicate PENDING entries sharing the same event_id across all output modes
|
||||
results_list = result if isinstance(result, list) else result.get("results", [result])
|
||||
seen_events: set[str] = set()
|
||||
deduped: list[dict] = []
|
||||
for r in results_list:
|
||||
if r.get("status") == "PENDING":
|
||||
eid = r.get("event_id", "")
|
||||
if eid and eid in seen_events:
|
||||
continue
|
||||
if eid:
|
||||
seen_events.add(eid)
|
||||
deduped.append(r)
|
||||
# Write back so downstream formatters see deduplicated data
|
||||
if isinstance(result, dict) and "results" in result:
|
||||
result = {**result, "results": deduped}
|
||||
else:
|
||||
result = deduped
|
||||
|
||||
if output == "agent":
|
||||
scope = {
|
||||
k: v
|
||||
for k, v in {
|
||||
"user_id": user_id,
|
||||
"agent_id": agent_id,
|
||||
"app_id": app_id,
|
||||
"run_id": run_id,
|
||||
}.items()
|
||||
if v
|
||||
}
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="add",
|
||||
data=deduped,
|
||||
scope=scope or None,
|
||||
count=len(deduped),
|
||||
)
|
||||
return
|
||||
|
||||
if output == "json":
|
||||
format_add_result(console, result, output)
|
||||
return
|
||||
|
||||
console.print()
|
||||
print_scope(console, user_id=user_id, agent_id=agent_id, app_id=app_id, run_id=run_id)
|
||||
# Count results
|
||||
results = result if isinstance(result, list) else result.get("results", [result])
|
||||
count = len(results) if results else 0
|
||||
print_success(
|
||||
console, f"Memory processed — {count} memor{'y' if count == 1 else 'ies'} extracted"
|
||||
)
|
||||
count = len(deduped)
|
||||
all_pending = count > 0 and all(r.get("status") == "PENDING" for r in deduped)
|
||||
if all_pending:
|
||||
print_success(
|
||||
console,
|
||||
f"Memory queued — {count} event{'s' if count != 1 else ''} pending",
|
||||
)
|
||||
else:
|
||||
print_success(
|
||||
console, f"Memory processed — {count} memor{'y' if count == 1 else 'ies'} extracted"
|
||||
)
|
||||
format_add_result(console, result, output)
|
||||
|
||||
|
||||
@@ -166,6 +230,11 @@ def cmd_search(
|
||||
output: str = "text",
|
||||
) -> None:
|
||||
"""Search memories."""
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("search")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
filters = None
|
||||
if filter_json:
|
||||
try:
|
||||
@@ -210,6 +279,27 @@ def cmd_search(
|
||||
if output == "quiet":
|
||||
return
|
||||
|
||||
if output == "agent":
|
||||
scope = {
|
||||
k: v
|
||||
for k, v in {
|
||||
"user_id": user_id,
|
||||
"agent_id": agent_id,
|
||||
"app_id": app_id,
|
||||
"run_id": run_id,
|
||||
}.items()
|
||||
if v
|
||||
}
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="search",
|
||||
data=results,
|
||||
scope=scope or None,
|
||||
count=len(results),
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
return
|
||||
|
||||
if output == "json":
|
||||
format_json(console, results)
|
||||
elif output == "table":
|
||||
@@ -236,6 +326,11 @@ def cmd_search(
|
||||
|
||||
def cmd_get(backend: Backend, memory_id: str, *, output: str) -> None:
|
||||
"""Get a specific memory by ID."""
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("get")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
with timed_status(err_console, "Fetching memory...") as _ts:
|
||||
try:
|
||||
result = backend.get(memory_id)
|
||||
@@ -243,7 +338,10 @@ def cmd_get(backend: Backend, memory_id: str, *, output: str) -> None:
|
||||
print_error(err_console, str(e))
|
||||
raise typer.Exit(1) from None
|
||||
|
||||
format_single_memory(console, result, output)
|
||||
if output == "agent":
|
||||
format_agent_envelope(console, command="get", data=result)
|
||||
else:
|
||||
format_single_memory(console, result, output)
|
||||
|
||||
|
||||
def cmd_list(
|
||||
@@ -262,6 +360,11 @@ def cmd_list(
|
||||
output: str = "table",
|
||||
) -> None:
|
||||
"""List memories."""
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("list")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
if page_size < 1:
|
||||
print_error(err_console, "--page-size must be >= 1.")
|
||||
raise typer.Exit(1)
|
||||
@@ -292,15 +395,24 @@ def cmd_list(
|
||||
if output == "quiet":
|
||||
return
|
||||
|
||||
if output == "json":
|
||||
from mem0_cli.output import format_json_envelope
|
||||
|
||||
format_json_envelope(
|
||||
if output in ("json", "agent"):
|
||||
scope = {
|
||||
k: v
|
||||
for k, v in {
|
||||
"user_id": user_id,
|
||||
"agent_id": agent_id,
|
||||
"app_id": app_id,
|
||||
"run_id": run_id,
|
||||
}.items()
|
||||
if v
|
||||
}
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="list",
|
||||
data=results,
|
||||
scope=scope or None,
|
||||
count=len(results),
|
||||
scope={k: v for k, v in {"user_id": user_id, "agent_id": agent_id}.items() if v},
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
elif output == "table":
|
||||
if results:
|
||||
@@ -343,6 +455,11 @@ def cmd_update(
|
||||
output: str,
|
||||
) -> None:
|
||||
"""Update a memory."""
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("update")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
meta = None
|
||||
if metadata:
|
||||
try:
|
||||
@@ -360,7 +477,14 @@ def cmd_update(
|
||||
raise typer.Exit(1) from None
|
||||
_elapsed = _time.perf_counter() - _start
|
||||
|
||||
if output == "json":
|
||||
if output == "agent":
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="update",
|
||||
data=result,
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
elif output == "json":
|
||||
format_json(console, result)
|
||||
elif output != "quiet":
|
||||
print_success(console, f"Memory {memory_id[:8]} updated ({_elapsed:.2f}s)")
|
||||
@@ -375,6 +499,11 @@ def cmd_delete(
|
||||
output: str,
|
||||
) -> None:
|
||||
"""Delete a single memory by ID."""
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("delete")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
if dry_run:
|
||||
# Fetch and display what would be deleted
|
||||
try:
|
||||
@@ -395,7 +524,14 @@ def cmd_delete(
|
||||
raise typer.Exit(1) from None
|
||||
_elapsed = _time.perf_counter() - _start
|
||||
|
||||
if output == "json":
|
||||
if output == "agent":
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="delete",
|
||||
data={"id": memory_id, "deleted": True},
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
elif output == "json":
|
||||
format_json(console, result)
|
||||
elif output != "quiet":
|
||||
print_success(console, f"Memory {memory_id[:8]} deleted ({_elapsed:.2f}s)")
|
||||
@@ -414,13 +550,17 @@ def cmd_delete_all(
|
||||
output: str,
|
||||
) -> None:
|
||||
"""Delete all memories matching a scope."""
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("delete-all")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
if not force:
|
||||
print_error(err_console, "Destructive operation requires --force in agent mode.")
|
||||
raise typer.Exit(1)
|
||||
if all_:
|
||||
# Project-wide wipe using wildcard entity IDs
|
||||
if dry_run:
|
||||
print_info(console, "Would delete ALL memories project-wide.")
|
||||
print_info(console, "Run without --dry-run to see the actual count.")
|
||||
print_info(console, "No changes made (dry run).")
|
||||
return
|
||||
# Note: --dry-run is ignored here because the API has no count-before-delete endpoint.
|
||||
|
||||
if not force:
|
||||
confirm = typer.confirm(
|
||||
@@ -445,7 +585,14 @@ def cmd_delete_all(
|
||||
raise typer.Exit(1) from None
|
||||
_elapsed = _time.perf_counter() - _start
|
||||
|
||||
if output == "json":
|
||||
if output == "agent":
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="delete-all",
|
||||
data={"deleted": True, "scope": "project"},
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
elif output == "json":
|
||||
format_json(console, result)
|
||||
elif output != "quiet":
|
||||
if isinstance(result, dict) and "message" in result:
|
||||
@@ -503,7 +650,25 @@ def cmd_delete_all(
|
||||
raise typer.Exit(1) from None
|
||||
_elapsed = _time.perf_counter() - _start
|
||||
|
||||
if output == "json":
|
||||
scope = {
|
||||
k: v
|
||||
for k, v in {
|
||||
"user_id": user_id,
|
||||
"agent_id": agent_id,
|
||||
"app_id": app_id,
|
||||
"run_id": run_id,
|
||||
}.items()
|
||||
if v
|
||||
}
|
||||
if output == "agent":
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="delete-all",
|
||||
data={"deleted": True},
|
||||
scope=scope or None,
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
elif output == "json":
|
||||
format_json(console, result)
|
||||
elif output != "quiet":
|
||||
if isinstance(result, dict) and "message" in result:
|
||||
|
||||
@@ -35,22 +35,26 @@ def cmd_status(
|
||||
output: str = "text",
|
||||
) -> None:
|
||||
"""Check connectivity and auth."""
|
||||
from mem0_cli.output import format_json_envelope
|
||||
from mem0_cli.output import format_agent_envelope
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("status")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
|
||||
_start = _time.perf_counter()
|
||||
with timed_status(err_console, "Checking connection...") as _ts:
|
||||
result = backend.status(user_id=user_id, agent_id=agent_id)
|
||||
_elapsed = _time.perf_counter() - _start
|
||||
|
||||
if output == "json":
|
||||
format_json_envelope(
|
||||
if output in ("json", "agent"):
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="status",
|
||||
data={
|
||||
"connected": result.get("connected", False),
|
||||
"backend": result.get("backend", "?"),
|
||||
"base_url": result.get("base_url", ""),
|
||||
"latency_ms": int(_elapsed * 1000),
|
||||
},
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
@@ -67,6 +71,14 @@ def cmd_status(
|
||||
lines.append(f" [{DIM_COLOR}]API URL:[/] {result['base_url']}")
|
||||
if result.get("error"):
|
||||
lines.append(f" [{ERROR_COLOR}]Error:[/] {result['error']}")
|
||||
if "Authentication failed" in str(result["error"]):
|
||||
lines.append("")
|
||||
lines.append(
|
||||
f" [{DIM_COLOR}]Run [bold]mem0 init[/bold] to reconfigure your API key[/]"
|
||||
)
|
||||
lines.append(
|
||||
f" [{DIM_COLOR}]Get a key at [bold]https://app.mem0.ai/dashboard/api-keys[/bold][/]"
|
||||
)
|
||||
lines.append(f" [{DIM_COLOR}]Latency:[/] {_elapsed:.2f}s")
|
||||
|
||||
content = "\n".join(lines)
|
||||
@@ -96,7 +108,12 @@ def cmd_import(
|
||||
output: str = "text",
|
||||
) -> None:
|
||||
"""Import memories from a JSON file."""
|
||||
from mem0_cli.output import format_json_envelope
|
||||
from mem0_cli.output import format_agent_envelope
|
||||
from mem0_cli.state import is_agent_mode, set_current_command
|
||||
|
||||
set_current_command("import")
|
||||
if is_agent_mode():
|
||||
output = "agent"
|
||||
|
||||
try:
|
||||
data = json.loads(Path(file_path).read_text())
|
||||
@@ -129,11 +146,13 @@ def cmd_import(
|
||||
failed += 1
|
||||
_elapsed = _time.perf_counter() - _start
|
||||
|
||||
if output == "json":
|
||||
format_json_envelope(
|
||||
if output in ("json", "agent"):
|
||||
scope = {k: v for k, v in {"user_id": user_id, "agent_id": agent_id}.items() if v}
|
||||
format_agent_envelope(
|
||||
console,
|
||||
command="import",
|
||||
data={"added": added, "failed": failed, "duration_s": round(_elapsed, 2)},
|
||||
data={"added": added, "failed": failed},
|
||||
scope=scope or None,
|
||||
duration_ms=int(_elapsed * 1000),
|
||||
)
|
||||
return
|
||||
|
||||
@@ -155,16 +155,23 @@ def format_add_result(console: Console, result: dict | list, output: str = "text
|
||||
return
|
||||
|
||||
console.print()
|
||||
seen_pending_events: set[str] = set()
|
||||
for r in results:
|
||||
# Detect async PENDING response from Platform API
|
||||
if r.get("status") == "PENDING":
|
||||
event_id = r.get("event_id", "")[:8]
|
||||
event_id = r.get("event_id", "")
|
||||
# Deduplicate PENDING entries with the same event_id
|
||||
if event_id and event_id in seen_pending_events:
|
||||
continue
|
||||
if event_id:
|
||||
seen_pending_events.add(event_id)
|
||||
icon = f"[{ACCENT_COLOR}]{_sym('⧗', '...')}[/]"
|
||||
parts = [f" {icon} [{DIM_COLOR}]{'Queued':<10}[/]"]
|
||||
parts.append("[white]Processing in background[/]")
|
||||
if event_id:
|
||||
parts.append(f"[{DIM_COLOR}](event {event_id})[/]")
|
||||
console.print(" ".join(parts))
|
||||
if event_id:
|
||||
console.print(f" [{DIM_COLOR}] event_id: {event_id}[/]")
|
||||
console.print(f" [{DIM_COLOR}] → Check status: mem0 event status {event_id}[/]")
|
||||
continue
|
||||
|
||||
event = r.get("event", "ADD")
|
||||
@@ -225,6 +232,100 @@ def format_json_envelope(
|
||||
console.print_json(json.dumps(envelope, default=str))
|
||||
|
||||
|
||||
def sanitize_agent_data(command: str, data: Any) -> Any:
|
||||
"""Project API response data to minimal relevant fields for agent consumption."""
|
||||
|
||||
def pick(obj: dict, keys: list) -> dict:
|
||||
return {k: obj[k] for k in keys if k in obj}
|
||||
|
||||
if data is None:
|
||||
return data
|
||||
|
||||
if command == "add":
|
||||
items = data if isinstance(data, list) else [data]
|
||||
result = []
|
||||
for item in items:
|
||||
if item.get("status") == "PENDING":
|
||||
result.append(pick(item, ["status", "event_id"]))
|
||||
else:
|
||||
result.append(pick(item, ["id", "memory", "event"]))
|
||||
return result
|
||||
|
||||
if command == "search":
|
||||
return [pick(r, ["id", "memory", "score", "created_at", "categories"]) for r in data]
|
||||
|
||||
if command == "list":
|
||||
return [pick(r, ["id", "memory", "created_at", "categories"]) for r in data]
|
||||
|
||||
if command == "get":
|
||||
return pick(data, ["id", "memory", "created_at", "updated_at", "categories", "metadata"])
|
||||
|
||||
if command == "update":
|
||||
return pick(data, ["id", "memory"])
|
||||
|
||||
if command in ("delete", "delete-all", "entity delete"):
|
||||
return data
|
||||
|
||||
if command == "entity list":
|
||||
result = []
|
||||
for r in data:
|
||||
item = pick(r, ["type", "count"])
|
||||
item["name"] = r.get("name") or r.get("id", "")
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
if command == "event list":
|
||||
return [pick(r, ["id", "event_type", "status", "latency", "created_at"]) for r in data]
|
||||
|
||||
if command == "event status":
|
||||
ev = data
|
||||
raw_results = ev.get("results") or []
|
||||
sanitized_results = []
|
||||
for r in raw_results:
|
||||
nested = r.get("data") or {}
|
||||
memory = nested.get("memory") if isinstance(nested, dict) else None
|
||||
sanitized_results.append(
|
||||
{
|
||||
"id": r.get("id"),
|
||||
"event": r.get("event"),
|
||||
"user_id": r.get("user_id"),
|
||||
"memory": memory,
|
||||
}
|
||||
)
|
||||
result = pick(ev, ["id", "event_type", "status", "latency", "created_at", "updated_at"])
|
||||
result["results"] = sanitized_results
|
||||
return result
|
||||
|
||||
# Pass-through: status, import, config show/get/set
|
||||
return data
|
||||
|
||||
|
||||
def format_agent_envelope(
|
||||
console: Console,
|
||||
*,
|
||||
command: str,
|
||||
data: Any,
|
||||
duration_ms: int | None = None,
|
||||
scope: dict | None = None,
|
||||
count: int | None = None,
|
||||
) -> None:
|
||||
"""Output structured JSON envelope for agent/programmatic use (--json/--agent mode)."""
|
||||
envelope: dict[str, Any] = {
|
||||
"status": "success",
|
||||
"command": command,
|
||||
}
|
||||
if duration_ms is not None:
|
||||
envelope["duration_ms"] = duration_ms
|
||||
if scope:
|
||||
filtered = {k: v for k, v in scope.items() if v}
|
||||
if filtered:
|
||||
envelope["scope"] = filtered
|
||||
if count is not None:
|
||||
envelope["count"] = count
|
||||
envelope["data"] = sanitize_agent_data(command, data)
|
||||
console.print_json(json.dumps(envelope, default=str))
|
||||
|
||||
|
||||
def print_result_summary(
|
||||
console: Console,
|
||||
count: int,
|
||||
@@ -237,7 +338,7 @@ def print_result_summary(
|
||||
parts = [f"{count} result{'s' if count != 1 else ''}"]
|
||||
if page is not None:
|
||||
parts.append(f"page {page}")
|
||||
scope_parts = [f"{k.replace('_', ' ')}={v}" for k, v in scope_ids.items() if v]
|
||||
scope_parts = [f"{k}={v}" for k, v in scope_ids.items() if v]
|
||||
if scope_parts:
|
||||
parts.append(", ".join(scope_parts))
|
||||
if duration_secs is not None:
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Agent mode state — set by the root callback, read by commands and branding."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
_agent_mode: bool = False
|
||||
_current_command: str = ""
|
||||
|
||||
|
||||
def is_agent_mode() -> bool:
|
||||
return _agent_mode
|
||||
|
||||
|
||||
def set_agent_mode(val: bool) -> None:
|
||||
global _agent_mode
|
||||
_agent_mode = val
|
||||
|
||||
|
||||
def get_current_command() -> str:
|
||||
return _current_command
|
||||
|
||||
|
||||
def set_current_command(name: str) -> None:
|
||||
global _current_command
|
||||
_current_command = name
|
||||
@@ -96,6 +96,43 @@ def mock_backend():
|
||||
{"name": "alice", "count": 5},
|
||||
{"name": "bob", "count": 3},
|
||||
]
|
||||
backend.list_events.return_value = [
|
||||
{
|
||||
"id": "evt-abc-123-def-456",
|
||||
"event_type": "ADD",
|
||||
"status": "SUCCEEDED",
|
||||
"graph_status": None,
|
||||
"latency": 1234.5,
|
||||
"created_at": "2026-04-01T10:00:00Z",
|
||||
"updated_at": "2026-04-01T10:00:01Z",
|
||||
},
|
||||
{
|
||||
"id": "evt-def-456-ghi-789",
|
||||
"event_type": "SEARCH",
|
||||
"status": "PENDING",
|
||||
"graph_status": None,
|
||||
"latency": None,
|
||||
"created_at": "2026-04-01T10:01:00Z",
|
||||
"updated_at": "2026-04-01T10:01:00Z",
|
||||
},
|
||||
]
|
||||
backend.get_event.return_value = {
|
||||
"id": "evt-abc-123-def-456",
|
||||
"event_type": "ADD",
|
||||
"status": "SUCCEEDED",
|
||||
"graph_status": "SUCCEEDED",
|
||||
"latency": 1234.5,
|
||||
"created_at": "2026-04-01T10:00:00Z",
|
||||
"updated_at": "2026-04-01T10:00:01Z",
|
||||
"results": [
|
||||
{
|
||||
"id": "mem-abc-123",
|
||||
"event": "ADD",
|
||||
"user_id": "alice",
|
||||
"data": {"memory": "User prefers dark mode"},
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
return backend
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import typing
|
||||
from io import StringIO
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -16,6 +17,7 @@ from mem0_cli.commands.config_cmd import (
|
||||
cmd_config_show,
|
||||
)
|
||||
from mem0_cli.commands.entities import cmd_entities_delete, cmd_entities_list
|
||||
from mem0_cli.commands.events_cmd import cmd_event_list, cmd_event_status
|
||||
from mem0_cli.commands.memory import (
|
||||
cmd_add,
|
||||
cmd_delete,
|
||||
@@ -176,30 +178,28 @@ class TestAddCommand:
|
||||
def test_add_no_content_exits(self, mock_backend):
|
||||
console, _buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
# Patch stdin.isatty to return True so it doesn't try to read stdin
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
patch("mem0_cli.commands.memory.sys") as mock_sys,
|
||||
patch("mem0_cli.commands.memory._stdin_is_piped", return_value=False),
|
||||
pytest.raises((SystemExit, ClickExit)),
|
||||
):
|
||||
mock_sys.stdin.isatty.return_value = True
|
||||
with pytest.raises((SystemExit, ClickExit)):
|
||||
cmd_add(
|
||||
mock_backend,
|
||||
None,
|
||||
user_id="alice",
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
messages=None,
|
||||
file=None,
|
||||
metadata=None,
|
||||
immutable=False,
|
||||
no_infer=False,
|
||||
expires=None,
|
||||
categories=None,
|
||||
output="text",
|
||||
)
|
||||
cmd_add(
|
||||
mock_backend,
|
||||
None,
|
||||
user_id="alice",
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
messages=None,
|
||||
file=None,
|
||||
metadata=None,
|
||||
immutable=False,
|
||||
no_infer=False,
|
||||
expires=None,
|
||||
categories=None,
|
||||
output="text",
|
||||
)
|
||||
|
||||
def test_add_invalid_metadata_json(self, mock_backend):
|
||||
console, _buf = _make_console()
|
||||
@@ -279,6 +279,66 @@ class TestAddCommand:
|
||||
mock_backend.add.assert_called_once()
|
||||
|
||||
|
||||
class TestAddDeduplicatesPending:
|
||||
"""Ensure duplicate PENDING entries with the same event_id are collapsed."""
|
||||
|
||||
DUPLICATE_PENDING: typing.ClassVar[dict] = {
|
||||
"results": [
|
||||
{"status": "PENDING", "event_id": "evt-dup"},
|
||||
{"status": "PENDING", "event_id": "evt-dup"},
|
||||
]
|
||||
}
|
||||
|
||||
def _run_add(self, mock_backend, output):
|
||||
mock_backend.add.return_value = self.DUPLICATE_PENDING
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_add(
|
||||
mock_backend,
|
||||
"test",
|
||||
user_id="alice",
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
messages=None,
|
||||
file=None,
|
||||
metadata=None,
|
||||
immutable=False,
|
||||
no_infer=False,
|
||||
expires=None,
|
||||
categories=None,
|
||||
output=output,
|
||||
)
|
||||
return buf.getvalue()
|
||||
|
||||
def test_text_shows_one_pending(self, mock_backend):
|
||||
raw = self._run_add(mock_backend, "text")
|
||||
assert raw.count("Queued") == 1
|
||||
|
||||
def test_json_shows_one_pending(self, mock_backend):
|
||||
raw = self._run_add(mock_backend, "json")
|
||||
data = json.loads(raw)
|
||||
results = data.get("results", data)
|
||||
pending = [r for r in results if r.get("status") == "PENDING"]
|
||||
assert len(pending) == 1
|
||||
|
||||
def test_agent_shows_one_pending(self, mock_backend):
|
||||
from mem0_cli.state import set_agent_mode
|
||||
|
||||
set_agent_mode(True)
|
||||
try:
|
||||
raw = self._run_add(mock_backend, "agent")
|
||||
finally:
|
||||
set_agent_mode(False)
|
||||
data = json.loads(raw)
|
||||
assert data["count"] == 1
|
||||
assert len(data["data"]) == 1
|
||||
|
||||
|
||||
class TestSearchCommand:
|
||||
def test_search_text(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
@@ -618,28 +678,6 @@ class TestDeleteAllCommand:
|
||||
run_id="*",
|
||||
)
|
||||
|
||||
def test_delete_all_project_wide_dry_run(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_delete_all(
|
||||
mock_backend,
|
||||
force=True,
|
||||
all_=True,
|
||||
dry_run=True,
|
||||
user_id=None,
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
output="text",
|
||||
)
|
||||
output = buf.getvalue()
|
||||
assert "project-wide" in output.lower()
|
||||
mock_backend.delete.assert_not_called()
|
||||
|
||||
def test_delete_all_project_wide_async_response(self, mock_backend):
|
||||
mock_backend.delete.return_value = {"message": "Memories deletion started..."}
|
||||
console, buf = _make_console()
|
||||
@@ -888,6 +926,28 @@ class TestEntitiesDeleteCommand:
|
||||
output = buf.getvalue()
|
||||
assert "deleted" in output.lower()
|
||||
|
||||
def test_delete_entity_agent_id(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.entities.console", console),
|
||||
patch("mem0_cli.commands.entities.err_console", err_console),
|
||||
):
|
||||
cmd_entities_delete(
|
||||
mock_backend,
|
||||
user_id=None,
|
||||
agent_id="bot1",
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
force=True,
|
||||
output="text",
|
||||
)
|
||||
mock_backend.delete_entities.assert_called_once_with(
|
||||
user_id=None, agent_id="bot1", app_id=None, run_id=None
|
||||
)
|
||||
output = buf.getvalue()
|
||||
assert "deleted" in output.lower()
|
||||
|
||||
def test_delete_entity_no_id_exits(self, mock_backend):
|
||||
console, _buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
@@ -1024,3 +1084,388 @@ class TestEnableGraph:
|
||||
)
|
||||
call_kwargs = mock_backend.list_memories.call_args
|
||||
assert call_kwargs.kwargs.get("enable_graph") is True
|
||||
|
||||
|
||||
class TestEventCommands:
|
||||
def test_event_list_table(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.events_cmd.console", console),
|
||||
patch("mem0_cli.commands.events_cmd.err_console", err_console),
|
||||
):
|
||||
cmd_event_list(mock_backend, output="table")
|
||||
out = buf.getvalue()
|
||||
assert "evt-abc-" in out
|
||||
assert "ADD" in out
|
||||
assert "SUCCEEDED" in out
|
||||
|
||||
def test_event_list_json(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.events_cmd.console", console),
|
||||
patch("mem0_cli.commands.events_cmd.err_console", err_console),
|
||||
):
|
||||
cmd_event_list(mock_backend, output="json")
|
||||
out = buf.getvalue()
|
||||
assert "evt-abc-123-def-456" in out
|
||||
assert "evt-def-456-ghi-789" in out
|
||||
|
||||
def test_event_list_empty(self, mock_backend):
|
||||
mock_backend.list_events.return_value = []
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.events_cmd.console", console),
|
||||
patch("mem0_cli.commands.events_cmd.err_console", err_console),
|
||||
):
|
||||
cmd_event_list(mock_backend, output="table")
|
||||
out = buf.getvalue()
|
||||
assert "No events" in out
|
||||
|
||||
def test_event_status_text(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.events_cmd.console", console),
|
||||
patch("mem0_cli.commands.events_cmd.err_console", err_console),
|
||||
):
|
||||
cmd_event_status(mock_backend, "evt-abc-123-def-456", output="text")
|
||||
out = buf.getvalue()
|
||||
assert "evt-abc-123-def-456" in out
|
||||
assert "SUCCEEDED" in out
|
||||
|
||||
def test_event_status_json(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.events_cmd.console", console),
|
||||
patch("mem0_cli.commands.events_cmd.err_console", err_console),
|
||||
):
|
||||
cmd_event_status(mock_backend, "evt-abc-123-def-456", output="json")
|
||||
out = buf.getvalue()
|
||||
assert "evt-abc-123-def-456" in out
|
||||
assert "ADD" in out
|
||||
|
||||
|
||||
class TestAgentMode:
|
||||
"""Tests for --json/--agent mode: structured JSON envelope output."""
|
||||
|
||||
def setup_method(self):
|
||||
"""Enable agent mode before each test."""
|
||||
from mem0_cli.state import set_agent_mode
|
||||
|
||||
set_agent_mode(True)
|
||||
|
||||
def teardown_method(self):
|
||||
"""Reset agent mode after each test."""
|
||||
from mem0_cli.state import set_agent_mode
|
||||
|
||||
set_agent_mode(False)
|
||||
|
||||
# ── add ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_add_agent_mode_envelope(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_add(
|
||||
mock_backend,
|
||||
"I prefer dark mode",
|
||||
user_id="alice",
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
messages=None,
|
||||
file=None,
|
||||
metadata=None,
|
||||
immutable=False,
|
||||
no_infer=False,
|
||||
expires=None,
|
||||
categories=None,
|
||||
output="text", # will be overridden to "agent"
|
||||
)
|
||||
raw = buf.getvalue()
|
||||
data = json.loads(raw)
|
||||
assert data["status"] == "success"
|
||||
assert data["command"] == "add"
|
||||
assert "data" in data
|
||||
assert isinstance(data["data"], list)
|
||||
assert data["count"] == 1
|
||||
assert set(data["data"][0].keys()) == {"id", "memory", "event"}
|
||||
|
||||
def test_add_agent_mode_scope(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_add(
|
||||
mock_backend,
|
||||
"test",
|
||||
user_id="bob",
|
||||
agent_id="agent1",
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
messages=None,
|
||||
file=None,
|
||||
metadata=None,
|
||||
immutable=False,
|
||||
no_infer=False,
|
||||
expires=None,
|
||||
categories=None,
|
||||
output="text",
|
||||
)
|
||||
data = json.loads(buf.getvalue())
|
||||
assert data["scope"]["user_id"] == "bob"
|
||||
assert data["scope"]["agent_id"] == "agent1"
|
||||
|
||||
# ── search ───────────────────────────────────────────────────────────────
|
||||
|
||||
def test_search_agent_mode_envelope(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_search(
|
||||
mock_backend,
|
||||
"dark mode",
|
||||
user_id="alice",
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
top_k=10,
|
||||
threshold=0.3,
|
||||
rerank=False,
|
||||
keyword=False,
|
||||
filter_json=None,
|
||||
fields=None,
|
||||
output="text",
|
||||
)
|
||||
data = json.loads(buf.getvalue())
|
||||
assert data["status"] == "success"
|
||||
assert data["command"] == "search"
|
||||
assert isinstance(data["data"], list)
|
||||
assert data["count"] == 2
|
||||
assert "duration_ms" in data
|
||||
assert set(data["data"][0].keys()) == {"id", "memory", "score", "created_at", "categories"}
|
||||
|
||||
# ── list ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_list_agent_mode_envelope(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_list(
|
||||
mock_backend,
|
||||
user_id="alice",
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
page=1,
|
||||
page_size=100,
|
||||
category=None,
|
||||
after=None,
|
||||
before=None,
|
||||
output="table", # will be overridden to "agent"
|
||||
)
|
||||
data = json.loads(buf.getvalue())
|
||||
assert data["status"] == "success"
|
||||
assert data["command"] == "list"
|
||||
assert isinstance(data["data"], list)
|
||||
assert data["count"] == 2
|
||||
assert data["scope"]["user_id"] == "alice"
|
||||
assert set(data["data"][0].keys()) == {"id", "memory", "created_at", "categories"}
|
||||
|
||||
# ── get ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_get_agent_mode_envelope(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_get(mock_backend, "abc-123-def-456", output="text")
|
||||
data = json.loads(buf.getvalue())
|
||||
assert data["status"] == "success"
|
||||
assert data["command"] == "get"
|
||||
assert isinstance(data["data"], dict)
|
||||
assert data["data"]["id"] == "abc-123-def-456"
|
||||
assert "memory" in data["data"]
|
||||
assert set(data["data"].keys()) >= {"id", "memory"}
|
||||
|
||||
# ── update ───────────────────────────────────────────────────────────────
|
||||
|
||||
def test_update_agent_mode_envelope(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_update(mock_backend, "abc-123", "Updated content", metadata=None, output="text")
|
||||
data = json.loads(buf.getvalue())
|
||||
assert data["status"] == "success"
|
||||
assert data["command"] == "update"
|
||||
assert isinstance(data["data"], dict)
|
||||
assert "memory" in data["data"]
|
||||
assert "duration_ms" in data
|
||||
|
||||
# ── delete ───────────────────────────────────────────────────────────────
|
||||
|
||||
def test_delete_agent_mode_envelope(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_delete(mock_backend, "abc-123-def-456", output="text")
|
||||
data = json.loads(buf.getvalue())
|
||||
assert data["status"] == "success"
|
||||
assert data["command"] == "delete"
|
||||
assert data["data"]["id"] == "abc-123-def-456"
|
||||
assert data["data"]["deleted"] is True
|
||||
assert "duration_ms" in data
|
||||
|
||||
# ── event list ───────────────────────────────────────────────────────────
|
||||
|
||||
def test_event_list_agent_mode_envelope(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.events_cmd.console", console),
|
||||
patch("mem0_cli.commands.events_cmd.err_console", err_console),
|
||||
):
|
||||
cmd_event_list(mock_backend, output="table")
|
||||
data = json.loads(buf.getvalue())
|
||||
assert data["status"] == "success"
|
||||
assert data["command"] == "event list"
|
||||
assert isinstance(data["data"], list)
|
||||
assert data["count"] == 2
|
||||
assert "duration_ms" in data
|
||||
assert set(data["data"][0].keys()) == {
|
||||
"id",
|
||||
"event_type",
|
||||
"status",
|
||||
"latency",
|
||||
"created_at",
|
||||
}
|
||||
|
||||
# ── event status ─────────────────────────────────────────────────────────
|
||||
|
||||
def test_event_status_agent_mode_envelope(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.events_cmd.console", console),
|
||||
patch("mem0_cli.commands.events_cmd.err_console", err_console),
|
||||
):
|
||||
cmd_event_status(mock_backend, "evt-abc-123-def-456", output="text")
|
||||
data = json.loads(buf.getvalue())
|
||||
assert data["status"] == "success"
|
||||
assert data["command"] == "event status"
|
||||
assert isinstance(data["data"], dict)
|
||||
assert data["data"]["id"] == "evt-abc-123-def-456"
|
||||
assert "duration_ms" in data
|
||||
assert set(data["data"]["results"][0].keys()) == {"id", "event", "user_id", "memory"}
|
||||
assert "data" not in data["data"]["results"][0]
|
||||
|
||||
# ── error handling ───────────────────────────────────────────────────────
|
||||
|
||||
def test_error_in_agent_mode_produces_json_to_stdout(self, mock_backend):
|
||||
"""Errors in agent mode must emit a JSON envelope to stdout, not stderr."""
|
||||
from io import StringIO
|
||||
|
||||
mock_backend.get.side_effect = Exception("Memory not found")
|
||||
console, _buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
|
||||
captured_stdout = StringIO()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
patch("sys.stdout", captured_stdout),
|
||||
pytest.raises((SystemExit, ClickExit)),
|
||||
):
|
||||
cmd_get(mock_backend, "bad-id", output="text")
|
||||
|
||||
stdout_output = captured_stdout.getvalue()
|
||||
# The error JSON envelope must be on stdout
|
||||
error_data = json.loads(stdout_output)
|
||||
assert error_data["status"] == "error"
|
||||
assert "error" in error_data
|
||||
assert error_data["data"] is None
|
||||
|
||||
def test_branding_suppressed_in_agent_mode(self, mock_backend):
|
||||
"""Scope line and success message must be absent in agent mode output."""
|
||||
console, buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_add(
|
||||
mock_backend,
|
||||
"branding test",
|
||||
user_id="alice",
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
messages=None,
|
||||
file=None,
|
||||
metadata=None,
|
||||
immutable=False,
|
||||
no_infer=False,
|
||||
expires=None,
|
||||
categories=None,
|
||||
output="text",
|
||||
)
|
||||
output = buf.getvalue()
|
||||
# Must be valid JSON only — no human-readable branding
|
||||
data = json.loads(output)
|
||||
assert data["status"] == "success"
|
||||
# "Scope:" and "Memory processed" must NOT appear in the raw output
|
||||
assert "Scope:" not in output
|
||||
assert "Memory processed" not in output
|
||||
assert "spinner" not in output.lower()
|
||||
|
||||
def test_no_spinner_in_agent_mode(self, mock_backend):
|
||||
"""timed_status must not emit spinner output in agent mode."""
|
||||
err_buf = StringIO()
|
||||
err_console_buf = Console(file=err_buf, force_terminal=False, no_color=True, width=120)
|
||||
console, _buf = _make_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console_buf),
|
||||
):
|
||||
cmd_search(
|
||||
mock_backend,
|
||||
"query",
|
||||
user_id="alice",
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
top_k=5,
|
||||
threshold=0.3,
|
||||
rerank=False,
|
||||
keyword=False,
|
||||
filter_json=None,
|
||||
fields=None,
|
||||
output="text",
|
||||
)
|
||||
# The err_buf captures what would have been spinner/timing noise
|
||||
# In agent mode it should be empty (no status lines printed)
|
||||
err_output = err_buf.getvalue()
|
||||
assert "Searching" not in err_output
|
||||
|
||||
@@ -11,6 +11,7 @@ from mem0_cli.output import (
|
||||
format_memories_table,
|
||||
format_memories_text,
|
||||
format_single_memory,
|
||||
sanitize_agent_data,
|
||||
)
|
||||
|
||||
|
||||
@@ -129,8 +130,153 @@ class TestAddResult:
|
||||
output = buf.getvalue()
|
||||
assert output.strip() == ""
|
||||
|
||||
def test_format_add_result_deduplicates_pending_by_event_id(self):
|
||||
console, buf = _make_console()
|
||||
result = {
|
||||
"results": [
|
||||
{"status": "PENDING", "event_id": "evt-dup"},
|
||||
{"status": "PENDING", "event_id": "evt-dup"},
|
||||
]
|
||||
}
|
||||
format_add_result(console, result, "text")
|
||||
output = buf.getvalue()
|
||||
# Should show only one PENDING block despite two entries with same event_id
|
||||
assert output.count("evt-dup") == 2 # event_id line + status hint line
|
||||
assert output.count("Queued") == 1
|
||||
|
||||
def test_format_add_result_empty(self):
|
||||
console, buf = _make_console()
|
||||
format_add_result(console, {"results": []}, "text")
|
||||
output = buf.getvalue()
|
||||
assert "No memories extracted" in output
|
||||
|
||||
|
||||
class TestSanitizeAgentData:
|
||||
def test_add_projects_fields(self):
|
||||
raw = [
|
||||
{
|
||||
"id": "abc",
|
||||
"memory": "test",
|
||||
"event": "ADD",
|
||||
"metadata": {"x": 1},
|
||||
"categories": ["a"],
|
||||
}
|
||||
]
|
||||
result = sanitize_agent_data("add", raw)
|
||||
assert result == [{"id": "abc", "memory": "test", "event": "ADD"}]
|
||||
|
||||
def test_add_pending_passthrough(self):
|
||||
raw = [{"status": "PENDING", "event_id": "evt-123", "metadata": "noise"}]
|
||||
result = sanitize_agent_data("add", raw)
|
||||
assert result == [{"status": "PENDING", "event_id": "evt-123"}]
|
||||
|
||||
def test_search_projects_fields(self):
|
||||
raw = [
|
||||
{
|
||||
"id": "abc",
|
||||
"memory": "test",
|
||||
"score": 0.9,
|
||||
"created_at": "2026-01-01",
|
||||
"categories": ["a"],
|
||||
"user_id": "u1",
|
||||
"agent_id": None,
|
||||
}
|
||||
]
|
||||
result = sanitize_agent_data("search", raw)
|
||||
assert result == [
|
||||
{
|
||||
"id": "abc",
|
||||
"memory": "test",
|
||||
"score": 0.9,
|
||||
"created_at": "2026-01-01",
|
||||
"categories": ["a"],
|
||||
}
|
||||
]
|
||||
|
||||
def test_list_projects_fields(self):
|
||||
raw = [
|
||||
{
|
||||
"id": "abc",
|
||||
"memory": "test",
|
||||
"created_at": "2026-01-01",
|
||||
"categories": ["a"],
|
||||
"user_id": "u1",
|
||||
}
|
||||
]
|
||||
result = sanitize_agent_data("list", raw)
|
||||
assert result == [
|
||||
{"id": "abc", "memory": "test", "created_at": "2026-01-01", "categories": ["a"]}
|
||||
]
|
||||
|
||||
def test_get_projects_fields(self):
|
||||
raw = {
|
||||
"id": "abc",
|
||||
"memory": "test",
|
||||
"created_at": "2026-01-01",
|
||||
"updated_at": "2026-01-02",
|
||||
"categories": ["a"],
|
||||
"metadata": {"k": "v"},
|
||||
"user_id": "u1",
|
||||
}
|
||||
result = sanitize_agent_data("get", raw)
|
||||
assert "user_id" not in result
|
||||
assert "id" in result and "memory" in result
|
||||
|
||||
def test_update_projects_fields(self):
|
||||
raw = {"id": "abc", "memory": "updated", "extra": "noise"}
|
||||
result = sanitize_agent_data("update", raw)
|
||||
assert result == {"id": "abc", "memory": "updated"}
|
||||
|
||||
def test_event_list_projects_fields(self):
|
||||
raw = [
|
||||
{
|
||||
"id": "evt-1",
|
||||
"event_type": "ADD",
|
||||
"status": "SUCCEEDED",
|
||||
"graph_status": None,
|
||||
"latency": 100.0,
|
||||
"created_at": "2026-01-01",
|
||||
"updated_at": "2026-01-02",
|
||||
}
|
||||
]
|
||||
result = sanitize_agent_data("event list", raw)
|
||||
assert result == [
|
||||
{
|
||||
"id": "evt-1",
|
||||
"event_type": "ADD",
|
||||
"status": "SUCCEEDED",
|
||||
"latency": 100.0,
|
||||
"created_at": "2026-01-01",
|
||||
}
|
||||
]
|
||||
assert "updated_at" not in result[0]
|
||||
assert "graph_status" not in result[0]
|
||||
|
||||
def test_event_status_flattens_results(self):
|
||||
raw = {
|
||||
"id": "evt-1",
|
||||
"event_type": "ADD",
|
||||
"status": "SUCCEEDED",
|
||||
"latency": 100.0,
|
||||
"created_at": "2026-01-01",
|
||||
"updated_at": "2026-01-02",
|
||||
"results": [
|
||||
{"id": "mem-1", "event": "ADD", "user_id": "alice", "data": {"memory": "dark mode"}}
|
||||
],
|
||||
}
|
||||
result = sanitize_agent_data("event status", raw)
|
||||
assert result["results"][0] == {
|
||||
"id": "mem-1",
|
||||
"event": "ADD",
|
||||
"user_id": "alice",
|
||||
"memory": "dark mode",
|
||||
}
|
||||
assert "data" not in result["results"][0]
|
||||
|
||||
def test_passthrough_commands(self):
|
||||
for cmd in ("status", "import", "config show", "config get", "config set"):
|
||||
data = {"key": "value", "other": "stuff"}
|
||||
assert sanitize_agent_data(cmd, data) == data
|
||||
|
||||
def test_none_data(self):
|
||||
assert sanitize_agent_data("add", None) is None
|
||||
|
||||
Reference in New Issue
Block a user