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.
synap/cli/app.py ADDED
@@ -0,0 +1,362 @@
1
+ """Typer application wiring + shared CLI context."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from typing import Optional
8
+
9
+ import typer
10
+
11
+ from synap.cli import __version__
12
+ from synap.cli.api import EXIT_AUTH, EXIT_USAGE, ApiClient, CliError
13
+ from synap.cli.config import ConfigStore, DEFAULT_API_BASE, Profile, env_base, env_hint
14
+ from synap.cli import interactive, render
15
+
16
+
17
+ @dataclass
18
+ class CliContext:
19
+ store: ConfigStore
20
+ profile_name: str
21
+ api_base_override: Optional[str]
22
+ env_override: Optional[str]
23
+ verbose: bool
24
+ # True when the profile came from --profile or SYNAP_PROFILE, not the default.
25
+ profile_explicit: bool = False
26
+
27
+ def active_profile(self) -> Profile:
28
+ return self.store.get_profile(self.profile_name)
29
+
30
+ def api_base(self) -> str:
31
+ # Precedence: --api-base > --env > saved profile > built-in default (prod).
32
+ if self.api_base_override:
33
+ return self.api_base_override
34
+ if self.env_override:
35
+ return env_base(self.env_override)
36
+ return self.active_profile().api_base or DEFAULT_API_BASE
37
+
38
+ def login_api_base(self) -> str:
39
+ # Server to log INTO. Unlike api_base(), this ignores any existing
40
+ # profile so `auth login` targets the default (prod) — or an explicit
41
+ # --api-base/--env/SYNAP_API_BASE — even when a stale profile points
42
+ # somewhere else (e.g. an old localhost session).
43
+ if self.api_base_override:
44
+ return self.api_base_override
45
+ if self.env_override:
46
+ return env_base(self.env_override)
47
+ return DEFAULT_API_BASE
48
+
49
+ def _refuse_if_session_ambiguous(self, profile: Profile) -> None:
50
+ """Two setup sessions on one machine: the active profile is only the LAST login, so an
51
+ unpinned command could act as the other agent. Refuse, and say how to pin."""
52
+ if self.profile_explicit or profile.key_origin != "onboarding-code":
53
+ return
54
+ names = [
55
+ n for n in self.store.profile_names()
56
+ if self.store.get_profile(n).is_logged_in()
57
+ and self.store.get_profile(n).key_origin == "onboarding-code"
58
+ ]
59
+ if len(names) < 2:
60
+ return
61
+ raise CliError(
62
+ f"More than one setup session is saved on this machine ({', '.join(names)}) and no "
63
+ "profile is pinned, so this command might act as the wrong agent. Nothing was done.",
64
+ code="profile_not_pinned", exit_code=EXIT_USAGE,
65
+ hint="Pin YOUR session: add `--profile <name>` to the command, or run "
66
+ "`export SYNAP_PROFILE=<name>` in a shell that persists. Your profile name was printed "
67
+ "by `auth login --code`; `maximem-synap auth list` shows every profile.",
68
+ )
69
+
70
+ def client(self, require_auth: bool = True) -> ApiClient:
71
+ # SYNAP_API_KEY wins over any stored profile — the zero-config path for
72
+ # CI / servers / containers where the browser pairing flow can't run.
73
+ env_key = os.getenv("SYNAP_API_KEY")
74
+ if env_key:
75
+ return ApiClient(
76
+ self.api_base(), env_key, verbose=self.verbose, key_from_env=True,
77
+ )
78
+ profile = self.active_profile()
79
+ if require_auth and profile.is_logged_in():
80
+ self._refuse_if_session_ambiguous(profile)
81
+ if require_auth and not profile.is_logged_in():
82
+ others = self.store.profile_names()
83
+ if not self.profile_name and others:
84
+ # A logout left no active profile on purpose; never pick one for the user.
85
+ raise CliError(
86
+ "No profile is active (the last one was logged out). Other saved "
87
+ f"profiles: {', '.join(others)}.",
88
+ code="not_authenticated", exit_code=EXIT_AUTH,
89
+ hint="Run `maximem-synap auth use <name>` or pass `--profile <name>`, "
90
+ "or log in again with `maximem-synap auth login --code <code>`.",
91
+ )
92
+ raise CliError(
93
+ "Not logged in. Run `maximem-synap auth login --code <code>` "
94
+ "(or set SYNAP_API_KEY for CI/servers).",
95
+ code="not_authenticated", exit_code=EXIT_AUTH,
96
+ hint="No credentials found. Ask the human for a fresh onboarding code, then run `maximem-synap auth login --code <code>`.",
97
+ )
98
+ return ApiClient(
99
+ self.api_base(),
100
+ profile.api_key if require_auth else None,
101
+ verbose=self.verbose,
102
+ )
103
+
104
+ def pinned_client(self, announce: bool = True) -> ApiClient:
105
+ """A client bound NOW to the resolved profile and key, for long-running
106
+ commands. The key is captured once, so a later `auth login` that rewrites
107
+ the config file cannot change which workspace a poll loop talks to."""
108
+ client = self.client()
109
+ if announce:
110
+ source = "SYNAP_API_KEY" if os.getenv("SYNAP_API_KEY") else f"profile {self.profile_name}"
111
+ render.err_console.print(f" [dim]Using {source} ({client.api_base})[/dim]")
112
+ return client
113
+
114
+
115
+ app = typer.Typer(
116
+ name="maximem-synap",
117
+ help="maximem-synap — provision and operate Synap from your terminal.",
118
+ no_args_is_help=True,
119
+ add_completion=True,
120
+ # A crash traceback must never print local variables: they can hold a fresh
121
+ # API key or a one-time code.
122
+ pretty_exceptions_show_locals=False,
123
+ )
124
+
125
+
126
+ def _version_callback(value: bool) -> None:
127
+ if value:
128
+ render.console.print(f"maximem-synap {__version__}")
129
+ raise typer.Exit()
130
+
131
+
132
+ @app.callback()
133
+ def main_callback(
134
+ ctx: typer.Context,
135
+ profile: str = typer.Option(
136
+ None, "--profile", "-p", help="Use a named profile/account.",
137
+ ),
138
+ output: str = typer.Option(
139
+ None, "--output", "-o", help="Output format: table | json | csv (default: table).",
140
+ ),
141
+ json_flag: bool = typer.Option(
142
+ False, "--json", help="Alias for `--output json`. Conflicts with an explicit --output other than json.",
143
+ ),
144
+ quiet: bool = typer.Option(
145
+ False, "--quiet", help="Suppress success/info chatter (errors still shown).",
146
+ ),
147
+ env: str = typer.Option(
148
+ None, "--env", help="Target environment: prod | staging (default: prod). staging needs SYNAP_STAGING_API_BASE.",
149
+ ),
150
+ api_base: str = typer.Option(
151
+ None, "--api-base", help="Override the Synap server base URL (e.g. for local dev).",
152
+ ),
153
+ verbose: bool = typer.Option(
154
+ False, "--verbose", "-v", help="Echo HTTP requests to stderr.",
155
+ ),
156
+ non_interactive: bool = typer.Option(
157
+ False, "--non-interactive",
158
+ help="Never prompt; fail with a hint instead. Automatic when stdin is not a "
159
+ "TTY or SYNAP_NON_INTERACTIVE=1.",
160
+ ),
161
+ _version: bool = typer.Option(
162
+ None, "--version", callback=_version_callback, is_eager=True,
163
+ help="Show the CLI version and exit.",
164
+ ),
165
+ ) -> None:
166
+ """Root options shared by every command."""
167
+ if json_flag and output is not None and output != "json":
168
+ raise CliError(
169
+ f"--json conflicts with --output {output}. Use one of them.",
170
+ code="invalid_argument", exit_code=EXIT_USAGE,
171
+ )
172
+ if json_flag:
173
+ output = "json"
174
+ render.set_output(output if output in ("table", "json", "csv") else "table")
175
+ render.set_quiet(quiet)
176
+ interactive.set_non_interactive(non_interactive)
177
+ if env is not None and env_base(env) is None:
178
+ raise CliError(
179
+ env_hint(env),
180
+ code="invalid_argument", exit_code=EXIT_USAGE,
181
+ )
182
+ store = ConfigStore()
183
+ ctx.obj = CliContext(
184
+ store=store,
185
+ profile_name=profile or os.getenv("SYNAP_PROFILE") or store.default_profile,
186
+ profile_explicit=bool(profile or os.getenv("SYNAP_PROFILE")),
187
+ api_base_override=api_base,
188
+ env_override=env,
189
+ verbose=verbose,
190
+ )
191
+
192
+
193
+ # Register command groups (imported here to avoid circular imports).
194
+ from synap.cli.commands import auth as auth_cmd # noqa: E402
195
+ from synap.cli.commands import instances as instances_cmd # noqa: E402
196
+ from synap.cli.commands import api_keys as api_keys_cmd # noqa: E402
197
+ from synap.cli.commands import client as client_cmd # noqa: E402
198
+ from synap.cli.commands import requests as requests_cmd # noqa: E402
199
+ from synap.cli.commands import memories as memories_cmd # noqa: E402
200
+ from synap.cli.commands import privacy as privacy_cmd # noqa: E402
201
+ from synap.cli.commands import visibility as visibility_cmd # noqa: E402
202
+ from synap.cli.commands import scoping as scoping_cmd # noqa: E402
203
+ from synap.cli.commands import billing as billing_cmd # noqa: E402
204
+ from synap.cli.commands import config_cmd # noqa: E402
205
+ from synap.cli.commands import onboard as onboard_cmd # noqa: E402
206
+ from synap.cli.commands import skill as skill_cmd # noqa: E402
207
+
208
+ app.add_typer(auth_cmd.app, name="auth", help="Log in, log out, switch accounts.")
209
+ app.add_typer(instances_cmd.app, name="instances", help="Manage memory instances.")
210
+ app.add_typer(api_keys_cmd.app, name="api-keys", help="Manage runtime API keys.")
211
+ app.add_typer(client_cmd.app, name="client", help="Inspect your client and team.")
212
+ app.add_typer(requests_cmd.app, name="requests", help="Inspect request-level SDK activity.")
213
+ app.add_typer(memories_cmd.app, name="memories", help="Inspect stored memories (read-only).")
214
+ app.add_typer(privacy_cmd.app, name="privacy", help="Sensitive-data policy, protection and audit.")
215
+ app.add_typer(visibility_cmd.app, name="visibility", help="Which instances can read which.")
216
+ app.add_typer(scoping_cmd.app, name="scoping", help="The scope ladder and nested scoping.")
217
+ app.add_typer(billing_cmd.app, name="billing", help="Billing controls: overages.")
218
+ app.add_typer(config_cmd.app, name="config", help="Local CLI settings.")
219
+ app.add_typer(onboard_cmd.app, name="onboard", help="Agent-driven onboarding: status and progress reports.")
220
+ app.add_typer(skill_cmd.app, name="skill", help="Install the Synap agent skill.")
221
+
222
+
223
+ @app.command()
224
+ def whoami(ctx: typer.Context) -> None:
225
+ """Show the account the active profile is logged into (alias of `auth whoami`)."""
226
+ auth_cmd.whoami(ctx)
227
+
228
+
229
+ def _latest_release() -> Optional[str]:
230
+ """Best-effort latest published CLI version (None on any failure).
231
+
232
+ Polls npm, not PyPI: `@maximem/synap-cli` is the only channel the CLI is
233
+ actually published on. This used to query `maximem-synap-cli` on PyPI,
234
+ which has never been published — so the lookup 404'd every time, returned
235
+ None, and `doctor` silently dropped its "are you up to date?" row instead
236
+ of ever reporting an available upgrade.
237
+ """
238
+ try:
239
+ import httpx
240
+ r = httpx.get(
241
+ "https://registry.npmjs.org/@maximem%2Fsynap-cli/latest", timeout=5.0
242
+ )
243
+ if r.status_code == 200:
244
+ return r.json().get("version")
245
+ except Exception:
246
+ return None
247
+ return None
248
+
249
+
250
+ @app.command()
251
+ def usage(
252
+ ctx: typer.Context,
253
+ period: str = typer.Option("30d", "--period", help="all | 1d | 7d | 30d | 90d | custom."),
254
+ start: Optional[str] = typer.Option(None, "--start", help="YYYY-MM-DD (with --period custom)."),
255
+ end: Optional[str] = typer.Option(None, "--end", help="YYYY-MM-DD (with --period custom)."),
256
+ ) -> None:
257
+ """Show aggregate usage (API calls, LLM tokens, memories) for your client."""
258
+ cc: CliContext = ctx.obj
259
+ if start or end:
260
+ period = "custom"
261
+ if period == "custom" and not (start and end):
262
+ # The server only honours a custom window with both dates and otherwise returns the last
263
+ # 30 days without saying so.
264
+ missing = "--end" if start else ("--start" if end else "--start and --end")
265
+ raise CliError(f"A custom window needs both dates: add {missing} (YYYY-MM-DD).")
266
+ params = {k: v for k, v in {
267
+ "period": period, "start_date": start, "end_date": end,
268
+ }.items() if v is not None}
269
+ resp = cc.client().get("/usage", params=params)
270
+ data = resp if isinstance(resp, dict) else {"usage": resp}
271
+ render.print_detail(data, title=f"Usage · {period}")
272
+
273
+
274
+ @app.command()
275
+ def doctor(ctx: typer.Context) -> None:
276
+ """Diagnose install, config, auth, and server connectivity."""
277
+ import platform
278
+ import sys
279
+
280
+ cc: CliContext = ctx.obj
281
+ checks: list = []
282
+
283
+ def add(name: str, ok: bool, detail: str) -> None:
284
+ checks.append({"check": name, "status": "ok" if ok else "warn", "detail": detail})
285
+
286
+ add("cli_version", True, __version__)
287
+ add("python", sys.version_info >= (3, 10),
288
+ f"{platform.python_version()} ({sys.executable})")
289
+ cfg = cc.store.path
290
+ add("config", True, f"{cfg} ({'exists' if cfg.exists() else 'not created yet'})")
291
+
292
+ env_key = bool(os.getenv("SYNAP_API_KEY"))
293
+ profile = cc.active_profile()
294
+ logged_in = env_key or profile.is_logged_in()
295
+ add("auth", logged_in,
296
+ "SYNAP_API_KEY set" if env_key
297
+ else (f"profile '{cc.profile_name}'" if logged_in else "not logged in"))
298
+ add("api_base", True, cc.api_base())
299
+
300
+ who = None
301
+ reachable = False
302
+ try:
303
+ if logged_in:
304
+ who = cc.client().get("/whoami")
305
+ else:
306
+ # Unauthenticated ping: a 401 still proves the server is reachable.
307
+ ApiClient(cc.api_base(), verbose=cc.verbose).get("/whoami", auth=False)
308
+ reachable = True
309
+ except CliError as e:
310
+ reachable = e.status_code is not None
311
+ add("connectivity", reachable, "reachable" if reachable else "unreachable")
312
+
313
+ if who:
314
+ add("client", True, who.get("client_name") or who.get("client_id"))
315
+ note = auth_cmd._expiry_note(
316
+ who.get("expires_at"),
317
+ issued_at=None if env_key else profile.api_key_issued_at,
318
+ onboarding=(who.get("origin") or (None if env_key else profile.key_origin))
319
+ == auth_cmd.ONBOARDING_KEY_ORIGIN,
320
+ )
321
+ add("key_expiry", note is None, note or "ok")
322
+
323
+ # Privacy posture, because "configured" and "protecting something" are
324
+ # different facts and only the second one matters. A policy on the
325
+ # `standard` preset reads as protective and leaves names, dates of birth
326
+ # and phone numbers unaliased, so a green auth row next to an
327
+ # unconfigured policy is a misleading pair of answers.
328
+ #
329
+ # Best-effort: a key without `read:privacy` is not a broken install, so a
330
+ # failure here reports "not checked" rather than turning doctor red.
331
+ try:
332
+ protection = cc.client().get("/privacy/protection")
333
+ protected = None
334
+ if isinstance(protection, dict):
335
+ protected = protection.get("is_protecting")
336
+ if protected is None:
337
+ protected = protection.get("protecting")
338
+ if protected is None:
339
+ add("privacy", True, "policy reachable")
340
+ else:
341
+ add(
342
+ "privacy",
343
+ bool(protected),
344
+ "protecting" if protected
345
+ else "nothing is protected (see `maximem-synap privacy status`)",
346
+ )
347
+ except CliError as e:
348
+ add("privacy", True, f"not checked ({e.status_code or 'unreachable'})")
349
+
350
+ latest = _latest_release()
351
+ if latest:
352
+ add("latest_version", latest == __version__,
353
+ "up to date" if latest == __version__ else f"{latest} available (installed {__version__})")
354
+
355
+ render.print_table(
356
+ checks,
357
+ [("check", "CHECK"), ("status", "STATUS"), ("detail", "DETAIL")],
358
+ title="maximem-synap doctor",
359
+ )
360
+ warns = [c for c in checks if c["status"] != "ok"]
361
+ if warns and not render.is_machine():
362
+ render.warn(f"{len(warns)} check(s) need attention.")
@@ -0,0 +1 @@
1
+ """maximem-synap CLI command groups."""