wspx 0.1.0.dev0__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 (99) hide show
  1. wspx/__init__.py +24 -0
  2. wspx/_version.py +1 -0
  3. wspx/addressing.py +415 -0
  4. wspx/auth.py +77 -0
  5. wspx/cli/__init__.py +1 -0
  6. wspx/cli/client.py +124 -0
  7. wspx/cli/config.py +89 -0
  8. wspx/cli/connect.py +88 -0
  9. wspx/cli/main.py +848 -0
  10. wspx/cloud/__init__.py +20 -0
  11. wspx/cloud/app.py +191 -0
  12. wspx/cloud/backend.py +141 -0
  13. wspx/cloud/compose.py +85 -0
  14. wspx/cloud/deploy.py +102 -0
  15. wspx/config.py +189 -0
  16. wspx/control/__init__.py +5 -0
  17. wspx/control/app.py +488 -0
  18. wspx/control/backend.py +244 -0
  19. wspx/control/gateway_client.py +79 -0
  20. wspx/control/mcp_server.py +71 -0
  21. wspx/control/sessions.py +424 -0
  22. wspx/control/tracedb.py +183 -0
  23. wspx/control/ui/assets/index-BJFweZAn.css +1 -0
  24. wspx/control/ui/assets/index-DhUVhWIK.js +10 -0
  25. wspx/control/ui/index.html +13 -0
  26. wspx/control/views.py +180 -0
  27. wspx/diagnostics.py +146 -0
  28. wspx/driver/__init__.py +7 -0
  29. wspx/driver/loop.py +255 -0
  30. wspx/driver/messages.py +62 -0
  31. wspx/driver/providers/__init__.py +84 -0
  32. wspx/driver/providers/anthropic.py +149 -0
  33. wspx/driver/providers/compat.py +115 -0
  34. wspx/driver/providers/google.py +138 -0
  35. wspx/driver/providers/openai.py +125 -0
  36. wspx/driver/run.py +134 -0
  37. wspx/errors.py +69 -0
  38. wspx/gateway/__init__.py +8 -0
  39. wspx/gateway/app.py +626 -0
  40. wspx/gateway/ledger.py +536 -0
  41. wspx/gateway/prices.py +75 -0
  42. wspx/gateway/usage.py +284 -0
  43. wspx/handles.py +117 -0
  44. wspx/integrations/AGENTS.snippet.md +8 -0
  45. wspx/integrations/SKILL.md +52 -0
  46. wspx/integrations/__init__.py +17 -0
  47. wspx/integrations/claude-plugin/.claude-plugin/plugin.json +30 -0
  48. wspx/integrations/claude-plugin/skills/wspx/SKILL.md +52 -0
  49. wspx/integrations/codex-hooks.toml +9 -0
  50. wspx/lab/__init__.py +5 -0
  51. wspx/lab/analysis.py +485 -0
  52. wspx/lab/check.py +489 -0
  53. wspx/lab/evaluate.py +108 -0
  54. wspx/lab/export.py +275 -0
  55. wspx/lab/grep.py +754 -0
  56. wspx/lab/index.py +239 -0
  57. wspx/lab/ir/__init__.py +1 -0
  58. wspx/lab/ir/capture.py +299 -0
  59. wspx/lab/ir/graph.py +148 -0
  60. wspx/lab/ir/model_ir.py +522 -0
  61. wspx/lab/ir/semantics.py +1255 -0
  62. wspx/lab/ir/tape.py +853 -0
  63. wspx/lab/loader.py +204 -0
  64. wspx/lab/merge.py +200 -0
  65. wspx/lab/ops/__init__.py +76 -0
  66. wspx/lab/ops/builtin.py +379 -0
  67. wspx/lab/patch.py +320 -0
  68. wspx/lab/probe.py +206 -0
  69. wspx/lab/results.py +114 -0
  70. wspx/lab/sdk.py +120 -0
  71. wspx/lab/server.py +236 -0
  72. wspx/lab/session.py +1574 -0
  73. wspx/lab/tensors.py +119 -0
  74. wspx/lab/text.py +69 -0
  75. wspx/lab/tree.py +302 -0
  76. wspx/loops.py +127 -0
  77. wspx/project.py +143 -0
  78. wspx/py.typed +0 -0
  79. wspx/safety/__init__.py +15 -0
  80. wspx/safety/kill.py +47 -0
  81. wspx/safety/sweeper.py +68 -0
  82. wspx/store/__init__.py +64 -0
  83. wspx/store/objects.py +130 -0
  84. wspx/store/overlay.py +209 -0
  85. wspx/store/refs.py +150 -0
  86. wspx/testing/__init__.py +21 -0
  87. wspx/testing/api.py +155 -0
  88. wspx/testing/builtin.py +139 -0
  89. wspx/testing/runner.py +257 -0
  90. wspx/tools/__init__.py +17 -0
  91. wspx/tools/dispatch.py +129 -0
  92. wspx/tools/schemas.py +313 -0
  93. wspx/vcs/__init__.py +17 -0
  94. wspx/vcs/repo.py +431 -0
  95. wspx-0.1.0.dev0.dist-info/METADATA +278 -0
  96. wspx-0.1.0.dev0.dist-info/RECORD +99 -0
  97. wspx-0.1.0.dev0.dist-info/WHEEL +4 -0
  98. wspx-0.1.0.dev0.dist-info/entry_points.txt +10 -0
  99. wspx-0.1.0.dev0.dist-info/licenses/LICENSE +201 -0
