spooling 0.2.14__tar.gz → 0.2.16__tar.gz

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 (80) hide show
  1. {spooling-0.2.14/spooling.egg-info → spooling-0.2.16}/PKG-INFO +15 -9
  2. {spooling-0.2.14 → spooling-0.2.16}/README.md +14 -8
  3. {spooling-0.2.14 → spooling-0.2.16}/pyproject.toml +1 -1
  4. {spooling-0.2.14 → spooling-0.2.16}/spooling/cli.py +10 -0
  5. {spooling-0.2.14 → spooling-0.2.16}/spooling/cloud.py +106 -6
  6. spooling-0.2.16/spooling/device_login.py +88 -0
  7. {spooling-0.2.14 → spooling-0.2.16/spooling.egg-info}/PKG-INFO +15 -9
  8. {spooling-0.2.14 → spooling-0.2.16}/spooling.egg-info/SOURCES.txt +3 -0
  9. spooling-0.2.16/tests/test_cloud_teams.py +118 -0
  10. spooling-0.2.16/tests/test_device_login.py +155 -0
  11. {spooling-0.2.14 → spooling-0.2.16}/tests/test_docs.py +9 -0
  12. {spooling-0.2.14 → spooling-0.2.16}/LICENSE +0 -0
  13. {spooling-0.2.14 → spooling-0.2.16}/setup.cfg +0 -0
  14. {spooling-0.2.14 → spooling-0.2.16}/spooling/__init__.py +0 -0
  15. {spooling-0.2.14 → spooling-0.2.16}/spooling/agent.py +0 -0
  16. {spooling-0.2.14 → spooling-0.2.16}/spooling/classifiers.py +0 -0
  17. {spooling-0.2.14 → spooling-0.2.16}/spooling/config.py +0 -0
  18. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/__init__.py +0 -0
  19. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/base.py +0 -0
  20. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/bigquery.py +0 -0
  21. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/clickhouse.py +0 -0
  22. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/factory.py +0 -0
  23. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/mongodb.py +0 -0
  24. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/mysql.py +0 -0
  25. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/postgresql.py +0 -0
  26. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/rest/__init__.py +0 -0
  27. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/rest/base.py +0 -0
  28. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/rest/shopify_connectors.py +0 -0
  29. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/snowflake.py +0 -0
  30. {spooling-0.2.14 → spooling-0.2.16}/spooling/connectors/types.py +0 -0
  31. {spooling-0.2.14 → spooling-0.2.16}/spooling/db.py +0 -0
  32. {spooling-0.2.14 → spooling-0.2.16}/spooling/embeddings.py +0 -0
  33. {spooling-0.2.14 → spooling-0.2.16}/spooling/evals.py +0 -0
  34. {spooling-0.2.14 → spooling-0.2.16}/spooling/experiments.py +0 -0
  35. {spooling-0.2.14 → spooling-0.2.16}/spooling/ingest.py +0 -0
  36. {spooling-0.2.14 → spooling-0.2.16}/spooling/insights.py +0 -0
  37. {spooling-0.2.14 → spooling-0.2.16}/spooling/mcp_server.py +0 -0
  38. {spooling-0.2.14 → spooling-0.2.16}/spooling/optimize.py +0 -0
  39. {spooling-0.2.14 → spooling-0.2.16}/spooling/parser.py +0 -0
  40. {spooling-0.2.14 → spooling-0.2.16}/spooling/pricing.py +0 -0
  41. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/__init__.py +0 -0
  42. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/antigravity.py +0 -0
  43. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/base.py +0 -0
  44. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/claude_code.py +0 -0
  45. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/codex.py +0 -0
  46. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/copilot.py +0 -0
  47. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/cortex_code.py +0 -0
  48. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/cursor.py +0 -0
  49. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/gemini.py +0 -0
  50. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/github.py +0 -0
  51. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/gitlab.py +0 -0
  52. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/kiro.py +0 -0
  53. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/opencode.py +0 -0
  54. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/session_file.py +0 -0
  55. {spooling-0.2.14 → spooling-0.2.16}/spooling/providers/windsurf.py +0 -0
  56. {spooling-0.2.14 → spooling-0.2.16}/spooling/redact.py +0 -0
  57. {spooling-0.2.14 → spooling-0.2.16}/spooling/remote_otel.py +0 -0
  58. {spooling-0.2.14 → spooling-0.2.16}/spooling/schema.py +0 -0
  59. {spooling-0.2.14 → spooling-0.2.16}/spooling/sdk.py +0 -0
  60. {spooling-0.2.14 → spooling-0.2.16}/spooling/search.py +0 -0
  61. {spooling-0.2.14 → spooling-0.2.16}/spooling/server.py +0 -0
  62. {spooling-0.2.14 → spooling-0.2.16}/spooling/sessions.py +0 -0
  63. {spooling-0.2.14 → spooling-0.2.16}/spooling/stats.py +0 -0
  64. {spooling-0.2.14 → spooling-0.2.16}/spooling/subscription_pricing.py +0 -0
  65. {spooling-0.2.14 → spooling-0.2.16}/spooling/tracing.py +0 -0
  66. {spooling-0.2.14 → spooling-0.2.16}/spooling/tunnel.py +0 -0
  67. {spooling-0.2.14 → spooling-0.2.16}/spooling/tunnel_auth.py +0 -0
  68. {spooling-0.2.14 → spooling-0.2.16}/spooling/watcher.py +0 -0
  69. {spooling-0.2.14 → spooling-0.2.16}/spooling.egg-info/dependency_links.txt +0 -0
  70. {spooling-0.2.14 → spooling-0.2.16}/spooling.egg-info/entry_points.txt +0 -0
  71. {spooling-0.2.14 → spooling-0.2.16}/spooling.egg-info/requires.txt +0 -0
  72. {spooling-0.2.14 → spooling-0.2.16}/spooling.egg-info/top_level.txt +0 -0
  73. {spooling-0.2.14 → spooling-0.2.16}/tests/test_agent_spans.py +0 -0
  74. {spooling-0.2.14 → spooling-0.2.16}/tests/test_claude_code_provider.py +0 -0
  75. {spooling-0.2.14 → spooling-0.2.16}/tests/test_cloud_errors.py +0 -0
  76. {spooling-0.2.14 → spooling-0.2.16}/tests/test_insights.py +0 -0
  77. {spooling-0.2.14 → spooling-0.2.16}/tests/test_mcp_auth_middleware.py +0 -0
  78. {spooling-0.2.14 → spooling-0.2.16}/tests/test_session_ids.py +0 -0
  79. {spooling-0.2.14 → spooling-0.2.16}/tests/test_storage_optimizations.py +0 -0
  80. {spooling-0.2.14 → spooling-0.2.16}/tests/test_tunnel_auth.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spooling
