6from __future__
import annotations
11from pathlib
import Path
14_CONFIG_PATH = Path.home() /
".aquin" /
"config.json"
15_BASE_URL =
"https://api.aquin.app"
19 if _CONFIG_PATH.exists():
20 with open(_CONFIG_PATH)
as f:
26 _CONFIG_PATH.parent.mkdir(parents=
True, exist_ok=
True)
27 with open(_CONFIG_PATH,
"w")
as f:
28 json.dump(data, f, indent=2)
32 """Optional cloud token from env / legacy config — not required for local use."""
34 return resolve_api_key(explicit=explicit)
38 """aquin status — loaded model and local engine state"""
43 if args[i] ==
"--plain":
46 elif args[i] ==
"--json":
49 elif args[i]
in (
"--api-key",
"-k",
"--live"):
50 print(f
"Removed flag: {args[i]} (no account auth in this framework).", file=sys.stderr)
52 elif args[i]
in (
"--help",
"-h",
"help"):
53 print(
"Usage: aquin status [--plain] [--json]")
55 print(
" Show loaded model and local engine state.")
56 print(
" --plain ASCII bullets (no color)")
57 print(
" --json Machine-readable rows")
60 print(f
"Unknown flag: {args[i]}", file=sys.stderr)
65 snap = collect_status_snapshot(logged_in=
False)
68 print(json.dumps(status_payload(snap), ensure_ascii=
False))
71 render_status(snap, plain=plain)
75 """aquin version — show the installed CLI version"""
76 if args
and args[0]
in (
"--help",
"-h",
"help"):
77 print(
"Usage: aquin version [--json]")
79 print(
" Show the installed CLI build version.")
80 print(
" --json Machine-readable")
86 print(json.dumps(version_payload(), ensure_ascii=
False))
93 """Show the AQIT Apache 2.0 license"""
94 if args
and args[0]
in (
"--help",
"-h",
"help"):
95 print(
"Usage: aqit license [--json] [--plain]")
97 print(
" Display the AQIT Apache License 2.0.")
98 print(
" --json Machine-readable text + acceptance status")
99 print(
" --plain Full ASCII frame (legacy layout)")
106 as_json =
"--json" in args
107 plain =
"--plain" in args
108 text = read_license_text()
109 accepted = is_license_accepted()
110 record = (load_config().get(
"license_accepted")
or {})
if accepted
else {}
111 accepted_at = str(record.get(
"accepted_at")
or "")
if isinstance(record, dict)
else ""
115 sys.stdout.reconfigure(encoding=
"utf-8")
119 "accepted": accepted,
120 "acceptedAt": accepted_at
or None,
123 }, ensure_ascii=
False))
129 render_license_document(context=
"view")
134 sys.stdout.reconfigure(encoding=
"utf-8")
137 print(f
"license {LICENSE_URL}")
140 print(f
"accepted {accepted_at}")
144 print(
"not accepted")
146 print(
"full text: aquin license --plain")
150 """aquin update — upgrade aquin to the latest version from PyPI"""
152 from importlib.metadata
import PackageNotFoundError, version
154 if args
and args[0]
in (
"--help",
"-h",
"help"):
155 print(
"Usage: aquin update [--json]")
157 print(
" Upgrade the Aquin engine package from PyPI.")
158 print(
" --json Machine-readable result (npm CLI)")
161 as_json =
"--json" in args
164 current = version(
"aquin")
165 except PackageNotFoundError:
169 print(f
"Current version: {current}")
170 print(
"Checking for updates...")
172 result = subprocess.run(
173 [sys.executable,
"-m",
"pip",
"install",
"--upgrade",
"aquin"],
178 if result.returncode != 0:
179 err = (result.stderr
or result.stdout
or "Update failed.")[-1000:]
184 "error": err.strip()
or "Update failed.",
185 }, ensure_ascii=
False))
187 print(
"Update failed:")
193 import importlib.metadata
as _meta
195 importlib.invalidate_caches()
196 new = _meta.version(
"aquin")
200 updated = new != current
207 }, ensure_ascii=
False))
211 print(f
"Updated to {new}")
213 print(
"Already up to date.")
217 """Return (os_label, arch) for desktop install messaging."""
220 system = platform.system()
221 machine = (platform.machine()
or "").lower()
222 if machine
in (
"x86_64",
"amd64"):
224 elif machine
in (
"aarch64",
"arm64"):
226 elif machine
in (
"i386",
"i686",
"x86"):
229 arch = machine
or "unknown"
231 if system ==
"Darwin":
233 if system ==
"Windows":
234 return "Windows", arch
235 if system ==
"Linux":
237 return system
or "Unknown OS", arch
241 """aquin desktop install — install the Aquin desktop app (stub until releases ship)."""
242 if not args
or args[0]
in (
"--help",
"-h",
"help"):
243 print(
"Usage: aquin desktop install")
245 print(
" Detect this machine's OS, confirm, then install Aquin desktop.")
246 print(
" Download packaging is not published yet; yes only acknowledges for now.")
249 if args[0] !=
"install":
250 print(f
"Unknown desktop subcommand: {args[0]}")
251 print(
"Usage: aquin desktop install")
255 if rest
and rest[0]
in (
"--help",
"-h",
"help"):
256 print(
"Usage: aquin desktop install")
258 print(
" Detect this machine's OS, confirm, then install Aquin desktop.")
259 print(
" Download packaging is not published yet; yes only acknowledges for now.")
263 print(f
"Detected: {os_label} ({arch})")
265 answer = input(
"Install Aquin desktop on this machine? [y/N] ").strip().lower()
270 if answer
not in (
"y",
"yes"):
275 print(f
"Desktop install for {os_label} ({arch}) will download and install here when builds ship.")
278def cmd_list(args: list[str]) ->
None:
279 """aquin list simulation"""
281 print(
"Usage: aquin list simulation")
283 if args[0]
in (
"model",
"models"):
284 print(
"Removed. Pass a HuggingFace model id to aquin load model <id>.", file=sys.stderr)
286 if args[0]
in (
"sae",
"saes"):
287 print(
"Removed. Use: aquin load sae <model-l{n}> | --user <name> | --path <file>", file=sys.stderr)
289 if args[0]
in (
"watch",
"watches"):
290 print(
"Removed. Training watch is no longer part of the CLI.", file=sys.stderr)
291 print(
"Use the SDK: aquin.init() / run.log() → ./aquin_run/", file=sys.stderr)
293 if args[0] ==
"simulation":
296 if args[0] ==
"simulations":
297 print(
"Use: aquin list simulation", file=sys.stderr)
299 print(
"Usage: aquin list simulation")
303def cmd_info(args: list[str]) ->
None:
304 """aquin info sae <model-l{layer}>"""
305 if not args
or args[0] !=
"sae" or "--help" in args
or "-h" in args:
306 print(
"Usage: aquin info sae <model-l{n}> [--json] [--plain]")
307 print(
"Example: aquin info sae pythia-70m-l3")
309 print(
" --json Machine-readable fields")
310 print(
" --plain Rich table layout")
311 if args
and args[0] ==
"sae" and (
"--help" in args
or "-h" in args):
315 as_json =
"--json" in args
316 plain =
"--plain" in args
317 rest = [a
for a
in args[1:]
if a
not in (
"--json",
"--plain")]
319 print(
"Usage: aquin info sae <model-l{n}> [--json] [--plain]")
325 render_info_sae_quiet,
332 sys.stdout.reconfigure(encoding=
"utf-8")
335 print(json.dumps(info_sae_payload(r), ensure_ascii=
False))
340 render_info_sae_quiet(r)
344 """Default ~/.aquin/sae/... path for aquin load sae <model-l{n}>."""
349 m = re.match(
r"^(.+)-l(\d+)$", sae_id)
352 model_slug, layer_s = m.group(1), int(m.group(2))
354 model_id = resolve_model_id(model_slug)
357 return resolve_sae_path(model_id, layer_s)
362 if stem.startswith(
"sae_layer"):
364 return int(stem.replace(
"sae_layer",
""))
372 print(
" aquin load sae <model-l{n}> pull catalog SAE")
373 print(
" aquin load sae --user <name> [--layer N] activate user-trained SAE")
374 print(
" aquin load sae --path <file.pt> [--layer N] [--model <id>] # self-hosted weights")
377 print(
" aquin load sae gpt2-small-l8")
378 print(
" aquin sae train --layer 8 --name my-run")
379 print(
" aquin load sae --user my-run --layer 8")
380 print(
" aquin info sae <model-l{n}>")
384 """Best-effort: cache the SAE in the persistent daemon so tools reuse it."""
386 from .engine
import model_daemon
388 if model_daemon.is_running():
389 model_daemon.warm_sae(model_id, int(layer))
395 """aquin load sae <model-l{n}> | --user <name> | --path <file>"""
396 if not args
or args[0]
in (
"-h",
"--help",
"help"):
400 user_name: str |
None =
None
401 path_arg: str |
None =
None
402 layer: int |
None =
None
403 model_id: str |
None =
None
404 explicit_key: str |
None =
None
406 explicit_output =
False
408 positional: list[str] = []
413 if a
in (
"--force",
"-f"):
416 elif a ==
"--user" and i + 1 < len(args):
417 user_name = args[i + 1]
419 elif a ==
"--path" and i + 1 < len(args):
420 path_arg = args[i + 1]
422 elif a ==
"--layer" and i + 1 < len(args):
423 layer = int(args[i + 1])
425 elif a ==
"--model" and i + 1 < len(args):
426 model_id = args[i + 1]
428 elif a ==
"--key" and i + 1 < len(args):
429 explicit_key = args[i + 1]
431 elif a.startswith(
"--"):
432 print(f
"Unknown flag: {a}", file=sys.stderr)
443 sae_path = resolve_user_sae_path(locked, user_name, layer)
444 except (FileNotFoundError, ValueError)
as exc:
445 print(f
"Error: {exc}", file=sys.stderr)
448 if resolved_layer
is None:
449 print(
"Error: could not infer SAE layer. Pass --layer <n>.", file=sys.stderr)
451 binding = activate_user_sae(
453 layer=resolved_layer,
457 print(f
"Active user SAE: {user_name} layer {resolved_layer}")
458 print(f
" model: {binding['model_id']}")
459 print(f
" path: {binding['path']}")
467 sae_path, resolved_model, resolved_layer = resolve_path_sae(
472 except (FileNotFoundError, ValueError)
as exc:
473 print(f
"Error: {exc}", file=sys.stderr)
475 binding = activate_user_sae(
476 model_id=resolved_model,
477 layer=resolved_layer,
479 name=sae_path.parent.name,
481 print(f
"Active user SAE from {sae_path}")
482 print(f
" model: {binding['model_id']} layer: {resolved_layer}")
492 from .saes
import pull_sae
494 sae_id = positional[0]
495 if not explicit_output:
497 if default_out
is not None:
498 output = str(default_out)
500 m = re.match(
r"^(.+)-l(\d+)$", sae_id)
502 model_slug, layer_s = m.group(1), int(m.group(2))
503 resolved_catalog: str |
None =
None
510 resolved_catalog = resolve_model_id(model_slug)
512 resolved_catalog =
None
520 sae_path = resolve_sae_path(resolved_catalog, cfg_layer)
521 if sae_path.is_file()
and not force:
522 if is_valid_sae_checkpoint_path(sae_path):
523 clear_active_binding()
524 print(f
"SAE already on disk: {sae_path}")
527 print(f
"Removing invalid catalog SAE cache: {sae_path}", file=sys.stderr)
528 sae_path.unlink(missing_ok=
True)
529 norm_stale = sae_path.parent / f
"norm_layer{cfg_layer}.pt"
530 if norm_stale.is_file():
531 norm_stale.unlink(missing_ok=
True)
532 elif sae_path.is_file()
and force:
533 print(f
"Re-downloading catalog SAE (--force): {sae_path}", file=sys.stderr)
534 sae_path.unlink(missing_ok=
True)
535 norm_stale = sae_path.parent / f
"norm_layer{cfg_layer}.pt"
536 if norm_stale.is_file():
537 norm_stale.unlink(missing_ok=
True)
539 print(f
"Pulling SAE {resolved_catalog}-l{cfg_layer} from Aquin catalog...")
540 pull_sae(f
"{resolved_catalog}-l{cfg_layer}", sae_path, api_key)
541 clear_active_binding()
546 print(f
"Loading SAE {sae_id}...")
547 pull_sae(sae_id, output, api_key)
552 """Return the loaded model id, or exit."""
553 from .compute.model_loader
import get_active_model_id, resolve_model_id
555 active = (get_active_model_id()
or "").strip()
557 print(
"Error: no model loaded.")
558 print(
" Run: aquin load model <model-id>")
561 return resolve_model_id(active)
567 """Alias — session lock removed; uses loaded model."""
573 while i < len(raw_args):
574 if raw_args[i] ==
"--model" and i + 1 < len(raw_args):
575 print(
"Error: --model is not supported here.")
576 print(
" Run: aquin load model <id>")
582 """Local tool context for GPU dispatch + command tracking."""
583 from .engine.main
import _load_state
584 from .compute.model_loader
import get_active_model_id, resolve_model_id
586 state = _load_state()
589 api_key = state.get(
"api_key")
or resolve_api_key(allow_missing=
True)
591 api_key = state.get(
"api_key")
or ""
592 base_url = (state.get(
"base_url")
or os.environ.get(
"AQUIN_BASE_URL", _BASE_URL)).rstrip(
"/")
593 active = model_id
or get_active_model_id()
or ""
596 active = resolve_model_id(active)
600 local_mem = load_local_memory(
"local")
604 "base_url": base_url,
606 "activeModelId": active,
613 """aquin trace --prompt <text> --layer <n> [--check] [--umap]"""
616 if not args
or args[0]
in (
"-h",
"--help",
"help")
or "-h" in args
or "--help" in args:
617 print(
"Full attribution for one prompt: generate, SAE features, causal trace, logit lens.")
619 print(
"Usage: aquin trace --prompt <text> --layer <n> [--check] [--umap]")
621 print(
" --prompt Input prompt (model completes from here).")
622 print(
" --layer SAE layer with a downloaded checkpoint.")
623 print(
" --check Save trace-check.json and trace-check.png in cwd.")
624 print(
" --umap Load SAE UMAP projection after the run (web explorer).")
626 print(
"Docs: https://aquin.app/docs/inspection-sae/llm")
629 reject_legacy_output_flags(args)
630 print(
"[trace] starting...", flush=
True)
634 prompt = tool_args.get(
"prompt")
635 layer_raw = tool_args.get(
"layer")
636 layer: int |
None = int(layer_raw)
if layer_raw
is not None else None
637 do_check = bool(tool_args.get(
"check"))
or "--check" in args
641 print(
"Usage: aquin trace --prompt <text> --layer <n> [--check] [--umap]")
648 mid = resolve_model_id(mid)
649 except ValueError
as e:
650 print(f
"Error: {e}"); sys.exit(1)
652 format_sae_layer_choice_message(
655 example_suffix=f
'--prompt "{str(prompt)[:60]}"',
661 from .compute.model_loader
import resolve_model_id, ComputeNotAvailableError, require_sae_layer
662 from .compute.loader_shim
import apply
as _shim_apply
663 from .engine.sync_dispatch
import run_dispatch
667 mid = resolve_model_id(mid)
668 except ValueError
as e:
669 print(f
"Error: {e}"); sys.exit(1)
672 layer = require_sae_layer(
676 example_suffix=f
'--prompt "{str(prompt)[:60]}"',
678 except ValueError
as e:
679 print(str(e), file=sys.stderr)
684 ctx[
"state"][
"activeModelId"] = mid
687 print(f
"[trace] running full inspection (sae layer {layer})...")
688 result = run_dispatch(
689 "run_full_inspection",
690 {
"prompt": prompt,
"layer": layer},
695 if isinstance(result, dict)
and result.get(
"error"):
696 print(result[
"error"]); sys.exit(1)
698 content = result.get(
"content", {})
if isinstance(result, dict)
else {}
699 card_data = (result.get(
"card")
or {}).get(
"data", {})
if isinstance(result, dict)
else {}
700 response = content.get(
"response")
or card_data.get(
"response",
"")
701 top_features = content.get(
"top_features")
or card_data.get(
"topFeatures", [])
702 prompt_tokens = card_data.get(
"promptTokens", [])
703 response_tokens = card_data.get(
"responseTokens", [])
704 attribution = card_data.get(
"attribution", [])
705 sae_layer = content.get(
"sae_layer")
or card_data.get(
"saeLayer",
"?")
706 if sae_layer != layer:
708 f
"Error: trace used SAE layer {sae_layer} but --layer {layer} was requested.",
712 logit_lens = card_data.get(
"logitLensResults", [])
714 print(f
"[trace] response: {response!r}\n")
716 print(f
"prompt tokens : {prompt_tokens}")
717 print(f
"response tokens: {response_tokens}")
718 print(f
"sae layer : {sae_layer}")
719 print(f
"\ntop response features ({len(top_features)}):")
720 for f
in top_features[:10]:
721 ref = f.get(
"feature_ref")
or f[
"feature_idx"]
722 print(f
" [{ref}] act={f['activation']:.3f} token={f.get('token', '')!r}")
725 print(f
"\nattribution ({len(attribution)} response tokens with driven features):")
726 for a
in attribution[:5]:
728 f
"{d.get('feature_ref') or d['feature_idx']}({d['activation']:.2f})"
729 for d
in a.get(
"driven_by_features", [])[:3]
731 print(f
" {a.get('response_token', ''):>12} <- {driven}")
734 print(f
"\nlogit lens ({len(logit_lens)} layers), last 3 layers:")
735 for row
in logit_lens[-3:]:
736 tops =
" ".join(f
"{t['token']!r}({t['prob']:.3f})" for t
in row.get(
"top_tokens", [])[:3])
737 print(f
" layer {row['layer']:>2}: {tops}")
740 from .trace_check
import write_trace_check
742 json_path, png_path = write_trace_check(
743 result, tool_name=
"run_full_inspection", cwd=os.getcwd(),
745 print(f
"Saved {json_path}")
746 print(f
"Saved {png_path}")
747 except Exception
as exc:
748 from .user_errors
import die
749 die(message=
"Could not save check output files.", exc=exc, label=
"trace --check")
755 tool_args={
"layer": layer},
760 except ComputeNotAvailableError
as e:
761 from .user_errors
import die
762 die(str(e)
or "Compute is not available on this machine.")
763 except Exception
as e:
764 from .user_errors
import die
769 """aquin feature logit --feature <idx> [--layer <n>] [--topk <n>] [--check] [--umap]"""
770 if not args
or args[0]
in (
"-h",
"--help",
"help")
or "-h" in args
or "--help" in args:
771 print(
"Usage: aquin feature logit --feature <idx> [--layer <n>] [--topk <n>] [--check] [--umap]")
783 if args[i] ==
"--feature" and i + 1 < len(args):
784 feature_idx = int(args[i + 1]); i += 2
785 elif args[i] ==
"--layer" and i + 1 < len(args):
786 layer = int(args[i + 1]); i += 2
787 elif args[i]
in (
"--topk",
"--top-k")
and i + 1 < len(args):
788 top_k = int(args[i + 1]); i += 2
789 elif args[i] ==
"--check":
790 do_check =
True; i += 1
791 elif args[i] ==
"--umap":
792 want_umap =
True; i += 1
796 if feature_idx
is None:
797 print(
"Usage: aquin feature logit --feature <idx> [--layer <n>] [--topk <n>] [--check] [--umap]")
800 from .compute.model_loader
import resolve_model_id, ComputeNotAvailableError
801 from .engine.sync_dispatch
import run_dispatch
806 mid = resolve_model_id(mid)
807 except ValueError
as e:
808 print(f
"Error: {e}"); sys.exit(1)
809 ctx[
"state"][
"activeModelId"] = mid
811 tool_args: dict[str, Any] = {
"feature_idx": feature_idx,
"top_k": top_k}
812 if layer
is not None:
813 tool_args[
"layer"] = layer
816 result = run_dispatch(
"get_feature_logits", tool_args, ctx, command=
"feature logit", ensure_model=mid)
817 if isinstance(result, dict)
and result.get(
"error"):
818 print(f
"Error: {result['error']}"); sys.exit(1)
819 data = result.get(
"content", result)
if isinstance(result, dict)
else result
820 ref = data.get(
"feature_ref")
or feature_idx
821 print(f
"feature {ref} (model={mid} layer={layer or 'default'})")
822 print(f
"\ntop {top_k} boosted tokens:")
823 for t
in data.get(
"top", []):
824 print(f
" {t['token']!r:<20} logit={t['logit']:+.4f}")
825 print(f
"\ntop {top_k} suppressed tokens:")
826 for t
in data.get(
"bottom", []):
827 print(f
" {t['token']!r:<20} logit={t['logit']:+.4f}")
830 from .feature_logits_check
import write_feature_logits_check
832 json_path, png_path = write_feature_logits_check(
833 result, tool_name=
"get_feature_logits", cwd=os.getcwd(),
835 print(f
"Saved {json_path}")
836 print(f
"Saved {png_path}")
837 except Exception
as exc:
838 from .user_errors
import die
839 die(message=
"Could not save check output files.", exc=exc, label=
"feature logit --check")
848 feature_idxs=[feature_idx],
850 except ComputeNotAvailableError
as e:
851 from .user_errors
import die
852 die(str(e)
or "Compute is not available on this machine.")
853 except Exception
as e:
854 from .user_errors
import die
859 """aquin feature neighbor --feature <idx> [--layer <n>] [--topk <n>] [--check] [--umap]"""
860 if not args
or args[0]
in (
"-h",
"--help",
"help")
or "-h" in args
or "--help" in args:
861 print(
"Usage: aquin feature neighbor --feature <idx> [--layer <n>] [--topk <n>] [--check] [--umap]")
873 if args[i] ==
"--feature" and i + 1 < len(args):
874 feature_idx = int(args[i + 1]); i += 2
875 elif args[i] ==
"--layer" and i + 1 < len(args):
876 layer = int(args[i + 1]); i += 2
877 elif args[i]
in (
"--topk",
"--top-k")
and i + 1 < len(args):
878 top_k = int(args[i + 1]); i += 2
879 elif args[i] ==
"--check":
880 do_check =
True; i += 1
881 elif args[i] ==
"--umap":
882 want_umap =
True; i += 1
886 if feature_idx
is None:
887 print(
"Usage: aquin feature neighbor --feature <idx> [--layer <n>] [--topk <n>] [--check] [--umap]")
890 from .compute.model_loader
import resolve_model_id, ComputeNotAvailableError
891 from .engine.sync_dispatch
import run_dispatch
896 mid = resolve_model_id(mid)
897 except ValueError
as e:
898 print(f
"Error: {e}"); sys.exit(1)
899 ctx[
"state"][
"activeModelId"] = mid
901 tool_args: dict[str, Any] = {
"feature_idx": feature_idx,
"top_k": top_k}
902 if layer
is not None:
903 tool_args[
"layer"] = layer
906 result = run_dispatch(
"get_feature_neighbors", tool_args, ctx, command=
"feature neighbor", ensure_model=mid)
907 if isinstance(result, dict)
and result.get(
"error"):
908 print(f
"Error: {result['error']}"); sys.exit(1)
909 data = result.get(
"content", result)
if isinstance(result, dict)
else result
910 ref = data.get(
"feature_ref")
or feature_idx
911 print(f
"feature {ref} (model={mid} layer={layer or 'default'})")
912 print(f
"\n{top_k} nearest neighbors:")
913 for n
in data.get(
"neighbors", []):
914 nref = n.get(
"feature_ref")
or n[
"feature_idx"]
915 print(f
" [{nref}] similarity={n['similarity']:.4f}")
918 from .feature_neighbors_check
import write_feature_neighbors_check
920 json_path, png_path = write_feature_neighbors_check(
921 result, tool_name=
"get_feature_neighbors", cwd=os.getcwd(),
923 print(f
"Saved {json_path}")
924 print(f
"Saved {png_path}")
925 except Exception
as exc:
926 from .user_errors
import die
927 die(message=
"Could not save check output files.", exc=exc, label=
"feature neighbor --check")
936 feature_idxs=[feature_idx],
938 except ComputeNotAvailableError
as e:
939 from .user_errors
import die
940 die(str(e)
or "Compute is not available on this machine.")
941 except Exception
as e:
942 from .user_errors
import die
947 """Legacy no-op — web session sync removed."""
952 """Load a model into VRAM. Returns the resolved model id."""
953 from .compute.model_loader
import ComputeNotAvailableError
954 from .compute.model_runtime
import load_weights, resolve_kind, vram_line
955 from .engine.main
import _load_state, _save_state
956 from .load_model_display
import LoadProgress, load_model_payload
957 from .session_mode
import mode_for_model_id, mode_label
960 mode = mode_for_model_id(model_id)
961 except ValueError
as e:
963 print(json.dumps(load_model_payload(
964 model=model_id, mode=
"?", daemon=
False, ok=
False, error=str(e),
965 ), ensure_ascii=
False))
970 label = mode_label(mode)
971 progress =
None if as_json
else LoadProgress(f
"Loading {model_id} · {label}")
972 _push_log(f
"Loading {model_id} ({label})...")
975 resolved, _kind = resolve_kind(model_id)
976 loaded_via_daemon =
False
977 vram: str |
None =
None
978 elapsed: float |
None =
None
981 from .engine
import model_daemon
983 if model_daemon.ensure_running():
985 progress.phase(
"engine ready")
986 res = model_daemon.switch_model(resolved, on_tick=progress)
987 if res
and res.get(
"ok"):
988 loaded_via_daemon =
True
989 vram = res.get(
"vram")
990 elapsed = progress.elapsed()
if progress
else None
991 elif progress
and res
and res.get(
"error"):
992 progress.phase(f
"engine failed · {res['error']}")
994 loaded_via_daemon =
False
996 if not loaded_via_daemon:
998 progress.phase(
"loading weights in-process")
1000 def _on_progress(msg: str, _elapsed: float) ->
None:
1004 resolved = load_weights(model_id, progress=_on_progress
if progress
else None)
1005 elapsed = progress.elapsed()
if progress
else None
1010 print(json.dumps(load_model_payload(
1013 daemon=loaded_via_daemon,
1017 ), ensure_ascii=
False))
1019 tail = f
"Model ready · {model_id}"
1021 tail = f
"{tail} · {vram}"
1024 if loaded_via_daemon:
1025 progress.done(
"resident in background engine", indent=1)
1027 print(tail, flush=
True)
1028 _push_log(f
"Model ready: {model_id} ({label} tools active)")
1029 state = _load_state()
1030 _save_state({**state,
"session_mode": mode,
"active_model_id": model_id})
1032 except ComputeNotAvailableError
as e:
1035 print(json.dumps(load_model_payload(
1036 model=model_id, mode=mode, daemon=
False, ok=
False, error=err,
1037 ), ensure_ascii=
False))
1039 print(f
"Error: {err}")
1042 except ValueError
as e:
1045 print(json.dumps(load_model_payload(
1046 model=model_id, mode=mode, daemon=
False, ok=
False, error=err,
1047 ), ensure_ascii=
False))
1049 print(f
"Error: {err}")
1052 except Exception
as e:
1053 from .user_errors
import friendly_message
1055 err = friendly_message(e)
1057 print(json.dumps(load_model_payload(
1058 model=model_id, mode=mode, daemon=
False, ok=
False, error=err,
1059 ), ensure_ascii=
False))
1061 print(f
"Error: {err}", file=sys.stderr)
1067 """aquin unload [--stop] [--json] — free the resident model's VRAM."""
1068 if args
and args[0]
in (
"--help",
"-h",
"help"):
1069 print(
"Usage: aquin unload [--stop] [--json]")
1071 print(
" Free the loaded model's VRAM (engine stays up by default).")
1072 print(
" --stop Also stop the background engine")
1073 print(
" --json Machine-readable result")
1076 as_json =
"--json" in args
1077 stop_daemon =
"--stop" in args
or "--kill" in args
1078 from .compute.model_runtime
import unload_weights
1079 from .load_model_display
import LoadProgress, unload_payload
1081 progress =
None if as_json
else LoadProgress(
"Unloading model")
1083 daemon_running =
False
1084 message =
"Cleared active model."
1086 from .engine
import model_daemon
1088 daemon_running = model_daemon.is_running()
1092 progress.phase(
"stopping engine")
1093 freed = model_daemon.stop()
1094 message =
"Engine stopped · VRAM released"
1097 progress.phase(
"releasing daemon VRAM")
1098 freed = model_daemon.unload()
1099 message =
"Model unloaded · engine still running"
1101 message =
"No background engine · cleared active model"
1102 except Exception
as exc:
1104 print(json.dumps(unload_payload(
1106 daemon_running=
False,
1107 stopped=stop_daemon,
1109 ), ensure_ascii=
False))
1111 print(f
"Could not reach background engine: {exc}", file=sys.stderr)
1112 message = f
"Engine unreachable · {exc}"
1116 progress.phase(
"releasing local VRAM")
1122 print(json.dumps(unload_payload(
1124 daemon_running=daemon_running
and not stop_daemon,
1125 stopped=stop_daemon,
1127 ), ensure_ascii=
False))
1131 progress.done(message)
1133 print(message, flush=
True)
1136def cmd_load(args: list[str]) ->
None:
1137 """aquin load model <model-id> | sae <model-l{n}>"""
1138 if args
and args[0] ==
"sae":
1143 if rest
and rest[0] ==
"model":
1146 if "--help" in rest
or "-h" in rest
or (rest
and rest[0] ==
"help")
or not rest:
1147 print(
"Usage: aquin load model <model-id> [--json]")
1148 print(
" aquin load <model-id> # legacy shorthand")
1149 print(
" aquin load sae <model-l{n}> | --user <name> | --path <file>")
1151 print(
" --json Machine-readable result")
1153 print(
" Env: AQUIN_DEVICE=cuda|mps|cpu|auto (default: cuda → mps → cpu)")
1154 print(
" AQUIN_ALLOW_CPU=1 slow CPU smoke tests")
1156 print(
" Pass a HuggingFace model id (e.g. meta-llama/Llama-3.2-1B-Instruct)")
1157 if not rest
or "--help" in rest
or "-h" in rest
or rest[0] ==
"help":
1161 if rest[0] ==
"pull":
1162 print(
"Use: aquin load sae", file=sys.stderr)
1165 as_json =
"--json" in rest
1166 rest = [a
for a
in rest
if a !=
"--json"]
1170 while i < len(rest):
1171 if rest[i] ==
"--model" and i + 1 < len(rest):
1172 model_id = rest[i + 1]
1174 elif not rest[i].startswith(
"-")
and model_id
is None:
1181 print(
"Usage: aquin load model <model-id> [--json]")
1182 print(
" Example: aquin load model meta-llama/Llama-3.2-1B-Instruct")
1188def cmd_chat(args: list[str]) ->
None:
1189 """aquin chat — Ink (via npm), Textual detect, or Rich fallback."""
1190 if "--ink-bridge" in args:
1193 run_ink_chat_bridge()
1196 if args
and args[0]
in (
"--help",
"-h",
"help"):
1197 print(
"Usage: aquin chat [--plain]")
1199 print(
" Multi-turn agent chat (requires login + loaded model).")
1200 print(
" --plain Force Rich REPL (skip Ink / Textual)")
1206 cap = detect_tui_capability(argv=[
"aquin",
"chat", *args])
1207 if choose_chat_ui(cap) ==
"tui":
1209 run_chat_fallback(args, capability=cap)
1211 run_chat_fallback(args, capability=cap)
1215 """aquin prompt <text> — quick try-out generation against the loaded model."""
1216 if not args
or args[0]
in (
"--help",
"-h",
"help"):
1217 print(
"Usage: aquin prompt <text>")
1218 print(
" aquin prompting <text>")
1220 print(
" Generate a response from the loaded LLM (try the model).")
1222 print(
" --model <id> Model to use (default: last aquin load)")
1223 print(
" --max-tokens <n> Max new tokens (default: 200)")
1224 print(
" --temperature <t> Sampling temperature (default: 0.7)")
1225 print(
" --json Machine-readable result")
1228 print(
' aquin prompt "Why is the sky blue?"')
1229 print(
" aquin prompting hello")
1230 print(
" aquin prompt --model gpt2-small Tell me a joke")
1233 as_json =
"--json" in args
1234 model_flag: str |
None =
None
1237 text_parts: list[str] = []
1239 while i < len(args):
1244 if a ==
"--model" and i + 1 < len(args):
1245 model_flag = args[i + 1]
1248 if a
in (
"--max-tokens",
"--max_new_tokens")
and i + 1 < len(args):
1249 max_tokens = int(args[i + 1])
1252 if a ==
"--temperature" and i + 1 < len(args):
1253 temperature = float(args[i + 1])
1256 if a.startswith(
"-"):
1257 print(f
"Unknown flag: {a}", file=sys.stderr)
1259 text_parts.append(a)
1262 prompt_text =
" ".join(text_parts).strip()
1264 print(
"Usage: aquin prompt <text>")
1267 from .compute.model_loader
import get_active_model_id
1268 from .prompt_display
import print_prompt_result, prompt_payload
1270 model_id = (model_flag
or get_active_model_id()
or "").strip()
1272 err =
"No model loaded. Run: aquin load model <id>"
1274 print(json.dumps(prompt_payload(
1275 model=
"", prompt=prompt_text, response=
"", ok=
False, error=err,
1276 ), ensure_ascii=
False))
1278 print(f
"Error: {err}", file=sys.stderr)
1284 from .engine
import model_daemon
1286 if model_daemon.is_running():
1287 res = model_daemon.prompt(
1290 max_new_tokens=max_tokens,
1291 temperature=temperature,
1293 if res
and res.get(
"ok"):
1294 response = str(res.get(
"response")
or "")
1295 model_id = str(res.get(
"model_id")
or model_id)
1297 elif res
and res.get(
"error"):
1298 err = str(res[
"error"])
1300 print(json.dumps(prompt_payload(
1301 model=model_id, prompt=prompt_text, response=
"", ok=
False, error=err,
1302 ), ensure_ascii=
False))
1304 print(f
"Error: {err}", file=sys.stderr)
1311 from .compute.causal_trace
import run_chat
1314 from .load_model_display
import print_phase
1315 print_phase(f
"Generating · {model_id}")
1316 response = run_chat(
1319 max_new_tokens=max_tokens,
1320 temperature=temperature,
1322 except Exception
as exc:
1323 from .user_errors
import friendly_message
1325 err = friendly_message(exc)
1327 print(json.dumps(prompt_payload(
1328 model=model_id, prompt=prompt_text, response=
"", ok=
False, error=err,
1329 ), ensure_ascii=
False))
1331 print(f
"Error: {err}", file=sys.stderr)
1335 print(json.dumps(prompt_payload(
1341 ), ensure_ascii=
False))
1344 print_prompt_result(model=model_id, prompt=prompt_text, response=response)
1350from .session_mode
import (
1354 resolve_legacy_verb,
1358_CLI_TOOL_MAP: dict[str, str] = cli_verbs_for_mode(
None)
1362 from .engine.main
import _load_state
1363 return _load_state()
1368 return bool(get_active_model_id())
1372 """Return session mode from the loaded model."""
1373 from .session_mode
import mode_for_active_model
1376 return mode_for_active_model()
1380 from .session_mode
import SHARED_TOOLS, tools_for_mode
1383 m = cli_verbs_for_mode(mode)
1384 if mode
is not None:
1385 allowed = tools_for_mode(mode)
1386 return {verb: tool
for verb, tool
in m.items()
if tool
in allowed}
1388 return {verb: tool
for verb, tool
in m.items()
if tool
in SHARED_TOOLS}
1393 from .session_mode
import normalize_mode
1396 if mode
is not None:
1397 state = {**state,
"session_mode": mode}
1404 print(f
"[{cmd}] requires a loaded model.")
1405 print(
" aquin load model pythia-70m")
1410 print(
" aquin load model pythia-70m")
1414 from .session_mode
import mode_label
1416 verb = resolve_legacy_verb(verb)
1422 print(f
"[{verb}] no model loaded — run:")
1423 print(
" aquin load model llama-3.2-1b")
1425 if mode
is not None and verb_known(verb):
1426 print(f
"[{verb}] not available for the loaded {mode_label(mode)} model.")
1429 print(f
"Unknown command: {verb}")
1430 print(
"Run aquin help to see available commands.")
1435 """Parse CLI flag values: JSON arrays/objects, bools, numbers, or raw strings."""
1436 import json
as _json
1438 if not isinstance(val, str):
1440 stripped = val.strip()
1441 if stripped.startswith((
"[",
"{")):
1443 return _json.loads(stripped)
1444 except _json.JSONDecodeError:
1446 if stripped.lower() ==
"true":
1448 if stripped.lower() ==
"false":
1451 return int(stripped)
1455 return float(stripped)
1462 if tool_args.get(
"topk")
is not None and tool_args.get(
"top_k")
is None:
1463 tool_args[
"top_k"] = tool_args.pop(
"topk")
1464 if tool_args.get(
"topk_retrieval")
is not None and tool_args.get(
"top_k_retrieval")
is None:
1465 tool_args[
"top_k_retrieval"] = tool_args.pop(
"topk_retrieval")
1469 """Parse --key value flags into an args dict."""
1472 reject_legacy_output_flags(raw)
1473 tool_args: dict[str, Any] = {}
1477 if a.startswith(
"--"):
1479 key, _, val = a[2:].partition(
"=")
1482 elif i + 1 < len(raw)
and not raw[i + 1].startswith(
"--"):
1483 key = a[2:].replace(
"-",
"_")
1487 tool_args[a[2:].replace(
"-",
"_")] =
True
1496_UMAP_FOLLOWUP_VERBS: frozenset[str] = frozenset({
1519def _pop_umap_flag(tool_args: dict[str, Any], raw_args: list[str] |
None =
None) -> bool:
1520 wanted = bool(tool_args.pop(
"umap",
False))
1521 if raw_args
and "--umap" in raw_args:
1528 if value
is None or isinstance(value, bool):
1531 except (TypeError, ValueError):
1536 """Collect feature indices from a tool payload / args for UMAP highlighting."""
1537 idxs: list[int] = []
1538 seen: set[int] = set()
1540 def _add(raw: Any) ->
None:
1542 if idx
is None or idx
in seen:
1547 args = tool_args
or {}
1548 for key
in (
"feature_idx",
"feature",
"target_feature_idx",
"chosen_feature_idx"):
1551 if not isinstance(result, dict):
1554 payload = result.get(
"content", result)
if isinstance(result.get(
"content"), dict)
else result
1555 if not isinstance(payload, dict):
1558 for key
in (
"feature_idx",
"feature",
"target_feature_idx",
"chosen_feature_idx"):
1559 _add(payload.get(key))
1561 for key
in (
"top_features",
"rankings",
"neighbors",
"features"):
1562 rows = payload.get(key)
1563 if not isinstance(rows, list):
1566 if isinstance(row, dict):
1567 _add(row.get(
"feature_idx")
or row.get(
"feature")
or row.get(
"idx"))
1569 card = result.get(
"card")
if isinstance(result.get(
"card"), dict)
else None
1571 data = card.get(
"data")
if isinstance(card.get(
"data"), dict)
else {}
1572 _add(data.get(
"featureIdx")
or data.get(
"chosenFeatureIdx"))
1573 for key
in (
"topFeatures",
"rankings",
"neighbors",
"features"):
1574 rows = data.get(key)
1575 if not isinstance(rows, list):
1578 if isinstance(row, dict):
1579 _add(row.get(
"feature_idx")
or row.get(
"featureIdx")
or row.get(
"feature"))
1584def _layer_from_payload(result: Any, tool_args: dict[str, Any] |
None =
None) -> int |
None:
1585 args = tool_args
or {}
1586 for key
in (
"layer",
"sae_layer"):
1590 if not isinstance(result, dict):
1592 payload = result.get(
"content", result)
if isinstance(result.get(
"content"), dict)
else result
1593 if isinstance(payload, dict):
1594 for key
in (
"layer",
"sae_layer"):
1598 card = result.get(
"card")
if isinstance(result.get(
"card"), dict)
else None
1599 if isinstance(card, dict):
1600 data = card.get(
"data")
if isinstance(card.get(
"data"), dict)
else {}
1601 for key
in (
"layer",
"saeLayer",
"sae_layer"):
1609 ctx: dict[str, Any],
1612 tool_args: dict[str, Any] |
None =
None,
1613 ensure_model: str |
None =
None,
1614 layer: int |
None =
None,
1615 feature_idxs: list[int] |
None =
None,
1617 """After a feature-producing command, load UMAP and sync the explorer card."""
1618 from .cli_output
import print_tool_result
1619 from .engine.sync_dispatch
import run_dispatch
1623 umap_args: dict[str, Any] = {}
1624 if resolved_layer
is not None:
1625 umap_args[
"layer"] = resolved_layer
1627 umap_args[
"model_id"] = ensure_model
1629 print(
"\n[--umap] loading UMAP projection...", flush=
True)
1631 umap_result = run_dispatch(
1632 "ensure_umap_loaded",
1636 ensure_model=ensure_model,
1638 except Exception
as exc:
1639 print(f
"[--umap] failed: {exc}", file=sys.stderr)
1642 print_tool_result(
"umap", umap_result, tool_name=
"ensure_umap_loaded")
1643 if isinstance(umap_result, dict)
and umap_result.get(
"error"):
1646 shown =
", ".join(f
"f{i}" for i
in idxs[:8])
1647 more = f
" (+{len(idxs) - 8} more)" if len(idxs) > 8
else ""
1648 print(f
"[--umap] features to inspect: {shown}{more}")
1652 """List/load/compare saved simulation runs — no GPU model required."""
1653 from .engine.sync_dispatch
import dispatch_model_free
1654 from .engine.tools.registry
import _load_stubs
1661 result = dispatch_model_free(tool_name, tool_args, ctx, command=verb)
1662 except Exception
as exc:
1663 from .user_errors
import die
1664 die(exc=exc, label=verb)
1666 from .cli_output
import print_tool_result
1667 print_tool_result(verb, result, tool_name=tool_name)
1668 if isinstance(result, dict)
and result.get(
"error"):
1673 """`aquin check attention` must include --prompt."""
1674 if verb !=
"attention":
1677 if tool_name ==
"run_attention_routing":
1678 prompt = tool_args.get(
"prompt")
or tool_args.get(
"text")
1679 if not prompt
or not str(prompt).strip():
1680 print(
"Error: --prompt is required.", file=sys.stderr)
1681 print(
"Usage: aquin check attention --prompt <string> [--check]", file=sys.stderr)
1683 tool_args[
"prompt"] = str(prompt).strip()
1686def _save_tool_check(verb: str, result: dict[str, Any], tool_name: str |
None) ->
None:
1687 """Write JSON + PNG for verbs that support --check."""
1688 if not isinstance(result, dict):
1691 from .benchmark_check
import has_benchmark_payload
1692 from .audit_check
import has_audit_payload
1693 from .consistency_eval_check
import has_consistency_eval_payload
1694 from .suppression_eval_check
import has_suppression_eval_payload
1695 from .boundary_eval_check
import has_boundary_eval_payload
1696 from .red_team_check
import has_red_team_payload
1697 from .eval_check
import has_eval_payload
1699 if result.get(
"error"):
1700 if verb
in (
"benchmark",
"benchmarks")
and has_benchmark_payload(result):
1702 elif verb ==
"audit" and has_audit_payload(result):
1704 elif verb ==
"consistency-eval" and has_consistency_eval_payload(result):
1706 elif verb ==
"suppression-eval" and has_suppression_eval_payload(result):
1708 elif verb ==
"boundary-eval" and has_boundary_eval_payload(result):
1710 elif verb ==
"red-team" and has_red_team_payload(result):
1712 elif verb ==
"eval" and has_eval_payload(result):
1715 print(f
"[{verb} --check] skipped save: {result['error']}", file=sys.stderr)
1718 writers: dict[str, tuple[str, str]] = {
1719 "attention": (
"aquin.attention_check",
"write_attention_check"),
1720 "layer-analysis": (
"aquin.layer_analysis_check",
"write_layer_analysis_check"),
1721 "perturbation": (
"aquin.perturbation_check",
"write_perturbation_check"),
1722 "check-weights": (
"aquin.check_weights_check",
"write_check_weights_check"),
1723 "benchmark": (
"aquin.benchmark_check",
"write_benchmark_check"),
1724 "benchmarks": (
"aquin.benchmark_check",
"write_benchmark_check"),
1725 "audit": (
"aquin.audit_check",
"write_audit_check"),
1726 "consistency-eval": (
"aquin.consistency_eval_check",
"write_consistency_eval_check"),
1727 "suppression-eval": (
"aquin.suppression_eval_check",
"write_suppression_eval_check"),
1728 "boundary-eval": (
"aquin.boundary_eval_check",
"write_boundary_eval_check"),
1729 "red-team": (
"aquin.red_team_check",
"write_red_team_check"),
1730 "eval": (
"aquin.eval_check",
"write_eval_check"),
1732 spec = writers.get(verb)
1738 mod = importlib.import_module(spec[0])
1739 write_fn = getattr(mod, spec[1])
1741 json_path, png_path = write_fn(result, tool_name=tool_name, cwd=os.getcwd())
1742 print(f
"Saved {json_path}")
1743 print(f
"Saved {png_path}")
1744 except Exception
as exc:
1745 from .user_errors
import die
1746 die(message=
"Could not save check output files.", exc=exc, label=f
"{verb} --check")
1749def cmd_tool(verb: str, raw_args: list[str]) ->
None:
1750 """Generic handler for raw CLI tool verbs — thin argv layer over ``aquin.sdk``."""
1751 verb = resolve_legacy_verb(verb)
1755 from .engine.tools.registry
import _load_stubs
1756 from .session_mode
import tool_requires_model
1759 tool_name = active_map[verb]
1760 needs_model = tool_requires_model(tool_name)
1762 tool_check = bool(tool_args.pop(
"check",
False))
or "--check" in raw_args
1764 tool_args.pop(
"model_id",
None)
1766 if want_umap
and verb
not in _UMAP_FOLLOWUP_VERBS:
1768 f
"Error: --umap is for SAE feature commands "
1769 f
"(trace, feature locate/logit/neighbor, steer, benchmark).",
1774 if verb ==
"steer" and tool_args.get(
"save")
and tool_name ==
"run_steer_and_show":
1775 if tool_args.get(
"vector")
or tool_args.get(
"vector_path"):
1776 print(
"Error: --save exports a feature vector; use --vector to apply a saved vector.", file=sys.stderr)
1778 if tool_args.get(
"eval"):
1779 print(
"Error: cannot combine --eval with --save. Export first, then: aquin steer --eval --vector <path>", file=sys.stderr)
1781 if tool_args.get(
"feature_idx")
is None:
1782 print(
"Usage: aquin steer --feature_idx <n> --save <path> [--layer N]", file=sys.stderr)
1784 tool_name =
"extract_steer_vector"
1785 needs_model = tool_requires_model(tool_name)
1789 from .compute.model_loader
import get_active_model_id
1792 active_model = get_active_model_id()
or ""
1793 if active_model
and needs_model:
1794 tool_args.setdefault(
"model_id", active_model)
1801 needs_model=needs_model,
1802 model_id=active_model
or None,
1803 raise_on_error=
False,
1805 except NotImplementedError
as e:
1806 from .user_errors
import die
1807 die(f
"This command is not available yet.", exc=e, label=verb)
1808 except Exception
as e:
1809 from .user_errors
import die
1810 die(exc=e, label=verb)
1812 from .cli_output
import print_tool_result
1813 print_tool_result(verb, result, tool_name=tool_name)
1818 if want_umap
and isinstance(result, dict)
and not result.get(
"error"):
1820 build_ctx(model_id=active_model
or None),
1822 tool_args=tool_args,
1823 ensure_model=active_model
or None,
1826 if isinstance(result, dict)
and result.get(
"error"):
1831 """Dispatch aquin list simulation | compare simulation; redirect load simulation."""
1834 prefix, noun = args[0], args[1]
1835 if prefix ==
"list" and noun
in (
"simulation",
"simulations"):
1836 cmd_list([
"simulation"] + args[2:])
1838 if prefix ==
"load" and noun ==
"simulation":
1839 print(
"Use: aquin replay simulation --run_id <id>", file=sys.stderr)
1841 if prefix ==
"compare" and noun ==
"simulation":
1848def cmd_help(args: list[str]) ->
None:
1849 if args
and args[0] ==
"commands":
1850 from .commands_cli
import cmd_commands
1852 cmd_commands([
"--help"])
1855 if args
and args[0]
in (
"--help",
"-h",
"help"):
1856 print(
"Usage: aquin help [commands] [--json] [--plain]")
1858 print(
" Show the CLI command map.")
1859 print(
" commands Tracked-command subcommands")
1860 print(
" --json Machine-readable sections")
1861 print(
" --plain Full ASCII banner layout")
1864 as_json =
"--json" in args
1865 plain =
"--plain" in args
1869 model_id = get_active_model_id()
1873 from .help_display_ascii
import help_payload, render_help, render_help_quiet
1877 sys.stdout.reconfigure(encoding=
"utf-8")
1880 print(json.dumps(help_payload(
1885 ), ensure_ascii=
False))
1909 install_cli_quiet_mode()
1912 except KeyboardInterrupt:
1916 except Exception
as exc:
1917 from .user_errors
import die
1924 if args
and args[0] ==
"--cli-version":
1927 print(version_payload()[
"cli"])
1930 if "--accept-license" in args:
1933 accept_license_cli()
1942 cmd = resolve_legacy_verb(args[0])
1944 _CMD_TYPOS = {
"stauts":
"status"}
1945 cmd = _CMD_TYPOS.get(cmd, cmd)
1950 ensure_license_accepted(cmd=cmd)
1956 print(
"Removed. Use: aquin load model <id>")
1958 elif cmd
in (
"login",
"logout",
"switch"):
1959 print(f
"Removed. This framework has no account auth ({cmd}).", file=sys.stderr)
1963 elif cmd
in (
"prompt",
"prompting"):
1967 elif cmd ==
"unload":
1969 elif cmd ==
"commands":
1970 from .commands_cli
import cmd_commands
1972 elif cmd ==
"watch":
1973 print(
"Removed. Training watch is no longer part of the CLI.", file=sys.stderr)
1974 print(
"Use the SDK: aquin.init() / run.log() / run.checkpoint() → ./aquin_run/", file=sys.stderr)
1976 elif cmd ==
"dataset-generate":
1977 print(
"Removed. Pass --dataset <path> or --topic to aqit simulate.", file=sys.stderr)
1979 elif cmd
in (
"pairs-generate",
"embed-pairs-generate"):
1980 print(
"Removed. Pass --dataset <path> or --topic to aqit simulate.", file=sys.stderr)
1982 elif cmd ==
"dataset-analyze":
1983 print(
"Removed. Dataset quality check is no longer available.", file=sys.stderr)
1985 elif cmd ==
"space-decomp":
1986 print(
"Removed. Embedding space decomposition is no longer available.", file=sys.stderr)
1988 elif cmd
in (
"mem",
"mem-write",
"mem-read"):
1989 print(
"Removed.", file=sys.stderr)
1991 elif cmd
in (
"run-code",
"save-artifact"):
1992 print(
"Removed.", file=sys.stderr)
1994 elif cmd ==
"status":
1996 elif cmd ==
"update":
1998 elif cmd ==
"desktop":
2000 elif cmd ==
"setup":
2001 from .setup_cli
import cmd_setup
2003 elif cmd ==
"version" or cmd
in (
"--version",
"-V"):
2005 elif cmd ==
"license":
2007 elif cmd
in (
"help",
"--help",
"-h"):
2010 from aqit.cli import dispatch
as aqit_dispatch, is_aqit_verb
2012 if is_aqit_verb(cmd):
2013 aqit_dispatch([cmd, *rest])
2015 print(f
"Unknown command: {cmd}")
2016 print(
"Run aqit help for Recipe/train/inspect. aquin help for the shell.")
bool _try_simulation_phrase(list[str] args)
str _get_api_key(str|None explicit=None)
None _model_switch_hint(str|None mode)
None cmd_version(list[str] args)
dict _inject_session_mode(dict state)
str load_model_local(str model_id, *, bool as_json=False)
int|None _layer_from_filename_cli(Path path)
None _guard_llm_only_cmd(str cmd)
int|None _layer_from_payload(Any result, dict[str, Any]|None tool_args=None)
bool _pop_umap_flag(dict[str, Any] tool_args, list[str]|None raw_args=None)
None cmd_prompt(list[str] args)
None _assert_no_model_override(list[str] raw_args)
None _print_load_sae_help()
None cmd_trace(list[str] args)
Path|None _default_sae_load_output(str sae_id)
None cmd_desktop(list[str] args)
str _require_loaded_model_id()
None _cmd_simulation_catalog(str verb, str tool_name, list[str] extra_args)
dict _build_tool_ctx(str|None model_id=None)
list[int] _feature_idxs_from_payload(Any result, dict[str, Any]|None tool_args=None)
None _cmd_load_sae(list[str] args)
None cmd_unload(list[str] args)
None _warm_daemon_sae(str model_id, int layer)
None cmd_chat(list[str] args)
None _require_attention_args(str verb, str tool_name, dict[str, Any] tool_args)
None _guard_tool_verb(str verb)
None cmd_load(list[str] args)
Any _coerce_flag_value(str val)
None cmd_status(list[str] args)
None _save_tool_check(str verb, dict[str, Any] result, str|None tool_name)
None cmd_feature_neighbors(list[str] args)
None cmd_license(list[str] args)
str _require_locked_model_id()
None _save_config(dict data)
None _normalize_topk_flags(dict[str, Any] tool_args)
None cmd_tool(str verb, list[str] raw_args)
dict[str, Any] _parse_tool_flags(list[str] raw)
None cmd_help(list[str] args)
None cmd_feature_logits(list[str] args)
None _run_umap_followup(dict[str, Any] ctx, *, Any result=None, dict[str, Any]|None tool_args=None, str|None ensure_model=None, int|None layer=None, list[int]|None feature_idxs=None)
dict[str, str] _active_cli_tool_map()
int|None _coerce_feature_idx(Any value)
None cmd_info(list[str] args)
None cmd_update(list[str] args)
None cmd_list(list[str] args)
tuple[str, str] _detect_desktop_platform()