wspx/cli/main.py ADDED
@@ -0,0 +1,848 @@
1
+ """``wspx``: deploy, start sessions, call tools, set limits and stop everything."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import subprocess
7
+ import sys
8
+ import webbrowser
9
+ from pathlib import Path
10
+ from typing import Annotated, Any
11
+
12
+ import typer
13
+
14
+ from wspx import __version__
15
+ from wspx.cli import config as cli_config
16
+ from wspx.cli.client import Control
17
+ from wspx.config import CONFIG_FILENAME, find_config
18
+ from wspx.errors import WspxError
19
+
20
+ app = typer.Typer(
21
+ name="wspx",
22
+ no_args_is_help=True,
23
+ add_completion=False,
24
+ help="Grep, edit, check, test and version-control model weights.",
25
+ )
26
+ keys_app = typer.Typer(
27
+ help="Provider keys, stored as Modal secrets (never on local disk).", no_args_is_help=True
28
+ )
29
+ limits_app = typer.Typer(
30
+ help="Optional spend, rate and compute limits. None are set by default.",
31
+ invoke_without_command=True,
32
+ )
33
+ hook_app = typer.Typer(help="Hook adapters for external agents.", no_args_is_help=True)
34
+ app.add_typer(keys_app, name="keys")
35
+ app.add_typer(limits_app, name="limits")
36
+ app.add_typer(hook_app, name="hook")
37
+
38
+ Session = Annotated[
39
+ str | None, typer.Option("--session", "-s", help="Session id (default: the last one used).")
40
+ ]
41
+
42
+
43
+ def _control() -> Control:
44
+ cfg = cli_config.require(cli_config.load())
45
+ return Control(cfg.url, cfg.token)
46
+
47
+
48
+ def _project_root() -> str:
49
+ """The enclosing project's root ("" outside any project); each has its own current session."""
50
+ found = find_config()
51
+ return str(found.parent) if found else ""
52
+
53
+
54
+ def _session(value: str | None) -> str:
55
+ cfg = cli_config.load()
56
+ root = _project_root()
57
+ sid = value or cfg.current(root)
58
+ if not sid:
59
+ raise typer.BadParameter("no session: pass --session or start one with `wspx new`")
60
+ if value and value != cfg.current(root):
61
+ cfg.set_current(root, value)
62
+ cli_config.save(cfg)
63
+ return sid
64
+
65
+
66
+ def _fail(exc: Exception) -> None:
67
+ typer.secho(f"error: {exc}", fg=typer.colors.RED, err=True)
68
+ raise typer.Exit(1)
69
+
70
+
71
+ def _tool(session: str | None, name: str, args: dict[str, Any]) -> None:
72
+ try:
73
+ result = _control().tool(
74
+ _session(session), name, {k: v for k, v in args.items() if v is not None}
75
+ )
76
+ except WspxError as exc:
77
+ _fail(exc)
78
+ return
79
+ typer.echo(result.get("summary", ""))
80
+ if not result.get("ok", True):
81
+ raise typer.Exit(1)
82
+
83
+
84
+ @app.callback(invoke_without_command=True)
85
+ def _main(
86
+ version: Annotated[bool, typer.Option("--version", help="Print the version.")] = False,
87
+ ) -> None:
88
+ if version:
89
+ typer.echo(__version__)
90
+ raise typer.Exit
91
+
92
+
93
+ # ---------------------------------------------------------------------- account and deployment
94
+
95
+
96
+ @app.command()
97
+ def login() -> None:
98
+ """Link your Modal account (Modal's token flow)."""
99
+ raise typer.Exit(subprocess.call([sys.executable, "-m", "modal", "token", "new"]))
100
+
101
+
102
+ PROVIDERS = "anthropic, openai, google or hf"
103
+ SPEND_CAPS = {
104
+ "anthropic": "https://platform.claude.com/settings/limits",
105
+ "openai": "https://platform.openai.com/settings/organization/limits",
106
+ "google": "https://aistudio.google.com/spend",
107
+ }
108
+
109
+
110
+ def _reload_keys() -> str:
111
+ """Make a running deployment pick up changed keys; says what happened."""
112
+ cfg = cli_config.load()
113
+ if not (cfg.url and cfg.token):
114
+ return "it is used once you run `wspx deploy`"
115
+ try:
116
+ reloaded = Control(cfg.url, cfg.token).reload_keys()
117
+ except WspxError:
118
+ return "the deployment did not answer; it takes effect on the next `wspx deploy`"
119
+ return "active now" if reloaded else "it takes effect when the gateway restarts"
120
+
121
+
122
+ @keys_app.command("set")
123
+ def keys_set(provider: Annotated[str, typer.Argument(help=PROVIDERS)]) -> None:
124
+ """Store a provider key once; every session and project uses it."""
125
+ from modal.exception import Error as ModalError
126
+
127
+ from wspx.cloud.deploy import set_key
128
+
129
+ value = typer.prompt(f"{provider} key", hide_input=True)
130
+ try:
131
+ set_key(provider, value)
132
+ except (ValueError, subprocess.CalledProcessError, ModalError) as exc:
133
+ _fail(exc)
134
+ typer.echo(f"stored the {provider} key in your Modal account; {_reload_keys()}")
135
+ if provider in SPEND_CAPS:
136
+ typer.echo(f"tip: {provider} can also cap spend on its side: {SPEND_CAPS[provider]}")
137
+
138
+
139
+ @keys_app.command("rm")
140
+ def keys_rm(provider: Annotated[str, typer.Argument(help=PROVIDERS)]) -> None:
141
+ """Remove a provider key."""
142
+ from modal.exception import Error as ModalError
143
+
144
+ from wspx.cloud.deploy import remove_key
145
+
146
+ try:
147
+ remove_key(provider)
148
+ except (ValueError, subprocess.CalledProcessError, ModalError) as exc:
149
+ _fail(exc)
150
+ typer.echo(f"removed the {provider} key; {_reload_keys()}")
151
+
152
+
153
+ @keys_app.command("list")
154
+ def keys_list() -> None:
155
+ """Which keys are set and whether each works (checked with a free API call)."""
156
+ try:
157
+ keys = _control().keys()
158
+ except WspxError as exc:
159
+ _fail(exc)
160
+ return
161
+ names = {"hf-router": "hf"}
162
+ for provider, state in keys.items():
163
+ if not state.get("set"):
164
+ status = "not set"
165
+ elif state.get("ok"):
166
+ status = "ok"
167
+ elif state.get("ok") is None:
168
+ status = f"set, not checked ({state.get('detail', '')})"
169
+ else:
170
+ status = f"rejected ({state.get('detail', '')})"
171
+ typer.echo(f"{names.get(provider, provider):<10} {status}")
172
+
173
+
174
+ @app.command()
175
+ def deploy(
176
+ docker: Annotated[
177
+ bool, typer.Option("--docker", help="Write a Docker Compose file instead.")
178
+ ] = False,
179
+ ) -> None:
180
+ """Deploy wspx into your Modal account (or as Docker Compose on a GPU box)."""
181
+ if docker:
182
+ from wspx.cloud.compose import write_compose
183
+
184
+ path = write_compose(Path.cwd())
185
+ typer.echo(f"wrote {path}; start it with `docker compose up -d`")
186
+ return
187
+ from wspx.cloud.deploy import deploy as do_deploy
188
+
189
+ try:
190
+ result = do_deploy()
191
+ except subprocess.CalledProcessError as exc:
192
+ _fail(WspxError(exc.stderr or str(exc)))
193
+ return
194
+ cfg = cli_config.load()
195
+ cfg.url = result.control_url
196
+ if result.api_token:
197
+ cfg.token = result.api_token
198
+ path = cli_config.save(cfg)
199
+ typer.echo(f"deployed: {result.control_url}\nconfig saved to {path}")
200
+ if not cfg.token:
201
+ typer.echo(
202
+ "note: the API token was created by an earlier deploy; set WSPX_TOKEN if this machine lacks it"
203
+ )
204
+
205
+
206
+ # ---------------------------------------------------------------------- sessions
207
+
208
+
209
+ @app.command()
210
+ def init(
211
+ model: Annotated[
212
+ str | None, typer.Option("--model", "-m", help="Hugging Face model id.")
213
+ ] = None,
214
+ driver: Annotated[
215
+ str | None, typer.Option("--driver", "-d", help="e.g. anthropic:claude-opus-5-5")
216
+ ] = None,
217
+ gpu: Annotated[str | None, typer.Option("--gpu", help="e.g. L4, H100 or H100:8")] = None,
218
+ ) -> None:
219
+ """Make the current directory a wspx project (writes wspx.toml)."""
220
+ path = Path.cwd() / CONFIG_FILENAME
221
+ if path.exists():
222
+ raise typer.BadParameter(f"{path} already exists")
223
+
224
+ def entry(key: str, value: str | None, example: str) -> str:
225
+ return f'{key} = "{value}"' if value else f'# {key} = "{example}"'
226
+
227
+ path.write_text(
228
+ "\n".join(
229
+ [
230
+ "[project]",
231
+ f'name = "{Path.cwd().name}"',
232
+ "",
233
+ "[model]",
234
+ entry("id", model, "Qwen/Qwen3-0.6B"),
235
+ "",
236
+ "[driver]",
237
+ entry("model", driver, "anthropic:claude-opus-5-5"),
238
+ "",
239
+ "[lab]",
240
+ entry("gpu", gpu, "L4"),
241
+ "",
242
+ "[tests]",
243
+ 'paths = ["wtests/"]',
244
+ "",
245
+ ]
246
+ )
247
+ )
248
+ typer.echo(f'wrote {path}; start a session here with `wspx new "<task>"`')
249
+
250
+
251
+ @app.command()
252
+ def new(
253
+ task: Annotated[
254
+ str, typer.Argument(help="What the driver should do (omit for an interactive session).")
255
+ ] = "",
256
+ model: Annotated[
257
+ str | None, typer.Option("--model", "-m", help="Hugging Face model id or path.")
258
+ ] = None,
259
+ driver: Annotated[
260
+ str | None, typer.Option("--driver", "-d", help="e.g. anthropic:claude-opus-5-5")
261
+ ] = None,
262
+ gpu: Annotated[
263
+ str | None, typer.Option("--gpu", help="e.g. L4, H100 or H100:8 (default: CPU)")
264
+ ] = None,
265
+ branch: Annotated[str | None, typer.Option("--branch")] = None,
266
+ revision: Annotated[str | None, typer.Option("--revision")] = None,
267
+ trust_remote_code: Annotated[bool, typer.Option("--trust-remote-code")] = False,
268
+ ) -> None:
269
+ """Start a session. Inside a project, wspx.toml supplies the defaults and the lab gets its files."""
270
+ from wspx.config import WspxConfig
271
+ from wspx.project import Project
272
+
273
+ try:
274
+ project = Project.find()
275
+ cfg = project.config if project else WspxConfig()
276
+ model = model or cfg.model.id
277
+ if not model:
278
+ raise typer.BadParameter("pass --model, or set [model] id in wspx.toml (`wspx init`)")
279
+ control = _control()
280
+ snapshot = control.upload_project(project.pack()) if project else None
281
+ record = control.new(
282
+ model=model,
283
+ driver=driver or cfg.driver.model,
284
+ task=task,
285
+ gpu=gpu or cfg.lab.gpu,
286
+ branch=branch,
287
+ revision=revision or cfg.model.revision,
288
+ dtype=cfg.model.dtype,
289
+ trust_remote_code=trust_remote_code or cfg.model.trust_remote_code,
290
+ grace_s=cfg.lab.grace,
291
+ keep_warm=cfg.lab.keep_warm,
292
+ project=project.name if project else "",
293
+ snapshot=snapshot,
294
+ )
295
+ except WspxError as exc:
296
+ _fail(exc)
297
+ return
298
+ state = cli_config.load()
299
+ state.set_current(str(project.root) if project else "", record["id"])
300
+ cli_config.save(state)
301
+ where = f" in {project.name}" if project else ""
302
+ driven = f" driven by {record['driver']}" if record.get("driver") else ""
303
+ typer.echo(
304
+ f"session {record['id']}{where} on {model}{driven}\n"
305
+ "the lab is starting; `wspx open` to watch"
306
+ )
307
+
308
+
309
+ @app.command()
310
+ def sessions(
311
+ all_: Annotated[bool, typer.Option("--all", help="Include other projects' sessions.")] = False,
312
+ ) -> None:
313
+ """List this project's sessions (or every session with --all)."""
314
+ from wspx.project import Project
315
+
316
+ try:
317
+ rows = _control().sessions()
318
+ project = None if all_ else Project.find()
319
+ except WspxError as exc:
320
+ _fail(exc)
321
+ return
322
+ if project is not None:
323
+ rows = [r for r in rows if r.get("project") == project.name]
324
+ current = cli_config.load().current(_project_root())
325
+ for r in sorted(rows, key=lambda r: r.get("created", 0)):
326
+ mark = "*" if r["id"] == current else " "
327
+ typer.echo(
328
+ f"{mark} {r['id']} {r['status']:<8} {r['tier']:<5} {r.get('project') or '-':<16} "
329
+ f"{r['model']} {r.get('driver') or ''}"
330
+ )
331
+
332
+
333
+ @app.command("open")
334
+ def open_ui(session: Session = None) -> None:
335
+ """Open the UI in a browser."""
336
+ cfg = cli_config.require(cli_config.load())
337
+ sid = session or cfg.current(_project_root())
338
+ url = f"{cfg.url.rstrip('/')}/#token={cfg.token}" + (f"&session={sid}" if sid else "")
339
+ webbrowser.open(url)
340
+ typer.echo(f"{cfg.url} (the token is in the URL fragment, not sent to the server in logs)")
341
+
342
+
343
+ @app.command()
344
+ def connect(
345
+ client: Annotated[str, typer.Argument(help="claude or codex")], session: Session = None
346
+ ) -> None:
347
+ """Point a local Claude Code or Codex at the hosted MCP endpoint, with hooks and the skill."""
348
+ from wspx.cli import connect as conn
349
+
350
+ cfg = cli_config.require(cli_config.load())
351
+ sid = _session(session)
352
+ try:
353
+ done = (
354
+ (conn.claude if client == "claude" else conn.codex)(
355
+ cfg.url, cfg.token, sid, project=Path.cwd()
356
+ )
357
+ if client in ("claude", "codex")
358
+ else None
359
+ )
360
+ except WspxError as exc:
361
+ _fail(exc)
362
+ return
363
+ if done is None:
364
+ raise typer.BadParameter("connect claude or codex")
365
+ for line in done:
366
+ typer.echo(f"✓ {line}")
367
+
368
+
369
+ for _action, _help in (
370
+ ("pause", "Pause a session (state is kept)."),
371
+ ("stop", "Stop a session's driver and lab."),
372
+ ("start", "Start a session's driver."),
373
+ ):
374
+
375
+ def _make(action: str) -> Any:
376
+ def command(session: Session = None) -> None:
377
+ try:
378
+ _control().action(_session(session), action)
379
+ except WspxError as exc:
380
+ _fail(exc)
381
+ typer.echo(f"{action}: ok")
382
+
383
+ return command
384
+
385
+ app.command(_action, help=_help)(_make(_action))
386
+
387
+
388
+ @app.command()
389
+ def steer(text: Annotated[str, typer.Argument()], session: Session = None) -> None:
390
+ """Send a message to the driver of a running session."""
391
+ try:
392
+ _control().action(_session(session), "inject", text=text)
393
+ except WspxError as exc:
394
+ _fail(exc)
395
+ typer.echo("sent")
396
+
397
+
398
+ # ---------------------------------------------------------------------- tools (§4.2)
399
+
400
+
401
+ @app.command()
402
+ def info(
403
+ session: Session = None, handles: Annotated[bool, typer.Option("--handles")] = False
404
+ ) -> None:
405
+ """Model outline: blocks, layer types, residual stream, tying, coverage."""
406
+ _tool(session, "info", {"handles": handles})
407
+
408
+
409
+ @app.command()
410
+ def ls(
411
+ scope: Annotated[str, typer.Argument()] = "L*.*",
412
+ session: Session = None,
413
+ role: Annotated[str | None, typer.Option("--role")] = None,
414
+ layers: Annotated[str | None, typer.Option("--layers")] = None,
415
+ ) -> None:
416
+ """List addresses matching a scope."""
417
+ _tool(session, "ls", {"scope": scope, "role": role, "layers": layers})
418
+
419
+
420
+ @app.command()
421
+ def grep(
422
+ expression: Annotated[str | None, typer.Argument()] = None,
423
+ session: Session = None,
424
+ scope: Annotated[str | None, typer.Option("--in")] = None,
425
+ axis: Annotated[str | None, typer.Option("--axis")] = None,
426
+ top: Annotated[int, typer.Option("--top")] = 20,
427
+ name: Annotated[str | None, typer.Option("--as")] = None,
428
+ fires_on: Annotated[str | None, typer.Option("--fires-on")] = None,
429
+ ) -> None:
430
+ """Search weights for units matching an expression (or firing on prompts)."""
431
+ _tool(
432
+ session,
433
+ "grep",
434
+ {
435
+ "expression": expression,
436
+ "in": scope,
437
+ "axis": axis,
438
+ "top": top,
439
+ "name": name,
440
+ "fires_on": fires_on,
441
+ },
442
+ )
443
+
444
+
445
+ @app.command()
446
+ def show(
447
+ address: Annotated[str, typer.Argument()],
448
+ session: Session = None,
449
+ values: Annotated[int | None, typer.Option("--values")] = None,
450
+ ) -> None:
451
+ """Summarise a slice of weights."""
452
+ _tool(session, "show", {"address": address, "values": values})
453
+
454
+
455
+ @app.command()
456
+ def contrast(
457
+ positive: Annotated[str, typer.Argument(help=".jsonl of prompts with the behaviour")],
458
+ negative: Annotated[str, typer.Argument(help=".jsonl of prompts without it")],
459
+ name: Annotated[str, typer.Option("--name")],
460
+ session: Session = None,
461
+ layer: Annotated[int | None, typer.Option("--layer")] = None,
462
+ ) -> None:
463
+ """Build a direction from two prompt sets."""
464
+ _tool(
465
+ session,
466
+ "contrast",
467
+ {"positive": positive, "negative": negative, "name": name, "layer": layer},
468
+ )
469
+
470
+
471
+ @app.command()
472
+ def generate(
473
+ prompt: Annotated[str, typer.Argument()],
474
+ session: Session = None,
475
+ max_tokens: Annotated[int, typer.Option("--max-tokens")] = 64,
476
+ temperature: Annotated[float, typer.Option("--temperature")] = 0.0,
477
+ ) -> None:
478
+ """Sample from the current working tree."""
479
+ _tool(
480
+ session,
481
+ "generate",
482
+ {"prompt": prompt, "max_tokens": max_tokens, "temperature": temperature},
483
+ )
484
+
485
+
486
+ @app.command()
487
+ def trace(
488
+ prompt: Annotated[str, typer.Argument()],
489
+ session: Session = None,
490
+ vs: Annotated[str | None, typer.Option("--vs")] = None,
491
+ reference: Annotated[str | None, typer.Option("--reference")] = None,
492
+ target: Annotated[str | None, typer.Option("--target")] = None,
493
+ ) -> None:
494
+ """Forward, diff (--vs) or attribution (--reference) trace."""
495
+ _tool(session, "trace", {"prompt": prompt, "vs": vs, "reference": reference, "target": target})
496
+
497
+
498
+ @app.command()
499
+ def edit(
500
+ op: Annotated[str, typer.Argument()],
501
+ args: Annotated[
502
+ list[str] | None, typer.Argument(help="key=value; values are JSON when they parse")
503
+ ] = None,
504
+ session: Session = None,
505
+ precision: Annotated[str, typer.Option("--precision")] = "merged",
506
+ scope: Annotated[str | None, typer.Option("--scope")] = None,
507
+ ) -> None:
508
+ """Stage an edit op, e.g. `wspx edit project_out direction=dir:loop targets=L19.mlp.down cols=@r1`."""
509
+ parsed: dict[str, Any] = {}
510
+ for item in args or []:
511
+ key, sep, raw = item.partition("=")
512
+ if not sep:
513
+ raise typer.BadParameter(f"{item!r}: expected key=value")
514
+ try:
515
+ parsed[key] = json.loads(raw)
516
+ except json.JSONDecodeError:
517
+ parsed[key] = raw
518
+ _tool(session, "edit", {"op": op, "args": parsed, "precision": precision, "scope": scope})
519
+
520
+
521
+ @app.command()
522
+ def check(
523
+ session: Session = None,
524
+ patch: Annotated[str | None, typer.Option("--patch")] = None,
525
+ level: Annotated[str, typer.Option("--level")] = "smoke",
526
+ ) -> None:
527
+ """Diagnostics for staged edits."""
528
+ _tool(session, "check", {"patch": patch, "level": level})
529
+
530
+
531
+ @app.command("test")
532
+ def run_suites(
533
+ suite: Annotated[str | None, typer.Argument()] = None,
534
+ session: Session = None,
535
+ vs: Annotated[str | None, typer.Option("--vs")] = None,
536
+ ) -> None:
537
+ """Run suites (paired against --vs)."""
538
+ _tool(session, "test", {"suite": suite, "vs": vs})
539
+
540
+
541
+ @app.command()
542
+ def vcs(
543
+ action: Annotated[
544
+ str,
545
+ typer.Argument(
546
+ help="status, diff, commit, log, checkout, branch, revert, bisect, blame, merge"
547
+ ),
548
+ ],
549
+ target: Annotated[str | None, typer.Argument(help="revision, branch, address or suite")] = None,
550
+ session: Session = None,
551
+ message: Annotated[str | None, typer.Option("--message", "-m")] = None,
552
+ force: Annotated[bool, typer.Option("--force")] = False,
553
+ ) -> None:
554
+ """Version control of weight edits."""
555
+ args: dict[str, Any] = {"action": action, "message": message, "force": force}
556
+ key = {
557
+ "checkout": "rev",
558
+ "revert": "rev",
559
+ "log": "rev",
560
+ "branch": "name",
561
+ "merge": "name",
562
+ "blame": "address",
563
+ "bisect": "suite",
564
+ "diff": "a",
565
+ }.get(action)
566
+ if key and target:
567
+ args[key] = target
568
+ _tool(session, "vcs", args)
569
+
570
+
571
+ @app.command()
572
+ def export(
573
+ kind: Annotated[str, typer.Argument(help="merged, peft, gguf or bundle")],
574
+ path: Annotated[str, typer.Argument()],
575
+ session: Session = None,
576
+ ) -> None:
577
+ """Export the working tree."""
578
+ _tool(session, "export", {"kind": kind, "path": path})
579
+
580
+
581
+ @app.command()
582
+ def run(script: Annotated[str, typer.Argument()], session: Session = None) -> None:
583
+ """Run a script in the lab with the SDK preloaded."""
584
+ _tool(session, "run", {"script": script})
585
+
586
+
587
+ # ---------------------------------------------------------------------- spend and safety
588
+
589
+
590
+ @limits_app.callback()
591
+ def limits_list(ctx: typer.Context) -> None:
592
+ """Show the limits you have set (none by default)."""
593
+ if ctx.invoked_subcommand is not None:
594
+ return
595
+ try:
596
+ rows = _control().limits()
597
+ except WspxError as exc:
598
+ _fail(exc)
599
+ return
600
+ if not rows:
601
+ typer.echo("no limits are set (wspx never sets any by default)")
602
+ for r in rows:
603
+ typer.echo(f"{r['id']} {r['describe']}")
604
+
605
+
606
+ @limits_app.command("set")
607
+ def limits_set(
608
+ scope: Annotated[str, typer.Argument(help="call, session, day, month, rate or velocity")],
609
+ metric: Annotated[
610
+ str, typer.Argument(help="dollars, calls, turns, input_tokens, output_tokens …")
611
+ ],
612
+ value: Annotated[float, typer.Argument()],
613
+ session: Annotated[str | None, typer.Option("--session")] = None,
614
+ provider: Annotated[str | None, typer.Option("--provider")] = None,
615
+ window: Annotated[
616
+ float | None, typer.Option("--window", help="seconds (rate/velocity)")
617
+ ] = None,
618
+ ) -> None:
619
+ """Set a limit, e.g. `wspx limits set day dollars 50`."""
620
+ body = {
621
+ "scope": scope,
622
+ "metric": metric,
623
+ "value": value,
624
+ "session": session,
625
+ "provider": provider,
626
+ "window_s": window,
627
+ }
628
+ try:
629
+ limit = _control().set_limit({k: v for k, v in body.items() if v is not None})
630
+ except WspxError as exc:
631
+ _fail(exc)
632
+ return
633
+ typer.echo(f"set {limit['id']}")
634
+
635
+
636
+ @limits_app.command("rm")
637
+ def limits_rm(limit_id: Annotated[str, typer.Argument()]) -> None:
638
+ """Remove a limit."""
639
+ try:
640
+ removed = _control().remove_limit(limit_id)
641
+ except WspxError as exc:
642
+ _fail(exc)
643
+ return
644
+ typer.echo("removed" if removed else "no such limit")
645
+
646
+
647
+ @limits_app.command("price")
648
+ def limits_price(
649
+ model: Annotated[str, typer.Argument(help="provider:model")],
650
+ input_price: Annotated[float, typer.Argument(help="$ per million input tokens")],
651
+ output_price: Annotated[float, typer.Argument(help="$ per million output tokens")],
652
+ ) -> None:
653
+ """Set a model's price (needed for dollar limits on models wspx has no price for)."""
654
+ try:
655
+ _control().price(model, input_price, output_price)
656
+ except WspxError as exc:
657
+ _fail(exc)
658
+ typer.echo("price saved")
659
+
660
+
661
+ @app.command()
662
+ def usage(session: Session = None) -> None:
663
+ """Metered spend, per session, provider and model."""
664
+ try:
665
+ data = _control().usage(session)
666
+ except WspxError as exc:
667
+ _fail(exc)
668
+ return
669
+ for g in data.get("groups", []):
670
+ cost = "unknown" if g.get("c") is None else f"${g['c']:.4f}"
671
+ typer.echo(f"{g['session']:<12} {g['provider']}:{g['model']:<28} {g['n']:>5} calls {cost}")
672
+ typer.echo(
673
+ f"total charged ${data.get('total_charged', 0):.4f} · held ${data.get('held', 0):.4f}"
674
+ )
675
+
676
+
677
+ @app.command()
678
+ def doctor() -> None:
679
+ """Which limits are set, what is running, and where each provider's own caps live."""
680
+ cfg = cli_config.load()
681
+ modal_ok = (Path.home() / ".modal.toml").exists()
682
+ typer.echo(f"modal token: {'found' if modal_ok else 'missing (run `wspx login`)'}")
683
+ typer.echo(f"deployment: {cfg.url or 'none (run `wspx deploy`)'}")
684
+ if not cfg.url:
685
+ return
686
+ try:
687
+ data = _control().doctor()
688
+ except WspxError as exc:
689
+ _fail(exc)
690
+ return
691
+ limits = data["limits"]
692
+ typer.echo(
693
+ "limits: "
694
+ + (
695
+ "none set"
696
+ if limits == []
697
+ else json.dumps(limits)
698
+ if isinstance(limits, str)
699
+ else "; ".join(lim["describe"] for lim in limits)
700
+ )
701
+ )
702
+ typer.echo(f"active sessions: {len(data['active'])}" + (" · HALTED" if data["halted"] else ""))
703
+ for provider, url in data["provider_caps"].items():
704
+ typer.echo(f" {provider} spend caps: {url}")
705
+
706
+
707
+ @app.command()
708
+ def kill(
709
+ session: Annotated[str | None, typer.Argument()] = None,
710
+ all_: Annotated[
711
+ bool, typer.Option("--all", help="Stop everything and set the halt flag.")
712
+ ] = False,
713
+ hard: Annotated[bool, typer.Option("--hard", help="Use only your Modal token.")] = False,
714
+ ) -> None:
715
+ """Kill switch: stop sessions and release every GPU."""
716
+ if hard:
717
+ from wspx.safety.kill import hard_kill
718
+
719
+ report = hard_kill()
720
+ typer.echo(
721
+ f"terminated {len(report.terminated)} sandbox(es); app stopped: {report.app_stopped}"
722
+ )
723
+ for err in report.errors:
724
+ typer.secho(f" {err}", fg=typer.colors.YELLOW)
725
+ return
726
+ if not session and not all_:
727
+ raise typer.BadParameter("name a session or pass --all")
728
+ try:
729
+ n = _control().kill(None if all_ else session)
730
+ except WspxError as exc:
731
+ _fail(exc)
732
+ return
733
+ typer.echo(
734
+ f"stopped {n} session(s)" + (" and halted wspx; `wspx resume` to continue" if all_ else "")
735
+ )
736
+
737
+
738
+ @app.command()
739
+ def resume(session: Annotated[str | None, typer.Argument()] = None) -> None:
740
+ """Resume after a halt, a limit or a loop stop. Human only."""
741
+ try:
742
+ _control().resume(session)
743
+ except WspxError as exc:
744
+ _fail(exc)
745
+ typer.echo("resumed")
746
+
747
+
748
+ # ---------------------------------------------------------------------- stores on the Hub
749
+
750
+
751
+ @app.command()
752
+ def push(
753
+ repo: Annotated[str, typer.Argument(help="hf://user/repo")],
754
+ store: Annotated[Path, typer.Option("--store")] = Path("wspx-store"),
755
+ ) -> None:
756
+ """Share a store (objects, refs, IR and index) through a Hugging Face Hub repo."""
757
+ from huggingface_hub import HfApi
758
+
759
+ name = repo.removeprefix("hf://")
760
+ api = HfApi()
761
+ api.create_repo(name, repo_type="dataset", exist_ok=True, private=True)
762
+ api.upload_folder(
763
+ folder_path=str(store),
764
+ repo_id=name,
765
+ repo_type="dataset",
766
+ allow_patterns=["objects/**", "refs/heads/**", "models/**"],
767
+ )
768
+ typer.echo(f"pushed {store} to {repo}")
769
+
770
+
771
+ @app.command()
772
+ def clone(
773
+ repo: Annotated[str, typer.Argument(help="hf://user/repo")],
774
+ store: Annotated[Path, typer.Option("--store")] = Path("wspx-store"),
775
+ ) -> None:
776
+ """Fetch a store from a Hugging Face Hub repo."""
777
+ from huggingface_hub import snapshot_download
778
+
779
+ snapshot_download(repo.removeprefix("hf://"), repo_type="dataset", local_dir=str(store))
780
+ typer.echo(f"cloned {repo} into {store}")
781
+
782
+
783
+ # ---------------------------------------------------------------------- local serving and adapters
784
+
785
+
786
+ @app.command()
787
+ def serve(
788
+ store: Annotated[Path, typer.Option("--store")] = Path("wspx-store"),
789
+ port: Annotated[int, typer.Option("--port")] = 8765,
790
+ token: Annotated[str | None, typer.Option("--token", envvar="WSPX_TOKEN")] = None,
791
+ ) -> None:
792
+ """Run the control plane locally with in-process labs (needs the lab extra)."""
793
+ import secrets
794
+
795
+ import uvicorn
796
+
797
+ from wspx.auth import new_secret
798
+ from wspx.control.app import ControlSettings, create_app
799
+ from wspx.control.backend import LocalBackend
800
+
801
+ token = token or "wspx_" + secrets.token_urlsafe(18)
802
+ url = f"http://127.0.0.1:{port}"
803
+ settings = ControlSettings(
804
+ store_root=str(store), api_token=token, secret=new_secret(), public_url=url
805
+ )
806
+ cfg = cli_config.load()
807
+ cfg.url, cfg.token = url, token
808
+ cli_config.save(cfg)
809
+ typer.echo(f"wspx control plane on {url} (token saved to {cli_config.path()})")
810
+ uvicorn.run(
811
+ create_app(settings, LocalBackend(store)), host="127.0.0.1", port=port, log_level="warning"
812
+ )
813
+
814
+
815
+ @app.command()
816
+ def mcp() -> None:
817
+ """A local stdio MCP server that forwards to the hosted control plane (for Codex)."""
818
+ from wspx.control.mcp_server import run_stdio
819
+
820
+ cfg = cli_config.require(cli_config.load())
821
+ control = Control(cfg.url, cfg.token)
822
+ root = _project_root()
823
+
824
+ def call(session: str | None, name: str, args: dict[str, Any]) -> dict[str, Any]:
825
+ try:
826
+ return control.tool(session or cfg.current(root), name, args)
827
+ except WspxError as exc:
828
+ return {"summary": str(exc), "ok": False}
829
+
830
+ run_stdio(call)
831
+
832
+
833
+ @hook_app.command("codex")
834
+ def hook_codex() -> None:
835
+ """Forward a Codex hook payload (stdin) to the wspx trace."""
836
+ cfg = cli_config.load()
837
+ try:
838
+ payload = json.loads(sys.stdin.read() or "{}")
839
+ if cfg.url and cfg.token:
840
+ Control(cfg.url, cfg.token).ingest(
841
+ "codex", payload, cfg.current(_project_root()) or None
842
+ )
843
+ except (WspxError, json.JSONDecodeError):
844
+ pass # a hook must never break the agent; the call log stays authoritative
845
+
846
+
847
+ if __name__ == "__main__":
848
+ app()