maximem-synap-cli 0.3.5__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.
@@ -0,0 +1,148 @@
1
+ """`maximem-synap memories ...` — inspect stored memories (read-only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional
6
+
7
+ import typer
8
+
9
+ from synap.cli import render
10
+ from synap.cli.action_rows import action_rows
11
+ from synap.cli.validate import one_of
12
+
13
+ app = typer.Typer(no_args_is_help=True)
14
+
15
+ # "global" is what the server labels a memory with no user and no customer; its own
16
+ # `filters.scopes` lists it, so the CLI must accept it.
17
+ _SCOPES = ("client", "customer", "user", "global")
18
+
19
+ # Mirrors the server's MemoryCategoryName enum
20
+ # (synap/cloud/agents/memory_architecture/models/enums.py) — the same values
21
+ # back both `memories.memory_type` and `client_knowledge.knowledge_type`.
22
+ # Keep in sync when a category is added there.
23
+ _TYPES = ("facts", "preferences", "episodes", "emotions", "temporal_events")
24
+
25
+ _COLUMNS = [
26
+ ("id", "ID"),
27
+ ("content", "CONTENT"),
28
+ ("type", "TYPE"),
29
+ ("scope", "SCOPE"),
30
+ ("confidence", "CONF"),
31
+ ("created_at", "CREATED"),
32
+ ]
33
+
34
+
35
+ def _rows(resp):
36
+ if isinstance(resp, list):
37
+ return resp
38
+ if isinstance(resp, dict):
39
+ for key in ("items", "data", "memories", "results"):
40
+ v = resp.get(key)
41
+ if isinstance(v, list):
42
+ return v
43
+ return []
44
+
45
+
46
+ @app.command(name="list")
47
+ def list_memories(
48
+ ctx: typer.Context,
49
+ instance_id: Optional[str] = typer.Option(None, "--instance", "-i", help="Filter to one instance."),
50
+ search: Optional[str] = typer.Option(None, "--search", "-q", help="Full-text search on content."),
51
+ type_filter: Optional[str] = typer.Option(
52
+ None, "--type",
53
+ help="facts | preferences | episodes | emotions | temporal_events",
54
+ ),
55
+ scope: Optional[str] = typer.Option(None, "--scope", help="client | customer | user | global."),
56
+ entity: Optional[str] = typer.Option(None, "--entity", help="Entity filter."),
57
+ page: int = typer.Option(1, "--page", min=1),
58
+ limit: int = typer.Option(25, "--limit", min=1, max=200),
59
+ ) -> None:
60
+ """List memories with the dashboard's full filter set."""
61
+ one_of(type_filter, _TYPES, flag="--type")
62
+ one_of(scope, _SCOPES, flag="--scope")
63
+ params = {
64
+ "instance_id": instance_id,
65
+ "search": search,
66
+ "type": type_filter,
67
+ "scope": scope,
68
+ "entity": entity,
69
+ "page": page,
70
+ "page_size": limit,
71
+ }
72
+ params = {k: v for k, v in params.items() if v is not None}
73
+ resp = ctx.obj.client().get("/memories", params=params)
74
+ if render.is_json():
75
+ render.print_json(resp)
76
+ return
77
+ rows = _rows(resp)
78
+ total = resp.get("total") if isinstance(resp, dict) else None
79
+ render.print_table(rows, _COLUMNS, empty="No memories match.")
80
+ if total is not None:
81
+ render.info(f"[dim]{len(rows)} shown · {total} total[/dim]")
82
+ # Surface the available filter values the server reports, so devs know what
83
+ # they can filter by (mirrors the dashboard's filter dropdowns).
84
+ filters = resp.get("filters") if isinstance(resp, dict) else None
85
+ if filters and not render.is_json():
86
+ types = filters.get("types") or []
87
+ scopes = filters.get("scopes") or []
88
+ if types or scopes:
89
+ render.info(
90
+ f"[dim]filter by --type {{{', '.join(map(str, types))}}}"
91
+ f" --scope {{{', '.join(map(str, scopes))}}}[/dim]"
92
+ )
93
+
94
+
95
+ @app.command()
96
+ def get(
97
+ ctx: typer.Context,
98
+ memory_id: str = typer.Argument(...),
99
+ ) -> None:
100
+ """Show one memory in full detail."""
101
+ detail = ctx.obj.client().get(f"/memories/{memory_id}")
102
+ render.print_detail(detail, title=f"memory {memory_id}")
103
+
104
+
105
+ @app.command()
106
+ def history(
107
+ ctx: typer.Context,
108
+ memory_id: str = typer.Argument(...),
109
+ ) -> None:
110
+ """Show a memory's action changelog (create/update/supersede/delete)."""
111
+ resp = ctx.obj.client().get(f"/memories/{memory_id}/history")
112
+ if render.is_json():
113
+ render.print_json(resp)
114
+ return
115
+ events = resp if isinstance(resp, list) else (resp.get("events") or [])
116
+ render.print_table(
117
+ action_rows(events),
118
+ [("action", "ACTION"), ("created_at", "TIME"), ("detail", "DETAIL")],
119
+ empty="No history for this memory.",
120
+ )
121
+
122
+
123
+ _LINEAGE_COLUMNS = [
124
+ ("id", "ID"),
125
+ ("content", "CONTENT"),
126
+ ("memory_type", "TYPE"),
127
+ ("link_kind", "LINK"),
128
+ ("link_reason", "REASON"),
129
+ ("deprecated_at", "DEPRECATED"),
130
+ ]
131
+
132
+
133
+ @app.command()
134
+ def lineage(
135
+ ctx: typer.Context,
136
+ memory_id: str = typer.Argument(...),
137
+ ) -> None:
138
+ """Show a memory's immediate lineage (enriched/superseded neighbours)."""
139
+ resp = ctx.obj.client().get(f"/memories/{memory_id}/lineage")
140
+ if render.is_json():
141
+ render.print_json(resp)
142
+ return
143
+ ancestors = resp.get("ancestors") or [] if isinstance(resp, dict) else []
144
+ descendants = resp.get("descendants") or [] if isinstance(resp, dict) else []
145
+ render.info("[bold]Ancestors[/bold] [dim](enriched/superseded into this memory)[/dim]")
146
+ render.print_table(ancestors, _LINEAGE_COLUMNS, empty="No ancestors.")
147
+ render.info("[bold]Descendants[/bold] [dim](this memory was absorbed/replaced into)[/dim]")
148
+ render.print_table(descendants, _LINEAGE_COLUMNS, empty="No descendants.")
@@ -0,0 +1,220 @@
1
+ """`maximem-synap onboard ...` — what the agent-driven setup flow reports and reads."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import unicodedata
6
+ from typing import Optional
7
+
8
+ import typer
9
+
10
+ from synap.cli import render
11
+ from synap.cli.api import CliError
12
+ from synap.cli.validate import one_of, usage_error
13
+
14
+ app = typer.Typer(no_args_is_help=True)
15
+
16
+ STEPS = ("use_case_drafted", "use_case_approved", "integrating", "env_written", "needs_human")
17
+ STATUSES = ("in_progress", "done", "failed", "cleared")
18
+
19
+
20
+ SHARED_STATE_NOTE = (
21
+ "Step rows, agent_name and needs_human are shared by every agent session in this "
22
+ "workspace (the latest report wins), and lifecycle_state covers all its instances. "
23
+ "They say nothing about THIS project. Check `instances list` before you create or reuse "
24
+ "an instance."
25
+ )
26
+
27
+
28
+ TARGET_NAME_MAX = 60
29
+ _EXTRA_HIDDEN = frozenset(
30
+ [0x115F, 0x1160, 0x3164, 0xFFA0] + list(range(0xFE00, 0xFE10)) + list(range(0xE0100, 0xE01F0))
31
+ )
32
+
33
+
34
+ def _has_hidden(value: str) -> bool:
35
+ """Control, format (bidi, zero-width, tag block, soft hyphen ...), surrogate, private-use or
36
+ unassigned characters, line separators, blank fillers, variation selectors, or markup brackets.
37
+ The server applies the same rule; this only fails early with a clear message."""
38
+ if "<" in value or ">" in value:
39
+ return True
40
+ return any(
41
+ ord(ch) in _EXTRA_HIDDEN or unicodedata.category(ch) in ("Cc", "Cf", "Cs", "Co", "Cn", "Zl", "Zp")
42
+ for ch in value
43
+ )
44
+
45
+
46
+ SESSION_NOTE = (
47
+ "Steps and the question above belong to THIS session only. The other sessions are shown "
48
+ "read-only: you cannot change them, and they say nothing about this project."
49
+ )
50
+
51
+
52
+ def _workspace_instances(ctx: typer.Context):
53
+ """The workspace's instances (id, name, relationship, build), or None if unreadable.
54
+
55
+ Best effort: the status call must still work when this listing fails.
56
+ """
57
+ from synap.cli.commands.instances import maca_state
58
+
59
+ try:
60
+ resp = ctx.obj.client().get("/instances", params={"page": 1, "page_size": 50})
61
+ except CliError:
62
+ return None
63
+ rows = resp.get("data") if isinstance(resp, dict) else None
64
+ if not isinstance(rows, list):
65
+ return None
66
+ return [
67
+ {
68
+ "id": r.get("id"),
69
+ "name": r.get("name"),
70
+ "user_relationship": r.get("user_relationship"),
71
+ "build": maca_state(r)[0],
72
+ }
73
+ for r in rows if isinstance(r, dict)
74
+ ]
75
+
76
+
77
+ @app.command()
78
+ def status(ctx: typer.Context) -> None:
79
+ """Show the onboarding state: lifecycle plus what the agent has reported.
80
+
81
+ Also lists the instances the workspace already has. The state is per
82
+ WORKSPACE, not per agent session or project: another session's finished
83
+ steps show here as done.
84
+ """
85
+ instances = _workspace_instances(ctx)
86
+ state = ctx.obj.client().get("/onboarding/state")
87
+ if not isinstance(state, dict):
88
+ raise CliError("The server returned no onboarding state.", code="bad_response",
89
+ exit_code=8)
90
+ mine = state.get("session")
91
+ if instances is not None:
92
+ # A server with per-session state says so; only an older one needs the warning.
93
+ note = SESSION_NOTE if mine else SHARED_STATE_NOTE
94
+ state = {**state, "instances": instances, "note": note}
95
+ if render.is_json():
96
+ render.print_json(state)
97
+ return
98
+ agent = state.get("agent") or {}
99
+ detail = {
100
+ "lifecycle_state": state.get("lifecycle_state"),
101
+ "setup_complete": state.get("setup_complete"),
102
+ "agent_connected": agent.get("connected"),
103
+ "agent_name": agent.get("agent_name"),
104
+ "needs_human": (agent.get("needs_human") or {}).get("question"),
105
+ }
106
+ if mine:
107
+ detail.update({
108
+ "session": mine.get("id"),
109
+ "session_state": mine.get("state"),
110
+ "target_agent": mine.get("target_agent_name") or "not set (run `onboard target \"<AgentName>\"`)",
111
+ "session_instance": mine.get("instance_id"),
112
+ })
113
+ render.print_detail(detail, title="Onboarding")
114
+ steps = agent.get("steps") or {}
115
+ if steps:
116
+ rows = [
117
+ {"step": name, "status": (v or {}).get("status"), "detail": (v or {}).get("detail")}
118
+ for name, v in steps.items()
119
+ ]
120
+ render.print_table(rows, [("step", "STEP"), ("status", "STATUS"), ("detail", "DETAIL")])
121
+ others = state.get("other_sessions") or []
122
+ if mine is not None:
123
+ render.print_table(
124
+ [
125
+ {
126
+ "tool": o.get("tool_name") or "Agent", "target": o.get("target_agent_name") or "-",
127
+ "state": o.get("state"), "instance": o.get("instance_id") or "-",
128
+ "waiting": "yes" if o.get("waiting_for_human") else "",
129
+ }
130
+ for o in others
131
+ ],
132
+ [("tool", "TOOL"), ("target", "AGENT"), ("state", "STATE"), ("instance", "INSTANCE"),
133
+ ("waiting", "WAITING")],
134
+ title="Other sessions in this workspace (read-only)", empty="No other sessions.",
135
+ full_keys=("instance",),
136
+ )
137
+ if instances is not None:
138
+ render.info(f"[dim]{state['note']}[/dim]")
139
+ render.print_table(
140
+ instances,
141
+ [("id", "ID"), ("name", "NAME"), ("user_relationship", "RELATIONSHIP"), ("build", "BUILD")],
142
+ title="Instances in this workspace", empty="No instances in this workspace yet.",
143
+ full_keys=("id",),
144
+ )
145
+
146
+
147
+ def _post_event(ctx: typer.Context, step: str, status_: str, detail: Optional[str]) -> None:
148
+ body = {"step": step, "status": status_}
149
+ if detail:
150
+ body["detail"] = detail
151
+ resp = ctx.obj.client().post("/onboarding/events", json=body)
152
+ if render.is_json():
153
+ render.print_json(resp if isinstance(resp, dict) else {"ok": True, **body})
154
+ return
155
+ render.success(f"Reported {step}: {status_}.")
156
+
157
+
158
+ @app.command()
159
+ def report(
160
+ ctx: typer.Context,
161
+ step: str = typer.Argument(..., help=" | ".join(STEPS)),
162
+ status: str = typer.Argument(..., help=" | ".join(STATUSES)),
163
+ detail: Optional[str] = typer.Option(None, "--detail", help="Short note shown on the dashboard."),
164
+ ) -> None:
165
+ """Report an onboarding step so the dashboard checklist can show it."""
166
+ one_of(step, STEPS, flag="step")
167
+ one_of(status, STATUSES, flag="status")
168
+ _post_event(ctx, step, status, detail)
169
+
170
+
171
+ @app.command()
172
+ def ask(
173
+ ctx: typer.Context,
174
+ question: Optional[str] = typer.Argument(None, help="What you are waiting for the human to answer."),
175
+ clear: bool = typer.Option(False, "--clear", help="Clear the pending question."),
176
+ ) -> None:
177
+ """Tell the dashboard the agent is blocked on a human answer (or clear it)."""
178
+ if clear:
179
+ if question:
180
+ raise usage_error("Pass either a question or --clear, not both.")
181
+ _post_event(ctx, "needs_human", "cleared", None)
182
+ return
183
+ if not question or not question.strip():
184
+ raise usage_error("Pass the question to show, or --clear.")
185
+ _post_event(ctx, "needs_human", "in_progress", question.strip())
186
+
187
+
188
+ @app.command()
189
+ def target(
190
+ ctx: typer.Context,
191
+ name: str = typer.Argument(..., help="The client's agent you are adding memory to, e.g. BillingAgent."),
192
+ ) -> None:
193
+ """Name the agent this session is integrating (set it once the human has chosen).
194
+
195
+ Shown on the dashboard next to the tool you run as (e.g. Claude Code). Safe to
196
+ run again to change it. Affects this session only.
197
+ """
198
+ value = (name or "").strip()
199
+ if not value:
200
+ raise usage_error("The agent name is empty.")
201
+ if _has_hidden(value):
202
+ raise usage_error("The agent name must be plain one-line text: no control, invisible or direction characters, no < or >.")
203
+ if len(value) > TARGET_NAME_MAX:
204
+ raise usage_error(f"The agent name is {len(value)} characters; the limit is {TARGET_NAME_MAX}.")
205
+ resp = ctx.obj.client().put("/onboarding/session/target", json={"target_agent_name": value})
206
+ # Remember it in this session's profile so `auth list` can name the session.
207
+ try:
208
+ cc = ctx.obj
209
+ cc.store.reload()
210
+ if cc.store.has_profile(cc.profile_name) and cc.store.get_profile(cc.profile_name).session_id:
211
+ prof = cc.store.get_profile(cc.profile_name)
212
+ prof.target_agent = value
213
+ cc.store.set_profile(cc.profile_name, prof)
214
+ cc.store.save()
215
+ except Exception: # noqa: BLE001 - a local label must never fail the command
216
+ pass
217
+ if render.is_json():
218
+ render.print_json(resp if isinstance(resp, dict) else {"target_agent_name": value})
219
+ return
220
+ render.success(f"This session is integrating: {value}.")