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,342 @@
1
+ """`maximem-synap billing ...`: billing controls for your client.
2
+
3
+ Backed by `/api/v1/management/billing/*`, the same code the dashboard's
4
+ Plan & billing tab runs.
5
+
6
+ Overages
7
+ --------
8
+ Overages decide what happens when a paid plan's credits run out. Off (the
9
+ default for every client) means requests stop and the SDK raises
10
+ `InsufficientCreditsError`. On means requests keep working and the usage past
11
+ the allowance is billed per 1,000 credits at the plan's overage rate.
12
+
13
+ Three things about this switch are worth knowing before using it:
14
+
15
+ - **Only the client owner can change it.** A key approved by an admin reads it
16
+ but gets a permission error on `set`. The server decides that, not the CLI;
17
+ `get` reports `can_edit` so a script can check first.
18
+ - **Turning it on needs a chargeable card.** That means the subscription's
19
+ default card, or the billing account's default card, and not expired. Any
20
+ other card on file does not count. The server re-checks this on every
21
+ `set --allow`, so a stale `get` cannot turn it on.
22
+ - **Synap can turn it off for you.** When that card is removed or expires, or
23
+ the subscription is cancelled, overages go off automatically and every member
24
+ is emailed. `updated_by` then reads as Synap, with the reason.
25
+
26
+ Turning overages off never needs a card and never prompts.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from typing import Any, Dict, Optional
32
+
33
+ import typer
34
+
35
+ from synap.cli import interactive, render
36
+ from synap.cli.api import CliError
37
+
38
+ app = typer.Typer(no_args_is_help=True)
39
+ overages_app = typer.Typer(no_args_is_help=True)
40
+ app.add_typer(
41
+ overages_app,
42
+ name="overages",
43
+ help="Whether usage can continue past your plan's credits (billed per 1,000 credits).",
44
+ )
45
+
46
+ _OVERAGES_PATH = "/billing/overages"
47
+
48
+ # Where a person fixes a card or a plan. Named rather than linked: the CLI does
49
+ # not know which dashboard host a profile belongs to.
50
+ _DASHBOARD_PLACE = "the Synap dashboard (Credits & Usage, then Plan & billing)"
51
+
52
+ # Plain words for each `IneligibleReason` the server can return. Mirrors
53
+ # synap/cloud/application/credits/overage_settings.py (a test pins the parity);
54
+ # kept as literals because the CLI ships without the server package.
55
+ _REASON_WORDS: Dict[str, str] = {
56
+ "trial_plan": (
57
+ "the Trial plan cannot carry overages. Upgrade to Starter, Pro or Scale "
58
+ f"in {_DASHBOARD_PLACE}."
59
+ ),
60
+ "no_overage_rate": "your plan has no overage rate, so there is nothing to bill usage at.",
61
+ "enterprise_plan": (
62
+ "Enterprise usage past the allowance is covered by your contract, so there "
63
+ "is no switch to change."
64
+ ),
65
+ "subscription_inactive": (
66
+ "your subscription is not active (for example, a payment is past due or it "
67
+ f"was cancelled). Check it in {_DASHBOARD_PLACE}."
68
+ ),
69
+ "no_card": (
70
+ "there is no default card on your subscription or billing account. Add one "
71
+ f"in {_DASHBOARD_PLACE}."
72
+ ),
73
+ "card_expired": f"your default card has expired. Update it in {_DASHBOARD_PLACE}.",
74
+ "stripe_unavailable": (
75
+ "your card could not be checked with the payment provider just now. Try "
76
+ "again in a minute."
77
+ ),
78
+ }
79
+
80
+ # Plain words for the `system:<trigger>` actors Synap writes when it turns
81
+ # overages off on its own. Mirrors the TRIGGER_* and PLAN_CHANGE_* constants in
82
+ # overage_settings.py.
83
+ _SYSTEM_TRIGGER_WORDS: Dict[str, str] = {
84
+ "payment_method_detached": "card removed",
85
+ "customer_updated": "default card changed",
86
+ "subscription_updated": "subscription card changed",
87
+ "invoice_created": "card checked at renewal",
88
+ "card_expiry_sweep": "card expired",
89
+ "subscription_deleted": "subscription cancelled",
90
+ "plan_changed": "plan changed",
91
+ "subscription_status_changed": "subscription status changed",
92
+ }
93
+
94
+ _OWNER_REQUIRED = (
95
+ "Only the client owner can change overages, and this key does not act as the "
96
+ "owner. Ask the owner to change it in the Synap dashboard, or to run this "
97
+ "command after `maximem-synap auth login`."
98
+ )
99
+
100
+ # A key approved by a member holds read scopes only, so the server refuses it
101
+ # at the scope gate (403 missing_scope) before the owner check is reached.
102
+ _MEMBER_KEY_CANNOT_CHANGE = (
103
+ _OWNER_REQUIRED + " (This key is read-only: it does not have the 'manage:billing' scope.)"
104
+ )
105
+ _CANNOT_READ = (
106
+ "This key cannot read billing settings: it does not have the 'read:billing' "
107
+ "scope. Run `maximem-synap auth login` to get a key with your current permissions."
108
+ )
109
+
110
+
111
+ def reason_words(reason: Optional[str], fallback: Optional[str] = None) -> Optional[str]:
112
+ """A reason code in plain words, or the server's own sentence if it is new to us."""
113
+ if not reason:
114
+ return None
115
+ return _REASON_WORDS.get(reason) or fallback or reason.replace("_", " ")
116
+
117
+
118
+ def actor_words(actor: Optional[str]) -> Optional[str]:
119
+ """Render the raw `updated_by` actor the way a person would say it."""
120
+ if not actor:
121
+ return None
122
+ if actor.startswith("system:"):
123
+ trigger = actor[len("system:"):]
124
+ return f"Synap, automatically ({_SYSTEM_TRIGGER_WORDS.get(trigger, trigger)})"
125
+ if actor.startswith("cli:"):
126
+ name, _, short_id = actor[len("cli:"):].rpartition("#")
127
+ if not name:
128
+ name, short_id = short_id, ""
129
+ return f"CLI key {name}" + (f" (#{short_id})" if short_id else "")
130
+ return actor
131
+
132
+
133
+ def _rate_words(rate: Any) -> Optional[str]:
134
+ if rate is None:
135
+ return None
136
+ try:
137
+ return f"${float(rate):.2f} per 1,000 credits"
138
+ except (TypeError, ValueError):
139
+ return str(rate)
140
+
141
+
142
+ def _card_words(card: Optional[Dict[str, Any]]) -> Optional[str]:
143
+ if not card:
144
+ return None
145
+ if card.get("type") == "link":
146
+ email = card.get("email")
147
+ return f"Link ({email})" if email else "Link"
148
+ brand = (card.get("brand") or "card").title()
149
+ last4 = card.get("last4")
150
+ return f"{brand} ending {last4}" if last4 else brand
151
+
152
+
153
+ def _expiry_words(card: Optional[Dict[str, Any]]) -> Optional[str]:
154
+ if not card:
155
+ return None
156
+ month, year = card.get("exp_month"), card.get("exp_year")
157
+ if not month or not year:
158
+ return None
159
+ try:
160
+ return f"{int(month):02d}/{int(year)}"
161
+ except (TypeError, ValueError):
162
+ return f"{month}/{year}"
163
+
164
+
165
+ def _settings_row(resp: Dict[str, Any]) -> Dict[str, Any]:
166
+ """The overages response flattened for a key/value table or CSV."""
167
+ card = resp.get("card") or None
168
+ return {
169
+ "allowed": resp.get("allowed"),
170
+ "eligible": resp.get("eligible"),
171
+ "reason": reason_words(resp.get("ineligible_reason")),
172
+ "plan": resp.get("plan_id"),
173
+ "rate": _rate_words(resp.get("overage_rate_per_1k_credits")),
174
+ "card": _card_words(card),
175
+ "card_brand": card.get("brand") if card else None,
176
+ "card_last4": card.get("last4") if card else None,
177
+ "card_expiry": _expiry_words(card),
178
+ "card_expired": card.get("expired") if card else None,
179
+ "updated_by": actor_words(resp.get("updated_by")),
180
+ "updated_at": resp.get("updated_at"),
181
+ "can_edit": resp.get("can_edit"),
182
+ }
183
+
184
+
185
+ def _render_settings(resp: Dict[str, Any], *, title: str) -> None:
186
+ if render.is_json():
187
+ render.print_json(resp)
188
+ return
189
+ row = _settings_row(resp)
190
+ if render.is_csv():
191
+ render.print_detail(row)
192
+ return
193
+ # The table drops the split-out card columns: `card` and `card_expiry`
194
+ # already say the same thing in one line each.
195
+ shown = {k: v for k, v in row.items() if k not in ("card_brand", "card_last4")}
196
+ render.print_detail(shown, title=title)
197
+
198
+
199
+ def _explain_state(resp: Dict[str, Any]) -> None:
200
+ """One or two lines on what the current state means. Humans only."""
201
+ if render.is_machine():
202
+ return
203
+ code = resp.get("ineligible_reason")
204
+ reason = reason_words(code)
205
+
206
+ if code == "enterprise_plan":
207
+ # The reason row already says it all: there is no switch to explain.
208
+ return
209
+ if resp.get("allowed"):
210
+ if reason:
211
+ render.warn(f"Overages are on, but {reason}")
212
+ else:
213
+ render.info(
214
+ "[dim]When your credits run out, requests keep working and the extra "
215
+ "usage is billed at your plan's overage rate.[/dim]"
216
+ )
217
+ elif code in ("trial_plan", "subscription_inactive"):
218
+ # These stop at zero as a Trial does, whatever the switch says.
219
+ render.info("[dim]Requests stop when your credits run out.[/dim]")
220
+ render.info(f"[dim]Overages cannot be turned on yet: {reason}[/dim]")
221
+ else:
222
+ render.info(
223
+ "[dim]Overages are off: when your credits run out, requests stop and the "
224
+ "SDK raises InsufficientCreditsError.[/dim]"
225
+ )
226
+ if reason:
227
+ render.info(f"[dim]They cannot be turned on yet: {reason}[/dim]")
228
+ elif resp.get("can_edit"):
229
+ render.info(
230
+ "[dim]Turn them on with `maximem-synap billing overages set --allow`.[/dim]"
231
+ )
232
+ if not resp.get("can_edit"):
233
+ render.info("[dim]Only the client owner can change this setting.[/dim]")
234
+
235
+
236
+ def _translate(error: CliError) -> CliError:
237
+ """Turn the refusals this route can answer with into guidance."""
238
+ detail = error.detail if isinstance(error.detail, dict) else {}
239
+ code = detail.get("error")
240
+ if error.status_code == 403 and code == "owner_required":
241
+ return CliError(_OWNER_REQUIRED, status_code=403, detail=error.detail)
242
+ if error.status_code == 403 and code == "missing_scope":
243
+ if detail.get("required") == "manage:billing":
244
+ return CliError(_MEMBER_KEY_CANNOT_CHANGE, status_code=403, detail=error.detail)
245
+ if detail.get("required") == "read:billing":
246
+ return CliError(_CANNOT_READ, status_code=403, detail=error.detail)
247
+ if error.status_code == 409 and code == "overages_not_eligible":
248
+ words = reason_words(detail.get("reason"), fallback=detail.get("message"))
249
+ return CliError(
250
+ f"Overages were not turned on: {words}",
251
+ status_code=409,
252
+ detail=error.detail,
253
+ )
254
+ return error
255
+
256
+
257
+ @overages_app.command(name="get")
258
+ def overages_get(ctx: typer.Context) -> None:
259
+ """Show whether overages are on, whether they can be, the rate, and the card."""
260
+ try:
261
+ resp = ctx.obj.client().get(_OVERAGES_PATH)
262
+ except CliError as e:
263
+ raise _translate(e)
264
+ _render_settings(resp, title="Overages")
265
+ _explain_state(resp)
266
+
267
+
268
+ @overages_app.command(name="set")
269
+ def overages_set(
270
+ ctx: typer.Context,
271
+ allow: bool = typer.Option(
272
+ False, "--allow",
273
+ help="Turn overages on. Needs a paid plan and a chargeable default card.",
274
+ ),
275
+ disallow: bool = typer.Option(
276
+ False, "--disallow", help="Turn overages off. Requests stop when credits run out.",
277
+ ),
278
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt (required without a terminal)."),
279
+ ) -> None:
280
+ """Turn overages on or off for the client. Owner only.
281
+
282
+ Turning them on asks for confirmation first (skip it with --yes), because it
283
+ is the step that lets Synap bill past the plan's allowance. The check the
284
+ prompt shows is repeated by the server, so nothing is turned on that the
285
+ server would not allow.
286
+ """
287
+ if allow == disallow:
288
+ raise CliError("Pass exactly one of --allow or --disallow.")
289
+ client = ctx.obj.client()
290
+
291
+ if allow and not yes:
292
+ try:
293
+ current = client.get(_OVERAGES_PATH)
294
+ except CliError as e:
295
+ raise _translate(e)
296
+ if not current.get("can_edit"):
297
+ raise CliError(_OWNER_REQUIRED, status_code=403)
298
+ if not current.get("eligible"):
299
+ words = (
300
+ reason_words(current.get("ineligible_reason"))
301
+ or "this client is not eligible."
302
+ )
303
+ raise CliError(f"Overages were not turned on: {words}", status_code=409)
304
+ if current.get("allowed"):
305
+ render.success("Overages are already on. Nothing changed.")
306
+ if render.is_machine():
307
+ _render_settings(current, title="Overages")
308
+ return
309
+
310
+ rate = _rate_words(current.get("overage_rate_per_1k_credits"))
311
+ card = _card_words(current.get("card"))
312
+ render.info(
313
+ "With overages on, requests keep working after your plan's credits run "
314
+ "out, and the extra usage is billed"
315
+ + (f" at {rate}" if rate else "")
316
+ + (f" and charged to {card}" if card else "")
317
+ + "."
318
+ )
319
+ render.info(
320
+ "[dim]Every member is emailed as usage reaches 75%, 90% and 95% of the "
321
+ "allowance.[/dim]"
322
+ )
323
+ interactive.confirm("Turn on overages?")
324
+
325
+ try:
326
+ resp = client.put(_OVERAGES_PATH, json={"allowed": bool(allow)})
327
+ except CliError as e:
328
+ raise _translate(e)
329
+
330
+ if allow:
331
+ rate = _rate_words((resp or {}).get("overage_rate_per_1k_credits"))
332
+ render.success(
333
+ "Overages are on."
334
+ + (f" Usage past your plan's credits is billed at {rate}." if rate else "")
335
+ )
336
+ else:
337
+ render.success(
338
+ "Overages are off. When your credits run out, requests stop until credits "
339
+ "are added or the next cycle starts."
340
+ )
341
+ if render.is_machine() and isinstance(resp, dict):
342
+ _render_settings(resp, title="Overages")
@@ -0,0 +1,92 @@
1
+ """`maximem-synap client ...` — inspect your client and manage its team."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+
7
+ from synap.cli import interactive, render
8
+ from synap.cli.api import CliError
9
+ from synap.cli.validate import one_of
10
+
11
+ app = typer.Typer(no_args_is_help=True)
12
+
13
+ _ROLES = ("owner", "admin", "member")
14
+ members_app = typer.Typer(no_args_is_help=True, help="List and manage team members.")
15
+ app.add_typer(members_app, name="members")
16
+
17
+ _MEMBER_COLUMNS = [
18
+ ("email", "EMAIL"),
19
+ ("name", "NAME"),
20
+ ("role", "ROLE"),
21
+ ("membership_state", "STATE"),
22
+ ("user_id", "USER ID"),
23
+ ]
24
+
25
+
26
+ @app.command()
27
+ def get(ctx: typer.Context) -> None:
28
+ """Show the client this profile is bound to."""
29
+ cc = ctx.obj
30
+ client = cc.client().get("/client")
31
+ render.print_detail(client, title=client.get("name"))
32
+
33
+
34
+ @members_app.command(name="list")
35
+ def list_members(ctx: typer.Context) -> None:
36
+ """List members of your client."""
37
+ cc = ctx.obj
38
+ resp = cc.client().get("/client/members")
39
+ render.print_table(resp.get("data", []), _MEMBER_COLUMNS, empty="No members.")
40
+
41
+
42
+ @members_app.command()
43
+ def invite(
44
+ ctx: typer.Context,
45
+ email: str = typer.Option(..., "--email", "-e"),
46
+ role: str = typer.Option("member", "--role", "-r", help="owner | admin | member"),
47
+ ) -> None:
48
+ """Invite a member to your client by email."""
49
+ cc = ctx.obj
50
+ one_of(role, _ROLES, flag="--role")
51
+ member = cc.client().post("/client/members", json={"email": email, "role": role})
52
+ # Say what actually happened. An invite is *pending* until the invitee
53
+ # accepts it in the dashboard — reporting a flat "Invited" read as
54
+ # "they now have access", which they don't.
55
+ if (member or {}).get("membership_state") == "pending":
56
+ render.success(f"Invite sent to [bold]{email}[/bold] as {role}.")
57
+ render.info(
58
+ "[dim]Pending until they accept it in the dashboard. "
59
+ "They'll get an email; if they have no Synap account yet, it is "
60
+ "applied when they sign up with this address.[/dim]"
61
+ )
62
+ else:
63
+ render.success(f"Added [bold]{email}[/bold] as {role}.")
64
+ render.print_detail(member)
65
+
66
+
67
+ @members_app.command()
68
+ def update(
69
+ ctx: typer.Context,
70
+ member_user_id: str = typer.Argument(...),
71
+ role: str = typer.Option(..., "--role", "-r", help="owner | admin | member"),
72
+ ) -> None:
73
+ """Change a member's role."""
74
+ cc = ctx.obj
75
+ one_of(role, _ROLES, flag="--role")
76
+ member = cc.client().patch(f"/client/members/{member_user_id}", json={"role": role})
77
+ render.success("Member role updated.")
78
+ render.print_detail(member)
79
+
80
+
81
+ @members_app.command()
82
+ def remove(
83
+ ctx: typer.Context,
84
+ member_user_id: str = typer.Argument(...),
85
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt (required without a terminal)."),
86
+ ) -> None:
87
+ """Remove a member from your client."""
88
+ cc = ctx.obj
89
+ if not yes:
90
+ interactive.confirm(f"Remove member {member_user_id}?")
91
+ cc.client().delete(f"/client/members/{member_user_id}")
92
+ render.success("Member removed.")
@@ -0,0 +1,56 @@
1
+ """`maximem-synap config ...` — local CLI settings for the active profile."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+
7
+ from synap.cli import render
8
+ from synap.cli.api import CliError
9
+
10
+ app = typer.Typer(no_args_is_help=True)
11
+
12
+ # Only these keys are user-settable via `config set`.
13
+ _SETTABLE = {"api_base"}
14
+
15
+
16
+ @app.command()
17
+ def get(ctx: typer.Context) -> None:
18
+ """Show the active profile's settings (key masked)."""
19
+ cc = ctx.obj
20
+ p = cc.active_profile()
21
+ render.print_detail(
22
+ {
23
+ "profile": cc.profile_name,
24
+ "api_base": p.api_base,
25
+ "client_id": p.client_id,
26
+ "client_name": p.client_name,
27
+ "scopes": p.scopes,
28
+ "api_key_expires_at": p.api_key_expires_at,
29
+ "logged_in": p.is_logged_in(),
30
+ },
31
+ title="CLI config",
32
+ )
33
+
34
+
35
+ @app.command(name="set")
36
+ def set_value(
37
+ ctx: typer.Context,
38
+ key: str = typer.Argument(..., help="Setting to change (e.g. api_base)."),
39
+ value: str = typer.Argument(...),
40
+ ) -> None:
41
+ """Set a profile setting (currently: api_base)."""
42
+ cc = ctx.obj
43
+ if key not in _SETTABLE:
44
+ raise CliError(f"'{key}' is not settable. Allowed: {', '.join(sorted(_SETTABLE))}.")
45
+ profile = cc.active_profile()
46
+ setattr(profile, key, value)
47
+ cc.store.set_profile(cc.profile_name, profile)
48
+ cc.store.save()
49
+ render.success(f"Set {key} = {value} for profile '{cc.profile_name}'.")
50
+
51
+
52
+ @app.command()
53
+ def path(ctx: typer.Context) -> None:
54
+ """Print the path of the CLI config file."""
55
+ cc = ctx.obj
56
+ print(str(cc.store.path))