corethink 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. corethink/__init__.py +17 -0
  2. corethink/__main__.py +3 -0
  3. corethink/_version.py +3 -0
  4. corethink/account.py +470 -0
  5. corethink/cli.py +1058 -0
  6. corethink/client.py +253 -0
  7. corethink/commands/__init__.py +0 -0
  8. corethink/commands/admin.py +703 -0
  9. corethink/commands/api.py +59 -0
  10. corethink/commands/archive.py +433 -0
  11. corethink/commands/auth.py +375 -0
  12. corethink/commands/billing.py +314 -0
  13. corethink/commands/capture.py +564 -0
  14. corethink/commands/connection.py +1266 -0
  15. corethink/commands/endpoint.py +1124 -0
  16. corethink/commands/env.py +1966 -0
  17. corethink/commands/hub.py +269 -0
  18. corethink/commands/library.py +347 -0
  19. corethink/commands/models.py +258 -0
  20. corethink/commands/train.py +2655 -0
  21. corethink/commands/workspace.py +622 -0
  22. corethink/config.py +181 -0
  23. corethink/context.py +46 -0
  24. corethink/env_template.py +117 -0
  25. corethink/environment_http_store.py +96 -0
  26. corethink/experiment_cli.py +2187 -0
  27. corethink/hosted_profiles.py +44 -0
  28. corethink/hosted_rl.py +688 -0
  29. corethink/hosted_rl_archive.py +74 -0
  30. corethink/hosted_rl_attribution.py +44 -0
  31. corethink/hosted_rl_billing.py +103 -0
  32. corethink/hosted_rl_state.py +182 -0
  33. corethink/jobs_cli.py +839 -0
  34. corethink/main.py +204 -0
  35. corethink/output.py +201 -0
  36. corethink/py.typed +0 -0
  37. corethink/rl_cli.py +997 -0
  38. corethink/rl_inspect.py +521 -0
  39. corethink/rl_playground.py +129 -0
  40. corethink/rl_reassessment.py +214 -0
  41. corethink/rl_settings.py +43 -0
  42. corethink/sdk.py +331 -0
  43. corethink/settings.py +162 -0
  44. corethink-1.0.0.dist-info/METADATA +120 -0
  45. corethink-1.0.0.dist-info/RECORD +48 -0
  46. corethink-1.0.0.dist-info/WHEEL +5 -0
  47. corethink-1.0.0.dist-info/entry_points.txt +2 -0
  48. corethink-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,375 @@