3
- Version: 0.2.14
3
+ Version: 0.2.16
4
4
  Summary: Local session tracker and semantic search for AI coding assistants
5
5
  Author: Parsed Analytics, Inc.
6
6
  License: MIT
@@ -390,16 +390,19 @@ the CLI ships with a `spooling cloud` subcommand.
390
390
 
391
391
  ### One-time setup
392
392
 
393
- 1. Mint an API key in the GUI at `app.spooling.ai/settings/api-keys`
394
- (looks like `sk_live_...`).
395
- 2. Save it locally:
393
+ 1. Sign in from the terminal:
396
394
 
397
395
  ```bash
398
- spooling cloud login --key sk_live_...
396
+ spooling login
399
397
  ```
400
398
 
401
- The key is stored at `~/.config/spooling/cloud.json` with `0600` perms.
402
- You can override the API base with `--api-url` or the
399
+ This opens your browser with a short code (for example `BCDF-GHJK`). Check the code, pick the workspace the
400
+ sessions should go to, and click Approve. The API key is generated on your machine and only its hash is sent to
401
+ Spooling, so there is nothing to copy and paste. It is stored at `~/.config/spooling/cloud.json` with `0600`
402
+ perms. Use `--no-browser` to just print the link (SSH sessions, containers).
403
+
404
+ Prefer to manage keys yourself? Mint one at `app.spooling.ai/settings` and run
405
+ `spooling cloud login --key sk_live_...`. You can override the API base with `--api-url` or the
403
406
  `SPOOLING_CLOUD_URL` env var (default: `https://api.spooling.ai`).
404
407
 
405
408
  ### Push once
@@ -420,11 +423,14 @@ spooling push --dry-run # show what would be pushed
420
423
  **Which team gets the sessions** is decided by the API key you are logged in with. Each key belongs to one workspace (personal or a team), and `spooling push` sends to that workspace. Mint a key for the team in the app, then log in with it:
421
424
 
422
425
  ```bash
426
+ spooling cloud teams # every workspace (personal + teams) your account belongs to
427
+ spooling cloud whoami # the account and workspace this CLI pushes to
423
428
  spooling cloud login --key sk_<team-key> # replaces the stored key; later pushes go to this team
424
- spooling cloud status # session/cost totals of the workspace this key belongs to
425
429
  ```
426
430
 
427
- To push to a different team, log in with that team's key. Only one key is stored at a time. `cloud status` doesn't print the workspace name, so compare its totals with what the team shows in the app.
431
+ `spooling cloud teams` marks the workspace your current key pushes to with `<- this key`, and shows your role, the number of members and the plan for each. `spooling cloud status` also prints the workspace name now. `teams` and `whoami` take `--json` for scripting.
432
+
433
+ To push to a different team, log in with that team's key. Only one key is stored at a time, so check `spooling cloud whoami` before a push if you work with several teams. These commands need a server that supports `/v1/me`; against an older one they say so and `spooling cloud status` still works.
428
434
 
429
435
  **Which sessions go up.** With no filters, `spooling push` sends the most recent `--limit` sessions from every project on the machine. Use these to send only some of them. Filters combine with AND:
430
436
 
@@ -354,16 +354,19 @@ the CLI ships with a `spooling cloud` subcommand.
354
354
 
355
355
  ### One-time setup
356
356
 
357
- 1. Mint an API key in the GUI at `app.spooling.ai/settings/api-keys`
358
- (looks like `sk_live_...`).
359
- 2. Save it locally:
357
+ 1. Sign in from the terminal:
360
358
 
361
359
  ```bash
362
- spooling cloud login --key sk_live_...
360
+ spooling login
363
361
  ```
364
362
 
365
- The key is stored at `~/.config/spooling/cloud.json` with `0600` perms.
366
- You can override the API base with `--api-url` or the
363
+ This opens your browser with a short code (for example `BCDF-GHJK`). Check the code, pick the workspace the
364
+ sessions should go to, and click Approve. The API key is generated on your machine and only its hash is sent to
365
+ Spooling, so there is nothing to copy and paste. It is stored at `~/.config/spooling/cloud.json` with `0600`
366
+ perms. Use `--no-browser` to just print the link (SSH sessions, containers).
367
+
368
+ Prefer to manage keys yourself? Mint one at `app.spooling.ai/settings` and run
369
+ `spooling cloud login --key sk_live_...`. You can override the API base with `--api-url` or the
367
370
  `SPOOLING_CLOUD_URL` env var (default: `https://api.spooling.ai`).