1
+ """Signing in and out, who you are, tokens for scripts, and profiles (several Workbenches or accounts)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import platform
7
+ import socket
8
+ import sys
9
+ import time
10
+ import webbrowser
11
+ from typing import Any
12
+
13
+ import typer
14
+ from rich.text import Text
15
+
16
+ from corethink import output as ui
17
+ from corethink._version import __version__
18
+ from corethink.client import ApiError, Client
19
+ from corethink.context import client, state
20
+ from corethink.settings import DEFAULT_URL, Profile, Store, config_path
21
+
22
+ app = typer.Typer(help="Sign in and out, and see who you are.")
23
+ token_app = typer.Typer(help="Tokens for scripts and CI (CORETHINK_TOKEN).", no_args_is_help=True)
24
+ profile_app = typer.Typer(help="Profiles: more than one account or Workbench.", no_args_is_help=True)
25
+
26
+
27
+ def _client_name() -> str:
28
+ host = socket.gethostname().split(".")[0] or "terminal"
29
+ return f"{host} · corethink {__version__} · {platform.system()}"
30
+
31
+
32
+ def login(
33
+ no_browser: bool = typer.Option(
34
+ False,
35
+ "--no-browser",
36
+ help="Print the link instead of opening a browser (for SSH and servers).",
37
+ ),
38
+ with_token: bool = typer.Option(
39
+ False,
40
+ "--with-token",
41
+ help="Read a token from stdin instead (a token made in Settings or with `corethink token create`).",
42
+ ),
43
+ ) -> None:
44
+ """Sign in through your browser.
45
+
46
+ Shows a code, opens the Workbench, and waits while you approve it there. The CLI then acts as you, with your roles
47
+ in your workspaces. Use --profile and --url to sign in to another account or Workbench.
48
+ """
49
+ resolved = state.settings()
50
+ url = resolved.url
51
+ if with_token:
52
+ token = sys.stdin.readline().strip() if not sys.stdin.isatty() else typer.prompt("Token", hide_input=True)
53
+ if not token.startswith("ctcli_"):
54
+ ui.error("That is not a CoreThink CLI token (they start with ctcli_).")
55
+ raise typer.Exit(2)
56
+ with Client(url, token, transport=state.transport) as signed: # type: ignore[arg-type]
57
+ me = signed.get("/api/v1/auth/me")
58
+ _save(resolved.profile, url, token, None, me.get("email"), None)
59
+ ui.success(f"Signed in as {me.get('email')} ({url}).")
60
+ return
61
+
62
+ anonymous = Client(url, None, transport=state.transport) # type: ignore[arg-type]
63
+ try:
64
+ started = anonymous.post("/api/v1/cli/device", {"client": _client_name()})
65
+ code = started["user_code"]
66
+ link = started.get("verification_uri_complete") or started["verification_uri"]
67
+ interval = float(started.get("interval") or 3)
68
+ deadline = time.monotonic() + float(started.get("expires_in") or 600)
69
+
70
+ ui.err.print()
71
+ ui.err.print(Text(" Your code: ", style="bold") + Text(code, style="bold cyan"))
72
+ ui.err.print()
73
+ opened = False
74
+ if not no_browser and not os.environ.get("SSH_CONNECTION"):
75
+ try:
76
+ opened = webbrowser.open(link)
77
+ except Exception:
78
+ opened = False
79
+ ui.err.print(
80
+ f" {'Opened' if opened else 'Open'} {link}\n and approve the sign-in (check that it shows the same code).\n"
81
+ )
82
+ with ui.err.status("Waiting for approval in the browser…", spinner="dots"):
83
+ while True:
84
+ if time.monotonic() > deadline:
85
+ ui.error("The sign-in timed out. Run `corethink login` again.")
86
+ raise typer.Exit(1)
87
+ time.sleep(interval)
88
+ try:
89
+ done = anonymous.post("/api/v1/cli/token", {"device_code": started["device_code"]}, retry=False)
90
+ break
91
+ except ApiError as problem:
92
+ if problem.code == "authorization_pending":
93
+ continue
94
+ if problem.code == "slow_down":
95
+ interval += 2
96
+ continue
97
+ if problem.code == "access_denied":
98
+ ui.error("The sign-in was denied in the browser.")
99
+ raise typer.Exit(1) from None
100
+ raise
101
+ finally:
102
+ anonymous.close()
103
+
104
+ store = Store.load()
105
+ previous = store.profile(resolved.profile)
106
+ _save(
107
+ resolved.profile,
108
+ url,
109
+ done["token"],
110
+ done.get("token_id"),
111
+ done.get("email"),
112
+ done.get("expires_at"),
113
+ )
114
+ # the token this profile held before is no longer needed: revoke it (quietly; it may have expired already)
115
+ if previous.token and previous.token != done["token"] and previous.url == url:
116
+ try:
117
+ with Client(url, previous.token, transport=state.transport) as old: # type: ignore[arg-type]
118
+ old.delete("/api/v1/cli/tokens/current")
119
+ except ApiError:
120
+ pass
121
+ ui.success(f"Signed in as {done.get('email')}.")
122
+ _hint_workspace()
123
+
124
+
125
+ def _save(
126
+ profile: str,
127
+ url: str,
128
+ token: str,
129
+ token_id: str | None,
130
+ email: str | None,
131
+ expires_at: str | None,
132
+ ) -> None:
133
+ store = Store.load()
134
+ stored = store.profile(profile)
135
+ stored.url = url
136
+ stored.token = token
137
+ stored.token_id = token_id
138
+ stored.email = email
139
+ stored.expires_at = expires_at
140
+ store.put(stored)
141
+ if store.current not in store.profiles:
142
+ store.current = profile
143
+ store.save()
144
+ state.reset()
145
+
146
+
147
+ def _hint_workspace() -> None:
148
+ try:
149
+ me = client().get("/api/v1/auth/me")
150
+ except ApiError:
151
+ return
152
+ space = me.get("space") or {}
153
+ if space:
154
+ ui.info(
155
+ f"Working in {space.get('name')} ({space.get('kind')}, {space.get('role')}). Change it with `corethink workspace use`."
156
+ )
157
+
158
+
159
+ def logout(
160
+ keep: bool = typer.Option(False, "--keep-token", help="Forget the token here without revoking it."),
161
+ ) -> None:
162
+ """Sign this profile out and revoke its token."""
163
+ store = Store.load()
164
+ resolved = state.settings()
165
+ profile = store.profile(resolved.profile)
166
+ if not profile.token:
167
+ if resolved.token_source == "env":
168
+ ui.warn("Signed in through CORETHINK_TOKEN: unset it to sign out (revoke it in Settings).")
169
+ else:
170
+ ui.info("Not signed in.")
171
+ return
172
+ if not keep:
173
+ try:
174
+ with Client(profile.url, profile.token, transport=state.transport) as signed: # type: ignore[arg-type]
175
+ signed.delete("/api/v1/cli/tokens/current")
176
+ except ApiError as problem:
177
+ if problem.status not in (401, 404):
178
+ ui.warn(f"The token could not be revoked ({problem.message}); it is forgotten here anyway.")
179
+ profile.token = profile.token_id = profile.expires_at = None
180
+ profile.email = None
181
+ store.put(profile)
182
+ store.save()
183
+ ui.success("Signed out.")
184
+
185
+
186
+ def whoami() -> None:
187
+ """Who the CLI is signed in as, the open workspace and its credit."""
188
+ resolved = state.settings()
189
+ me = client().get("/api/v1/auth/me")
190
+ space = me.get("space") or {}
191
+ credit = me.get("credit") or {}
192
+ data = {
193
+ **me,
194
+ "url": resolved.url,
195
+ "profile": resolved.profile,
196
+ "token_source": resolved.token_source,
197
+ }
198
+
199
+ def human() -> None:
200
+ ui.fields(
201
+ [
202
+ ("Signed in as", me.get("email")),
203
+ ("Workbench", resolved.url),
204
+ (
205
+ "Workspace",
206
+ f"{space.get('name')} · {space.get('kind')} · {space.get('role')}"
207
+ if space
208
+ else me.get("workspace"),
209
+ ),
210
+ (
211
+ "Credit available",
212
+ ui.usd(credit.get("availableUsd")) if space.get("billed", True) else "paid by CoreThink",
213
+ ),
214
+ ("Super admin", "yes" if me.get("superAdmin") else None),
215
+ (
216
+ "Email confirmed",
217
+ "yes" if me.get("verified") else "no: open the link we emailed you",
218
+ ),
219
+ ("Profile", resolved.profile),
220
+ (
221
+ "Token from",
222
+ "CORETHINK_TOKEN" if resolved.token_source == "env" else str(config_path()),
223
+ ),
224
+ ]
225
+ )
226
+
227
+ ui.emit(data, human)
228
+
229
+
230
+ # ---- tokens ------------------------------------------------------------------------------------------------------------
231
+
232
+
233
+ @token_app.command("list")
234
+ def token_list() -> None:
235
+ """Your CLI sign-ins and script tokens (never their secrets)."""
236
+ tokens = client().get("/api/v1/cli/tokens").get("tokens", [])
237
+
238
+ def human() -> None:
239
+ ui.table(
240
+ tokens,
241
+ [
242
+ (
243
+ "ID",
244
+ lambda t: ui.short_id(t["id"], 10) + (" (this one)" if t.get("current") else ""),
245
+ ),
246
+ ("Name", "name"),
247
+ ("Kind", lambda t: "script" if t.get("via") == "manual" else "sign-in"),
248
+ ("Token", "masked"),
249
+ ("Last used", lambda t: ui.ago(t.get("last_used_at"))),
250
+ ("Expires", lambda t: ui.when(t.get("expires_at"))),
251
+ ],
252
+ empty="No CLI sign-ins or tokens.",
253
+ )
254
+
255
+ ui.emit(tokens, human)
256
+
257
+
258
+ @token_app.command("create")
259
+ def token_create(
260
+ name: str = typer.Argument(..., help="What it is for, e.g. github-actions."),
261
+ days: int = typer.Option(90, "--days", min=1, max=365, help="How long it lasts."),
262
+ ) -> None:
263
+ """Make a token for a script or CI. It is printed once: store it as CORETHINK_TOKEN."""
264
+ made = client().post("/api/v1/cli/tokens", {"name": name, "days": days})
265
+
266
+ def human() -> None:
267
+ ui.out.print(made["token"])
268
+ ui.info(f"Shown once. Expires {ui.when(made.get('expires_at'))}. Use it as CORETHINK_TOKEN.")
269
+
270
+ ui.emit(made, human)
271
+
272
+
273
+ @token_app.command("revoke")
274
+ def token_revoke(
275
+ token_id: str = typer.Argument(..., help="The token's ID from `corethink token list` (the first characters do)."),
276
+ yes: bool = typer.Option(False, "--yes", "-y", help="Do not ask."),
277
+ ) -> None:
278
+ """Revoke a token: anything using it is signed out within a minute."""
279
+ tokens = client().get("/api/v1/cli/tokens").get("tokens", [])
280
+ matches = [t for t in tokens if t["id"].startswith(token_id)]
281
+ if len(matches) != 1:
282
+ ui.error("No token has that ID." if not matches else "More than one token starts with that; give more of it.")
283
+ raise typer.Exit(5 if not matches else 2)
284
+ target = matches[0]
285
+ ui.confirm(f"Revoke {target['name']} ({target['masked']})?", yes=yes)
286
+ client().delete(f"/api/v1/cli/tokens/{target['id']}")
287
+ ui.emit({"revoked": target["id"]}, lambda: ui.success(f"Revoked {target['name']}."))
288
+
289
+
290
+ # ---- profiles ----------------------------------------------------------------------------------------------------------
291
+
292
+
293
+ @profile_app.command("list")
294
+ def profile_list() -> None:
295
+ """Your profiles, and which one is in use."""
296
+ store = Store.load()
297
+ current = state.profile or os.environ.get("CORETHINK_PROFILE") or store.current
298
+ rows: list[dict[str, Any]] = [
299
+ {
300
+ "name": p.name,
301
+ "url": p.url,
302
+ "email": p.email,
303
+ "signed_in": bool(p.token),
304
+ "current": p.name == current,
305
+ }
306
+ for p in store.profiles.values()
307
+ ]
308
+
309
+ def human() -> None:
310
+ ui.table(
311
+ rows,
312
+ [
313
+ ("", lambda r: "*" if r["current"] else ""),
314
+ ("Profile", "name"),
315
+ ("Signed in as", lambda r: r["email"] or ("yes" if r["signed_in"] else "no")),
316
+ ("Workbench", "url"),
317
+ ],
318
+ empty="No profiles yet: `corethink login` makes one.",
319
+ )
320
+
321
+ ui.emit(rows, human)
322
+
323
+
324
+ @profile_app.command("use")
325
+ def profile_use(name: str = typer.Argument(..., help="The profile to use from now on.")) -> None:
326
+ """Switch the profile commands use by default."""
327
+ store = Store.load()
328
+ if name not in store.profiles:
329
+ store.put(Profile(name=name, url=state.url or DEFAULT_URL))
330
+ store.current = name
331
+ store.save()
332
+ ui.success(f"Using profile {name}.")
333
+
334
+
335
+ @profile_app.command("set-url")
336
+ def profile_set_url(
337
+ url: str = typer.Argument(..., help="The Workbench address, e.g. https://workbench.corethink.ai"),
338
+ ) -> None:
339
+ """Point this profile at another Workbench."""
340
+ if not url.startswith(("https://", "http://localhost", "http://127.0.0.1")):
341
+ ui.error("Use an https:// address.")
342
+ raise typer.Exit(2)
343
+ store = Store.load()
344
+ resolved = state.settings()
345
+ profile = store.profile(resolved.profile)
346
+ profile.url = url.rstrip("/")
347
+ store.put(profile)
348
+ store.save()
349
+ ui.success(f"Profile {profile.name} now uses {profile.url}.")
350
+
351
+
352
+ @profile_app.command("remove")
353
+ def profile_remove(
354
+ name: str = typer.Argument(...),
355
+ yes: bool = typer.Option(False, "--yes", "-y", help="Do not ask."),
356
+ ) -> None:
357
+ """Forget a profile (its token is not revoked: `corethink logout` first for that)."""
358
+ store = Store.load()
359
+ if name not in store.profiles:
360
+ ui.error(f"No profile {name}.")
361
+ raise typer.Exit(5)
362
+ ui.confirm(f"Forget profile {name}?", yes=yes)
363
+ del store.profiles[name]
364
+ if store.current == name:
365
+ store.current = next(iter(store.profiles), "default")
366
+ store.save()
367
+ ui.success(f"Forgot {name}.")
368
+
369
+
370
+ def register(root: typer.Typer) -> None:
371
+ root.command(rich_help_panel="Account")(login)
372
+ root.command(rich_help_panel="Account")(logout)
373
+ root.command(rich_help_panel="Account")(whoami)
374
+ root.add_typer(token_app, name="token", rich_help_panel="Account")
375
+ root.add_typer(profile_app, name="profile", rich_help_panel="Account")
@@ -0,0 +1,314 @@
1
+ """`corethink billing`: the open workspace's credit and spend, card payments, and buying credit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import webbrowser
7
+ from datetime import datetime, timezone
8
+ from typing import Any
9
+
10
+ import typer
11
+
12
+ from corethink import output as ui
13
+ from corethink.commands.workspace import entry_amount, entry_type
14
+ from corethink.context import client
15
+
16
+ app = typer.Typer(help="Credit, spend and card payments for the open workspace.", no_args_is_help=True)
17
+
18
+ PURCHASE_STATUS = {
19
+ "open": "not completed",
20
+ "processing": "processing",
21
+ "paid": "paid",
22
+ "failed": "failed",
23
+ "expired": "expired",
24
+ "unapplied": "being checked",
25
+ "review": "being checked",
26
+ }
27
+
28
+
29
+ def _local(value: Any) -> datetime | None:
30
+ if not value:
31
+ return None
32
+ try:
33
+ moment = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
34
+ except ValueError:
35
+ return None
36
+ if moment.tzinfo is None:
37
+ moment = moment.replace(tzinfo=timezone.utc)
38
+ return moment.astimezone()
39
+
40
+
41
+ def _month(value: Any) -> str | None:
42
+ moment = _local(value)
43
+ return moment.strftime("%Y-%m") if moment else None
44
+
45
+
46
+ def _is_charge(entry: dict[str, Any]) -> bool:
47
+ """Charged for work (credit moved to a team workspace leaves the balance but is not a charge)."""
48
+ return entry.get("kind") in ("charge", "debit") and entry.get("source") != "transfer"
49
+
50
+
51
+ def summarize(entries: list[dict[str, Any]]) -> dict[str, Any]:
52
+ """What the ledger entries add up to, as the console's Usage & billing page reads them."""
53
+
54
+ def total(rows: list[dict[str, Any]]) -> float:
55
+ return round(sum(float(r.get("amountUsd") or 0) for r in rows), 6)
56
+
57
+ spent = [e for e in entries if _is_charge(e)]
58
+ captures = [e for e in spent if e.get("kind") == "charge" and str(e.get("jobId") or "").startswith("capture-")]
59
+ training = [
60
+ e
61
+ for e in spent
62
+ if e.get("kind") == "charge" and e.get("jobId") and not str(e.get("jobId")).startswith("capture-")
63
+ ]
64
+ reviews = [e for e in spent if e.get("kind") == "debit"]
65
+ return {
66
+ "spentUsd": total(spent),
67
+ "charges": len(spent),
68
+ "training": {"usd": total(training), "runs": len({e.get("jobId") for e in training})},
69
+ "captures": {"usd": total(captures), "count": len({e.get("jobId") for e in captures})},
70
+ "reviews": {"usd": total(reviews), "count": len(reviews)},
71
+ "addedUsd": total([e for e in entries if e.get("kind") in ("grant", "credit")]),
72
+ }
73
+
74
+
75
+ def _open(url: str, no_browser: bool) -> bool:
76
+ if no_browser or os.environ.get("SSH_CONNECTION"):
77
+ return False
78
+ try:
79
+ return bool(webbrowser.open(url))
80
+ except Exception:
81
+ return False
82
+
83
+
84
+ def _amount(text: str) -> float:
85
+ try:
86
+ value = round(float(text.strip().lstrip("$").replace(",", "")), 2)
87
+ except ValueError:
88
+ value = 0.0
89
+ if not value > 0:
90
+ ui.error("Give an amount in US dollars, e.g. 25 or 12.50.")
91
+ raise typer.Exit(2)
92
+ return value
93
+
94
+
95
+ @app.command("show")
96
+ def show() -> None:
97
+ """Credit (balance, held, available), this month's spend by type, and credit by where it came from."""
98
+ billing = client().get("/api/v1/billing") or {}
99
+ month = datetime.now().astimezone().strftime("%Y-%m")
100
+ ledger = billing.get("ledger") or []
101
+ bill = summarize([e for e in ledger if _month(e.get("at")) == month])
102
+ space = billing.get("space") or {}
103
+ credit = billing.get("credit") or {}
104
+ team = space.get("kind") == "team"
105
+ unbilled = space.get("billed") is False
106
+ manager = space.get("role") in ("owner", "admin") or not team
107
+ breakdown = billing.get("breakdown")
108
+
109
+ def human() -> None:
110
+ ui.fields(
111
+ [
112
+ (
113
+ "Workspace",
114
+ f"{space.get('name')} ({space.get('kind')})" if space else billing.get("workspace"),
115
+ ),
116
+ (
117
+ "Plan",
118
+ "Credits · CoreThink pays for this workspace's runs"
119
+ if unbilled
120
+ else "Credits · shared, prepaid"
121
+ if team
122
+ else "Credits · prepaid, no monthly fee",
123
+ ),
124
+ ("Balance", ui.usd(credit.get("balanceUsd"))),
125
+ ("Held by running work", ui.usd(credit.get("heldUsd"))),
126
+ ("Available", ui.usd(credit.get("availableUsd"))),
127
+ ],
128
+ title="Credit",
129
+ )
130
+ ui.out.print()
131
+ lines: list[tuple[str, Any]] = [
132
+ (f"Training runs · {bill['training']['runs']}", ui.usd(bill["training"]["usd"])),
133
+ (
134
+ f"Captures of live traffic · {bill['captures']['count']}",
135
+ ui.usd(bill["captures"]["usd"]),
136
+ ),
137
+ (
138
+ f"Reviews by a judge model · {bill['reviews']['count']}",
139
+ ui.usd(bill["reviews"]["usd"]),
140
+ ),
141
+ ("Program calls", "not billed yet"),
142
+ ]
143
+ if bill["addedUsd"] > 0:
144
+ lines.append(("Credit received", "+" + ui.usd(bill["addedUsd"])))
145
+ lines.append(("Total, month to date", ui.usd(bill["spentUsd"])))
146
+ ui.fields(lines, title=f"This month so far ({month})")
147
+ if breakdown:
148
+ ui.out.print()
149
+ rows: list[tuple[str, Any]] = [
150
+ (label, ui.usd(breakdown.get(key)))
151
+ for label, key in (
152
+ ("Welcome credit", "welcomeUsd"),
153
+ ("Promotional credit", "promotionalUsd"),
154
+ ("Purchased credit", "purchasedUsd"),
155
+ ("Moved in by members", "movedInUsd"),
156
+ )
157
+ if float(breakdown.get(key) or 0) > 0
158
+ ]
159
+ if not rows:
160
+ rows.append(("No credit added yet", ui.usd(0)))
161
+ if float(breakdown.get("movedOutUsd") or 0) > 0:
162
+ rows.append(("Moved to team workspaces", "−" + ui.usd(breakdown.get("movedOutUsd"))))
163
+ spent = float(breakdown.get("spentUsd") or 0)
164
+ rows.append(("Spent", "−" + ui.usd(spent) if spent > 0 else ui.usd(0)))
165
+ rows.append(("Balance", ui.usd(breakdown.get("balanceUsd"))))
166
+ ui.fields(rows, title="Credit by type")
167
+ if not billing.get("verified") and not team:
168
+ ui.warn(f"Confirm your email to receive your {ui.usd(billing.get('signupCreditUsd'))} of free credit.")
169
+ if team and not manager:
170
+ ui.info(f"{space.get('name')}'s shared credit: only admins and owners can buy it or see charges.")
171
+ if len(ledger) >= 100:
172
+ ui.info("Only the latest 100 entries are read; older ones are not counted here.")
173
+
174
+ ui.emit({**billing, "monthToDate": {"month": month, **bill}}, human)
175
+
176
+
177
+ @app.command("history")
178
+ def history(
179
+ month: str = typer.Option(None, "--month", "-m", help="Only this month, as YYYY-MM."),
180
+ limit: int = typer.Option(50, "--limit", "-n", min=1, help="Show at most this many entries."),
181
+ ) -> None:
182
+ """The open workspace's credit and charges, newest first.
183
+
184
+ Example: corethink billing history --month 2026-10
185
+ """
186
+ ledger = (client().get("/api/v1/billing") or {}).get("ledger") or []
187
+ if month:
188
+ try:
189
+ datetime.strptime(month, "%Y-%m")
190
+ except ValueError:
191
+ ui.error("Give the month as YYYY-MM, e.g. 2026-10.")
192
+ raise typer.Exit(2) from None
193
+ ledger = [e for e in ledger if _month(e.get("at")) == month]
194
+ shown = ledger[:limit]
195
+
196
+ def human() -> None:
197
+ ui.table(
198
+ shown,
199
+ [
200
+ ("When", lambda e: ui.when(e.get("at"))),
201
+ ("Type", entry_type),
202
+ ("Note", "note"),
203
+ ("Amount", entry_amount),
204
+ ],
205
+ empty="No credit or charges yet.",
206
+ )
207
+
208
+ ui.emit(shown, human)
209
+
210
+
211
+ @app.command("payments")
212
+ def payments() -> None:
213
+ """Card payments for the open workspace, and the amounts you can buy."""
214
+ cards = client().get("/api/v1/billing/stripe") or {}
215
+ purchases = cards.get("purchases") or []
216
+
217
+ def human() -> None:
218
+ if not cards.get("enabled"):
219
+ ui.info("Card payments are not set up on this Workbench.")
220
+ return
221
+ ui.fields(
222
+ [
223
+ (
224
+ "Card payments",
225
+ "opening shortly" if cards.get("preview") else "test mode" if cards.get("testMode") else "on",
226
+ ),
227
+ (
228
+ "Amounts",
229
+ f"{ui.usd(cards.get('minUsd'))} to {ui.usd(cards.get('maxUsd'))}"
230
+ if cards.get("minUsd") is not None
231
+ else None,
232
+ ),
233
+ (
234
+ "You can buy",
235
+ "yes" if cards.get("canBuy") else "no (admins and owners buy a team's credit)",
236
+ ),
237
+ (
238
+ "Invoices and receipts",
239
+ "`corethink billing portal`" if cards.get("portal") else None,
240
+ ),
241
+ ]
242
+ )
243
+ if cards.get("canBuy"):
244
+ ui.out.print()
245
+ ui.table(
246
+ purchases,
247
+ [
248
+ ("When", lambda p: ui.when(p.get("at"))),
249
+ ("Amount", lambda p: ui.usd(p.get("amountUsd"))),
250
+ ("Status", lambda p: PURCHASE_STATUS.get(p.get("status", ""), p.get("status"))),
251
+ ("By", "email"),
252
+ ],
253
+ empty="No card payments yet.",
254
+ )
255
+
256
+ ui.emit(cards, human)
257
+
258
+
259
+ @app.command("buy")
260
+ def buy(
261
+ usd: str = typer.Argument(..., metavar="USD", help="How many US dollars of credit, e.g. 25."),
262
+ no_browser: bool = typer.Option(False, "--no-browser", help="Print the checkout link without opening a browser."),
263
+ ) -> None:
264
+ """Buy credit by card for the open workspace: opens Stripe's checkout page.
265
+
266
+ The credit shows once the payment is confirmed. Example: corethink billing buy 50
267
+ """
268
+ amount = _amount(usd)
269
+ cards = client().get("/api/v1/billing/stripe") or {}
270
+ if not cards.get("enabled"):
271
+ ui.error("Card payments are not set up on this Workbench.")
272
+ raise typer.Exit(5)
273
+ if cards.get("preview"):
274
+ ui.error("Card payments open shortly: the checkout is being connected.")
275
+ raise typer.Exit(7)
276
+ if cards.get("canBuy") is False:
277
+ ui.error("Only admins and owners of this workspace can buy its credit.")
278
+ raise typer.Exit(4)
279
+ low, high = cards.get("minUsd"), cards.get("maxUsd")
280
+ if low is not None and high is not None and not float(low) <= amount <= float(high):
281
+ ui.error(f"Choose an amount from {ui.usd(low)} to {ui.usd(high)}.")
282
+ raise typer.Exit(2)
283
+ started = client().post("/api/v1/billing/checkout", {"usd": amount}, retry=False) or {}
284
+ url = str(started.get("url") or "")
285
+
286
+ def human() -> None:
287
+ ui.out.print(url, soft_wrap=True, markup=False)
288
+ opened = _open(url, no_browser)
289
+ ui.info(
290
+ f"{'Opened' if opened else 'Open'} the checkout above to pay {ui.usd(amount)}"
291
+ f"{' (test mode)' if cards.get('testMode') else ''}. The credit shows once the payment is confirmed."
292
+ )
293
+
294
+ ui.emit({**started, "usd": amount}, human)
295
+
296
+
297
+ @app.command("portal")
298
+ def portal(
299
+ no_browser: bool = typer.Option(False, "--no-browser", help="Print the link without opening a browser."),
300
+ ) -> None:
301
+ """Open Stripe's billing portal: invoices, receipts and payment details."""
302
+ answer = client().post("/api/v1/billing/portal", retry=False) or {}
303
+ url = str(answer.get("url") or "")
304
+
305
+ def human() -> None:
306
+ ui.out.print(url, soft_wrap=True, markup=False)
307
+ opened = _open(url, no_browser)
308
+ ui.info("Opened the billing portal." if opened else "Open the link above for invoices and receipts.")
309
+
310
+ ui.emit(answer, human)
311
+
312
+
313
+ def register(root: typer.Typer) -> None:
314
+ root.add_typer(app, name="billing", rich_help_panel="Account")