368
371
 
369
372
  ### Push once
@@ -384,11 +387,14 @@ spooling push --dry-run # show what would be pushed
384
387
  **Which team gets the sessions** is decided by the API key you are logged in with. Each key belongs to one workspace (personal or a team), and `spooling push` sends to that workspace. Mint a key for the team in the app, then log in with it:
385
388
 
386
389
  ```bash
390
+ spooling cloud teams # every workspace (personal + teams) your account belongs to
391
+ spooling cloud whoami # the account and workspace this CLI pushes to
387
392
  spooling cloud login --key sk_<team-key> # replaces the stored key; later pushes go to this team
388
- spooling cloud status # session/cost totals of the workspace this key belongs to
389
393
  ```
390
394
 
391
- To push to a different team, log in with that team's key. Only one key is stored at a time. `cloud status` doesn't print the workspace name, so compare its totals with what the team shows in the app.
395
+ `spooling cloud teams` marks the workspace your current key pushes to with `<- this key`, and shows your role, the number of members and the plan for each. `spooling cloud status` also prints the workspace name now. `teams` and `whoami` take `--json` for scripting.
396
+
397
+ To push to a different team, log in with that team's key. Only one key is stored at a time, so check `spooling cloud whoami` before a push if you work with several teams. These commands need a server that supports `/v1/me`; against an older one they say so and `spooling cloud status` still works.
392
398
 
393
399
  **Which sessions go up.** With no filters, `spooling push` sends the most recent `--limit` sessions from every project on the machine. Use these to send only some of them. Filters combine with AND:
394
400
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "spooling"
3
- version = "0.2.14"
3
+ version = "0.2.16"
4
4
  description = "Local session tracker and semantic search for AI coding assistants"
5
5
  readme = "README.md"
6
6
  authors = [{ name = "Parsed Analytics, Inc." }]
@@ -107,6 +107,16 @@ def watch():
107
107
  do_watch()
108
108
 
109
109
 
110
+ @cli.command("login")
111
+ @click.option("--no-browser", is_flag=True, help="Print the approval link instead of opening it")
112
+ @click.option("--api-url", default=None, help="Override the Spooling Cloud API base")
113
+ @click.pass_context
114
+ def login(ctx, no_browser, api_url):
115
+ """Sign in to Spooling Cloud through your browser (shortcut for `spooling cloud login`)."""
116
+ from spooling.cloud import cloud_login
117
+ ctx.invoke(cloud_login, key=None, api_url=api_url, no_browser=no_browser)
118
+
119
+
110
120
  @cli.command()
111
121
  @click.argument("query")
112
122
  @click.option("-n", "--limit", default=10, help="Number of results")
@@ -15,6 +15,7 @@ import click
15
15
  import httpx
16
16
  from rich.console import Console
17
17
  from rich.markup import escape
18
+ from rich.table import Table
18
19
 
19
20
  from spooling.db import get_connection
20
21
  from spooling.redact import redact_messages, redact_traces
@@ -65,7 +66,7 @@ def _auth_headers() -> dict:
65
66
  cfg = _load_config()
66
67
  key = cfg.get("api_key") or os.environ.get("SPOOLING_CLOUD_API_KEY")
67
68
  if not key:
68
- raise click.ClickException("Not logged in. Run `spooling cloud login --key sk_...` first.")
69
+ raise click.ClickException("Not logged in. Run `spooling login` first.")
69
70
  return {"Authorization": f"Bearer {key}"}
70
71
 
71
72
 
@@ -217,14 +218,22 @@ def cloud():
217
218
 
218
219
 
219
220
  @cloud.command("login")
220
- @click.option("--key", required=True, help="API key minted at app.spooling.ai/settings/api-keys")
221
+ @click.option("--key", default=None, help="Use an API key you already have (skips the browser)")
221
222
  @click.option("--api-url", default=None, help=f"Override API base (default {DEFAULT_API})")
222
- def cloud_login(key: str, api_url: str | None):
223
- """Store a Spooling Cloud API key in ~/.config/spooling/cloud.json."""
223
+ @click.option("--no-browser", is_flag=True, help="Print the approval link instead of opening it")
224
+ def cloud_login(key: str | None, api_url: str | None, no_browser: bool):
225
+ """Sign in to Spooling Cloud (opens your browser), or store a key you already have."""
224
226
  cfg = _load_config()
225
- cfg["api_key"] = key.strip()
226
227
  if api_url:
227
228
  cfg["api_url"] = api_url.rstrip("/")
229
+ if key:
230
+ cfg["api_key"] = key.strip()
231
+ else:
232
+ from spooling.device_login import run_device_login
233
+ base = cfg.get("api_url") or os.environ.get("SPOOLING_CLOUD_URL") or DEFAULT_API
234
+ cfg["api_key"], ws = run_device_login(base, open_browser=not no_browser)
235
+ if ws.get("name"):
236
+ console.print(f"[green]Approved.[/green] Sessions will be pushed to [bold]{ws['name']}[/bold].")
228
237
  _save_config(cfg)
229
238
 
230
239
  base = cfg.get("api_url") or DEFAULT_API
@@ -245,7 +254,7 @@ def cloud_status():
245
254
  """Show current login + cloud stats."""
246
255
  cfg = _load_config()
247
256
  if not cfg.get("api_key"):
248
- console.print("[yellow]Not logged in.[/yellow] Run `spooling cloud login --key sk_...`.")
257
+ console.print("[yellow]Not logged in.[/yellow] Run `spooling login`.")
249
258
  return
250
259
  base = _api_base()
251
260
  try:
@@ -253,6 +262,10 @@ def cloud_status():
253
262
  r.raise_for_status()
254
263
  s = r.json()
255
264
  console.print(f"API: [cyan]{base}[/cyan]")
265
+ me = _fetch_me(required=False)
266
+ if me and me.get("workspace"):
267
+ ws = me["workspace"]
268
+ console.print(f" workspace: [bold]{escape(ws['name'])}[/bold] [dim]({_kind_label(ws)})[/dim]")
256
269
  console.print(f" sessions: [bold]{s.get('sessions', 0)}[/bold]")
257
270
  console.print(f" messages: [bold]{s.get('messages', 0)}[/bold]")
258
271
  console.print(f" providers: [bold]{s.get('providers', 0)}[/bold]")
@@ -263,6 +276,93 @@ def cloud_status():
263
276
  _fail(f"{_explain_error(e, base)}")
264
277
 
265
278
 
279
+ def _fetch_me(*, required: bool) -> dict | None:
280
+ """GET /v1/me: who this key is and which workspaces its user belongs to.
281
+
282
+ ``required=False`` is for best-effort extras (returns None on any problem);
283
+ ``required=True`` explains failures and exits non-zero.
284
+ """
285
+ headers = _auth_headers()
286
+ base = _api_base()
287
+ try:
288
+ r = httpx.get(f"{base}/v1/me", headers=headers, timeout=15)
289
+ r.raise_for_status()
290
+ return r.json()
291
+ except httpx.HTTPStatusError as e:
292
+ if not required:
293
+ return None
294
+ if e.response.status_code == 404:
295
+ _fail(
296
+ "This server is older than the CLI and can't list workspaces yet.\n"
297
+ " Ask your admin to redeploy it. Meanwhile `spooling cloud status`\n"
298
+ " shows the totals of the workspace your key belongs to."
299
+ )
300
+ _fail(_explain_http(e))
301
+ except Exception as e: # noqa: BLE001
302
+ if not required:
303
+ return None
304
+ _fail(_explain_error(e, base))
305
+
306
+
307
+ def _kind_label(w: dict) -> str:
308
+ return "Personal" if w.get("kind") == "personal" else "Team"
309
+
310
+
311
+ @cloud.command("whoami")
312
+ @click.option("--json", "as_json", is_flag=True, help="Print JSON instead of text")
313
+ def cloud_whoami(as_json: bool):
314
+ """Show which account and workspace (team) this CLI pushes to.
315
+
316
+ The workspace is decided by the API key you logged in with. Use
317
+ `spooling cloud teams` to see every workspace you belong to.
318
+ """
319
+ me = _fetch_me(required=True)
320
+ if as_json:
321
+ click.echo(json.dumps(me, indent=2))
322
+ return
323
+ user, ws = me["user"], me.get("workspace")
324
+ who = user.get("email") or user.get("name") or user.get("id")
325
+ console.print(f"Account: [bold]{escape(str(who))}[/bold]")
326
+ if ws:
327
+ role = f", you are {ws['role']}" if ws.get("role") else ""
328
+ members = f", {ws['members']} member{'s' if ws['members'] != 1 else ''}" if ws.get("members") is not None else ""
329
+ console.print(f"Workspace: [bold cyan]{escape(ws['name'])}[/bold cyan] [dim]({_kind_label(ws)}{role}{members}, {ws.get('plan', 'free')} plan)[/dim]")
330
+ console.print(f"API: [dim]{_api_base()}[/dim]")
331
+ console.print("[dim]`spooling push` sends sessions to this workspace. See all of yours with `spooling cloud teams`.[/dim]")
332
+
333
+
334
+ @cloud.command("teams")
335
+ @click.option("--json", "as_json", is_flag=True, help="Print JSON instead of a table")
336
+ def cloud_teams(as_json: bool):
337
+ """List every workspace (personal + teams) your account belongs to.
338
+
339
+ The row marked ``<- this key`` is where `spooling push` sends sessions.
340
+ To push somewhere else, log in with that team's API key:
341
+ `spooling cloud login --key sk_<team-key>`.
342
+ """
343
+ me = _fetch_me(required=True)
344
+ if as_json:
345
+ click.echo(json.dumps(me["workspaces"], indent=2))
346
+ return
347
+ rows = me["workspaces"]
348
+ table = Table(title="Your workspaces", show_lines=False)
349
+ table.add_column("Workspace", style="cyan")
350
+ table.add_column("Type")
351
+ table.add_column("Your role")
352
+ table.add_column("Members", justify="right")
353
+ table.add_column("Plan", style="dim")
354
+ table.add_column("")
355
+ for w in rows:
356
+ table.add_row(
357
+ escape(w["name"]), _kind_label(w), w.get("role") or "-",
358
+ str(w["members"]) if w.get("members") is not None else "-",
359
+ w.get("plan", "free"),
360
+ "[green]<- this key[/green]" if w.get("current") else "",
361
+ )
362
+ console.print(table if rows else "[yellow]No workspaces found for this account.[/yellow]")
363
+ console.print("[dim]A key pushes to one workspace. Switch with `spooling cloud login --key sk_<that team's key>`.[/dim]")
364
+
365
+
266
366
  @cloud.command("logout")
267
367
  def cloud_logout():
268
368
  """Remove the stored API key."""
@@ -0,0 +1,88 @@
1
+ """Sign the CLI in through the browser: ``spooling login``.
2
+
3
+ The API key is created HERE, on this machine, and only its sha256 is sent to Spooling. You approve the short code in
4
+ your browser (signed in, choosing the workspace), and the server registers that key for you. No secret ever travels
5
+ through the browser, the clipboard, or the server's responses, and there is nothing to copy and paste.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import platform
12
+ import secrets
13
+ import socket
14
+ import time
15
+ import webbrowser
16
+
17
+ import click
18
+ import httpx
19
+ from rich.console import Console
20
+
21
+ console = Console()
22
+
23
+
24
+ class LoginError(click.ClickException):
25
+ pass
26
+
27
+
28
+ def _new_key() -> str:
29
+ return "sk_" + secrets.token_urlsafe(32)
30
+
31
+
32
+ def _client_name() -> str:
33
+ try:
34
+ host = socket.gethostname().split(".")[0]
35
+ except Exception: # noqa: BLE001
36
+ host = "this computer"
37
+ return f"{host} ({platform.system() or 'unknown OS'})"[:80]
38
+
39
+
40
+ def run_device_login(api_base: str, *, open_browser: bool = True, sleep=time.sleep, now=time.monotonic,
41
+ http=httpx, out=console) -> tuple[str, dict]:
42
+ """Do the whole dance. Returns (api_key, workspace). Raises LoginError with a plain-English reason."""
43
+ api_base = api_base.rstrip("/")
44
+ key = _new_key()
45
+ try:
46
+ r = http.post(f"{api_base}/api/v1/auths/device/code", timeout=15, json={
47
+ "client_name": _client_name(), "key_hash": hashlib.sha256(key.encode()).hexdigest(), "key_prefix": key[:12]})
48
+ except httpx.HTTPError as e:
49
+ raise LoginError(f"Could not reach {api_base}: {e}") from e
50
+ if r.status_code == 429:
51
+ raise LoginError("Too many login attempts from this network. Try again in a while.")
52
+ if r.status_code != 200:
53
+ raise LoginError(f"Spooling refused the login request ({r.status_code}).")
54
+ d = r.json()
55
+
56
+ url = d["verification_uri_complete"]
57
+ out.print()
58
+ out.print(f" Your code: [bold cyan]{d['user_code']}[/bold cyan]")
59
+ out.print(f" Approve it at [underline]{url}[/underline]")
60
+ if open_browser:
61
+ try:
62
+ if webbrowser.open(url):
63
+ out.print(" [dim](opened in your browser)[/dim]")
64
+ except Exception: # noqa: BLE001
65
+ pass
66
+ out.print(" [dim]Waiting for approval... (Ctrl+C to cancel)[/dim]\n")
67
+
68
+ interval = max(int(d.get("interval", 5)), 1)
69
+ deadline = now() + int(d.get("expires_in", 600))
70
+ while now() < deadline:
71
+ sleep(interval)
72
+ try:
73
+ p = http.post(f"{api_base}/api/v1/auths/device/poll", json={"device_code": d["device_code"]}, timeout=15)
74
+ except httpx.HTTPError:
75
+ continue # a blip: keep waiting until the code expires
76
+ if p.status_code != 200:
77
+ continue
78
+ j = p.json()
79
+ status = j.get("status")
80
+ if status == "approved":
81
+ return key, j.get("workspace") or {}
82
+ if status == "denied":
83
+ raise LoginError("The request was denied in the browser.")
84
+ if status == "expired":
85
+ raise LoginError("The code expired before it was approved. Run the command again.")
86
+ if status == "slow_down":
87
+ interval = int(j.get("interval", interval + 5))
88
+ raise LoginError("Timed out waiting for approval. Run the command again.")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spooling
3
- Version: 0.2.14
3
+ Version: 0.2.16
4
4
  Summary: Local session tracker and semantic search for AI coding assistants
5
5
  Author: Parsed Analytics, Inc.
6
6
  License: MIT
@@ -390,16 +390,19 @@ the CLI ships with a `spooling cloud` subcommand.
390
390
 
391
391
  ### One-time setup
392
392
 
393
- 1. Mint an API key in the GUI at `app.spooling.ai/settings/api-keys`
394
- (looks like `sk_live_...`).
395
- 2. Save it locally:
393
+ 1. Sign in from the terminal:
396
394
 
397
395
  ```bash
398
- spooling cloud login --key sk_live_...
396
+ spooling login
399
397
  ```
400
398
 
401
- The key is stored at `~/.config/spooling/cloud.json` with `0600` perms.
402
- You can override the API base with `--api-url` or the
399
+ This opens your browser with a short code (for example `BCDF-GHJK`). Check the code, pick the workspace the
400
+ sessions should go to, and click Approve. The API key is generated on your machine and only its hash is sent to
401
+ Spooling, so there is nothing to copy and paste. It is stored at `~/.config/spooling/cloud.json` with `0600`
402
+ perms. Use `--no-browser` to just print the link (SSH sessions, containers).
403
+
404
+ Prefer to manage keys yourself? Mint one at `app.spooling.ai/settings` and run
405
+ `spooling cloud login --key sk_live_...`. You can override the API base with `--api-url` or the
403
406
  `SPOOLING_CLOUD_URL` env var (default: `https://api.spooling.ai`).
404
407
 
405
408
  ### Push once
@@ -420,11 +423,14 @@ spooling push --dry-run # show what would be pushed
420
423
  **Which team gets the sessions** is decided by the API key you are logged in with. Each key belongs to one workspace (personal or a team), and `spooling push` sends to that workspace. Mint a key for the team in the app, then log in with it:
421
424
 
422
425
  ```bash
426
+ spooling cloud teams # every workspace (personal + teams) your account belongs to
427
+ spooling cloud whoami # the account and workspace this CLI pushes to
423
428
  spooling cloud login --key sk_<team-key> # replaces the stored key; later pushes go to this team
424
- spooling cloud status # session/cost totals of the workspace this key belongs to
425
429
  ```
426
430
 
427
- To push to a different team, log in with that team's key. Only one key is stored at a time. `cloud status` doesn't print the workspace name, so compare its totals with what the team shows in the app.
431
+ `spooling cloud teams` marks the workspace your current key pushes to with `<- this key`, and shows your role, the number of members and the plan for each. `spooling cloud status` also prints the workspace name now. `teams` and `whoami` take `--json` for scripting.
432
+
433
+ To push to a different team, log in with that team's key. Only one key is stored at a time, so check `spooling cloud whoami` before a push if you work with several teams. These commands need a server that supports `/v1/me`; against an older one they say so and `spooling cloud status` still works.
428
434
 
429
435
  **Which sessions go up.** With no filters, `spooling push` sends the most recent `--limit` sessions from every project on the machine. Use these to send only some of them. Filters combine with AND:
430
436
 
@@ -8,6 +8,7 @@ spooling/cli.py
8
8
  spooling/cloud.py
9
9
  spooling/config.py
10
10
  spooling/db.py
11
+ spooling/device_login.py
11
12
  spooling/embeddings.py
12
13
  spooling/evals.py
13
14
  spooling/experiments.py
@@ -67,6 +68,8 @@ spooling/providers/windsurf.py
67
68
  tests/test_agent_spans.py
68
69
  tests/test_claude_code_provider.py
69
70
  tests/test_cloud_errors.py
71
+ tests/test_cloud_teams.py
72
+ tests/test_device_login.py
70
73
  tests/test_docs.py
71
74
  tests/test_insights.py
72
75
  tests/test_mcp_auth_middleware.py
@@ -0,0 +1,118 @@
1
+ """`spooling cloud whoami` / `cloud teams` (GET /v1/me), and the workspace line in `cloud status`."""
2
+
3
+ import json
4
+
5
+ import httpx
6
+ import pytest
7
+ from click.testing import CliRunner
8
+
9
+ from spooling import cloud
10
+ from spooling.cli import cli
11
+
12
+ ME = {
13
+ "user": {"id": "u1", "email": "dev@example.com", "name": "Dev"},
14
+ "workspace": {"id": "w1", "name": "Dev", "kind": "personal", "plan": "free", "role": "owner",
15
+ "members": 1, "current": True},
16
+ "workspaces": [
17
+ {"id": "w1", "name": "Dev", "kind": "personal", "plan": "free", "role": "owner", "members": 1, "current": True},
18
+ {"id": "w2", "name": "Toebox", "kind": "team", "plan": "team", "role": "admin", "members": 4, "current": False},
19
+ {"id": "w3", "name": "[red]Odd[/red] Name", "kind": "team", "plan": "free", "role": "member", "members": 2, "current": False},
20
+ ],
21
+ }
22
+ STATS = {"sessions": 12, "messages": 340, "providers": 2, "cost": 1.5}
23
+
24
+
25
+ def run(*args):
26
+ return CliRunner().invoke(cli, ["cloud", *args])
27
+
28
+
29
+ @pytest.fixture
30
+ def server(monkeypatch):
31
+ """Fake Spooling Cloud: path -> (status, json). Records the paths requested."""
32
+ routes = {"/v1/me": (200, ME), "/v1/stats": (200, STATS)}
33
+ seen = []
34
+ monkeypatch.setattr(cloud, "_auth_headers", lambda: {"Authorization": "Bearer sk_test"})
35
+ monkeypatch.setattr(cloud, "_api_base", lambda: "https://api.example")
36
+ monkeypatch.setattr(cloud, "_load_config", lambda: {"api_key": "sk_test"})
37
+
38
+ def fake_get(url, headers=None, params=None, timeout=None):
39
+ path = url.replace("https://api.example", "")
40
+ seen.append(path)
41
+ status, body = routes[path]
42
+ return httpx.Response(status, json=body, request=httpx.Request("GET", url))
43
+
44
+ monkeypatch.setattr(cloud.httpx, "get", fake_get)
45
+ return type("S", (), {"routes": routes, "seen": seen})
46
+
47
+
48
+ def test_whoami_shows_account_workspace_and_role(server):
49
+ r = run("whoami")
50
+ assert r.exit_code == 0
51
+ assert "dev@example.com" in r.output and "Dev" in r.output
52
+ assert "Personal" in r.output and "owner" in r.output and "1 member," in r.output
53
+ assert "spooling push" in r.output
54
+
55
+
56
+ def test_whoami_json(server):
57
+ assert json.loads(run("whoami", "--json").output) == ME
58
+
59
+
60
+ def test_teams_lists_all_workspaces_and_marks_the_current_one(server):
61
+ r = run("teams")
62
+ assert r.exit_code == 0
63
+ for name in ("Toebox", "Personal", "Team", "admin", "member"):
64
+ assert name in r.output
65
+ current_rows = [l for l in r.output.splitlines() if "<- this key" in l]
66
+ assert len(current_rows) == 1 and "Dev" in current_rows[0]
67
+
68
+
69
+ def test_teams_does_not_interpret_markup_in_names(server):
70
+ assert "[red]Odd[/red] Name" in run("teams").output
71
+
72
+
73
+ def test_teams_json_is_the_workspace_list(server):
74
+ data = json.loads(run("teams", "--json").output)
75
+ assert [w["name"] for w in data] == ["Dev", "Toebox", "[red]Odd[/red] Name"]
76
+ assert [w["current"] for w in data] == [True, False, False]
77
+
78
+
79
+ def test_older_server_without_v1_me_explains_and_exits_nonzero(server):
80
+ server.routes["/v1/me"] = (404, {"detail": "Not Found"})
81
+ for cmd in ("whoami", "teams"):
82
+ r = run(cmd)
83
+ assert r.exit_code == 1
84
+ assert "older than the CLI" in r.output and "cloud status" in r.output
85
+
86
+
87
+ def test_rejected_key_is_explained(server):
88
+ server.routes["/v1/me"] = (401, {"detail": "invalid or revoked key"})
89
+ r = run("whoami")
90
+ assert r.exit_code == 1 and "401" in r.output and "cloud login" in r.output
91
+
92
+
93
+ def test_unreachable_server_exits_nonzero(server, monkeypatch):
94
+ def boom(*a, **k):
95
+ raise httpx.ConnectError("connection refused")
96
+ monkeypatch.setattr(cloud.httpx, "get", boom)
97
+ r = run("teams")
98
+ assert r.exit_code == 1 and "log in" not in r.output.lower()
99
+
100
+
101
+ def test_status_shows_workspace_name_when_server_supports_it(server):
102
+ r = run("status")
103
+ assert r.exit_code == 0
104
+ assert "workspace" in r.output and "Dev" in r.output and "sessions" in r.output
105
+ assert "/v1/me" in server.seen
106
+
107
+
108
+ def test_status_still_works_against_an_older_server(server):
109
+ server.routes["/v1/me"] = (404, {"detail": "Not Found"})
110
+ r = run("status")
111
+ assert r.exit_code == 0
112
+ assert "sessions" in r.output and "workspace:" not in r.output
113
+
114
+
115
+ def test_status_ignores_a_failing_v1_me(server, monkeypatch):
116
+ server.routes["/v1/me"] = (500, {"detail": "boom"})
117
+ r = run("status")
118
+ assert r.exit_code == 0 and "sessions" in r.output
@@ -0,0 +1,155 @@
1
+ """`spooling login`: the key is made locally, only its hash is sent, and every failure is explained."""
2
+ import hashlib
3
+
4
+ import httpx
5
+ import pytest
6
+
7
+ from spooling import device_login
8
+ from spooling.device_login import LoginError, run_device_login
9
+
10
+
11
+ class FakeHttp:
12
+ """Stands in for httpx: records requests and replays a scripted server."""
13
+ HTTPError = httpx.HTTPError
14
+
15
+ def __init__(self, polls, code_status=200):
16
+ self.polls, self.code_status, self.sent, self.poll_calls = list(polls), code_status, None, 0
17
+
18
+ def post(self, url, json=None, timeout=None):
19
+ if url.endswith("/device/code"):
20
+ self.sent = json
21
+ body = {"device_code": "dc", "user_code": "BCDF-GHJK", "verification_uri_complete": "https://app.spooling.ai/device?code=BCDF-GHJK",
22
+ "expires_in": 600, "interval": 5}
23
+ return httpx.Response(self.code_status, json=body, request=httpx.Request("POST", url))
24
+ self.poll_calls += 1
25
+ item = self.polls.pop(0) if self.polls else {"status": "pending"}
26
+ if isinstance(item, Exception):
27
+ raise item
28
+ return httpx.Response(200, json=item, request=httpx.Request("POST", url))
29
+
30
+
31
+ class Clock:
32
+ def __init__(self): self.t = 0
33
+ def now(self): return self.t
34
+ def sleep(self, s): self.t += s
35
+
36
+
37
+ def run(polls, **kw):
38
+ clock, http = Clock(), FakeHttp(polls, **kw)
39
+ return http, lambda: run_device_login("https://api.spooling.ai/", open_browser=False, sleep=clock.sleep, now=clock.now, http=http)
40
+
41
+
42
+ def test_approved_returns_the_locally_generated_key_and_only_its_hash_was_sent():
43
+ http, go = run([{"status": "pending"}, {"status": "approved", "workspace": {"id": "w", "name": "Acme"}}])
44
+ key, ws = go()
45
+ assert key.startswith("sk_") and len(key) > 40 and ws == {"id": "w", "name": "Acme"}
46
+ assert http.sent["key_hash"] == hashlib.sha256(key.encode()).hexdigest()
47
+ assert key not in str(http.sent) and http.sent["key_prefix"] == key[:12]
48
+ assert http.poll_calls == 2
49
+
50
+
51
+ def test_each_login_makes_a_fresh_key():
52
+ assert run([{"status": "approved", "workspace": {}}])[1]()[0] != run([{"status": "approved", "workspace": {}}])[1]()[0]
53
+
54
+
55
+ @pytest.mark.parametrize("status,needle", [("denied", "denied"), ("expired", "expired")])
56
+ def test_denied_and_expired_are_explained(status, needle):
57
+ with pytest.raises(LoginError, match=needle):
58
+ run([{"status": status}])[1]()
59
+
60
+
61
+ def test_network_blips_while_polling_do_not_abort_the_login():
62
+ _, go = run([httpx.ConnectError("boom"), {"status": "approved", "workspace": {"name": "Acme"}}])
63
+ assert go()[1]["name"] == "Acme"
64
+
65
+
66
+ def test_slow_down_widens_the_interval():
67
+ clock = Clock()
68
+ http = FakeHttp([{"status": "slow_down", "interval": 10}, {"status": "approved", "workspace": {}}])
69
+ run_device_login("https://x", open_browser=False, sleep=clock.sleep, now=clock.now, http=http)
70
+ assert clock.t == 5 + 10
71
+
72
+
73
+ def test_gives_up_when_the_code_window_closes():
74
+ clock = Clock()
75
+ http = FakeHttp([]) # pending forever
76
+ with pytest.raises(LoginError, match="Timed out"):
77
+ run_device_login("https://x", open_browser=False, sleep=clock.sleep, now=clock.now, http=http)
78
+ assert clock.t >= 600
79
+
80
+
81
+ def test_rate_limited_and_server_errors_are_explained():
82
+ with pytest.raises(LoginError, match="Too many"):
83
+ run([], code_status=429)[1]()
84
+ with pytest.raises(LoginError, match="refused"):
85
+ run([], code_status=500)[1]()
86
+
87
+
88
+ def test_unreachable_server_is_explained():
89
+ class Down:
90
+ HTTPError = httpx.HTTPError
91
+ def post(self, *a, **k): raise httpx.ConnectError("no route")
92
+ with pytest.raises(LoginError, match="Could not reach"):
93
+ run_device_login("https://nowhere", open_browser=False, http=Down())
94
+
95
+
96
+ def test_the_approval_url_is_printed_even_if_the_browser_cannot_open(monkeypatch):
97
+ printed = []
98
+ class Out:
99
+ def print(self, *a, **k): printed.append(" ".join(str(x) for x in a))
100
+ monkeypatch.setattr(device_login.webbrowser, "open", lambda url: (_ for _ in ()).throw(RuntimeError("no display")))
101
+ clock, http = Clock(), FakeHttp([{"status": "approved", "workspace": {}}])
102
+ run_device_login("https://x", open_browser=True, sleep=clock.sleep, now=clock.now, http=http, out=Out())
103
+ assert any("BCDF-GHJK" in p for p in printed) and any("/device?code=BCDF-GHJK" in p for p in printed)
104
+
105
+
106
+ # --- wiring: `spooling login` and `spooling cloud login` ----------------------------------------------------------
107
+
108
+ def _cli(monkeypatch, tmp_path, result=("sk_made_locally", {"id": "w", "name": "Acme"})):
109
+ from spooling import cloud
110
+ monkeypatch.setattr(cloud, "CONFIG_PATH", tmp_path / "cloud.json")
111
+ monkeypatch.setattr(cloud.httpx, "get", lambda *a, **k: httpx.Response(200, json={"sessions": 3}, request=httpx.Request("GET", a[0])))
112
+ calls = []
113
+ import spooling.device_login as dl
114
+ monkeypatch.setattr(dl, "run_device_login", lambda base, open_browser=True, **k: calls.append((base, open_browser)) or result)
115
+ return cloud, calls
116
+
117
+
118
+ def test_top_level_login_saves_the_key_with_private_permissions(monkeypatch, tmp_path):
119
+ from click.testing import CliRunner
120
+ from spooling.cli import cli
121
+ cloud, calls = _cli(monkeypatch, tmp_path)
122
+ r = CliRunner().invoke(cli, ["login"])
123
+ assert r.exit_code == 0, r.output
124
+ assert calls == [("https://api.spooling.ai", True)]
125
+ assert cloud._load_config()["api_key"] == "sk_made_locally"
126
+ assert oct((tmp_path / "cloud.json").stat().st_mode & 0o777) == "0o600"
127
+ assert "Acme" in r.output
128
+
129
+
130
+ def test_no_browser_flag_and_custom_api_url_are_honoured(monkeypatch, tmp_path):
131
+ from click.testing import CliRunner
132
+ from spooling.cli import cli
133
+ cloud, calls = _cli(monkeypatch, tmp_path)
134
+ assert CliRunner().invoke(cli, ["login", "--no-browser", "--api-url", "https://staging.example/"]).exit_code == 0
135
+ assert calls == [("https://staging.example", False)]
136
+
137
+
138
+ def test_cloud_login_with_a_key_still_works_without_the_browser(monkeypatch, tmp_path):
139
+ from click.testing import CliRunner
140
+ from spooling.cli import cli
141
+ cloud, calls = _cli(monkeypatch, tmp_path)
142
+ assert CliRunner().invoke(cli, ["cloud", "login", "--key", "sk_pasted_key"]).exit_code == 0
143
+ assert calls == [] and cloud._load_config()["api_key"] == "sk_pasted_key"
144
+
145
+
146
+ def test_a_failed_login_leaves_the_existing_key_alone(monkeypatch, tmp_path):
147
+ from click.testing import CliRunner
148
+ from spooling.cli import cli
149
+ cloud, _ = _cli(monkeypatch, tmp_path)
150
+ cloud._save_config({"api_key": "sk_old"})
151
+ import spooling.device_login as dl
152
+ monkeypatch.setattr(dl, "run_device_login", lambda *a, **k: (_ for _ in ()).throw(LoginError("denied in the browser")))
153
+ r = CliRunner().invoke(cli, ["login"])
154
+ assert r.exit_code != 0 and "denied" in r.output
155
+ assert cloud._load_config()["api_key"] == "sk_old"
@@ -29,3 +29,12 @@ def test_readme_documents_every_push_scoping_option():
29
29
  for opt in ("--project", "--cwd", "--title", "--copy", "--with-spans", "--dry-run", "--no-redact", "cloud login --key sk_<team-key>"):
30
30
  assert opt in readme, f"README does not mention {opt}"
31
31
  assert "stats --by" not in readme
32
+
33
+
34
+ def test_readme_documents_the_team_commands():
35
+ from pathlib import Path
36
+ readme = (Path(__file__).resolve().parent.parent / "README.md").read_text()
37
+ for cmd in ("spooling cloud teams", "spooling cloud whoami"):
38
+ assert cmd in readme
39
+ out = CliRunner().invoke(cli, ["cloud", "--help"]).output
40
+ assert "teams" in out and "whoami" in out
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes