llav-gate 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
llav_gate/__init__.py ADDED
File without changes
llav_gate/cli.py ADDED
@@ -0,0 +1,294 @@
1
+ """llav-gate command line.
2
+
3
+ llav-gate doctor can this machine run it? (read-only, a few seconds)
4
+ llav-gate setup [--from DIR] download llav 4B (pinned, sha256-checked; shared with llavRAG)
5
+ llav-gate demo two commands that look harmless, judged live
6
+ llav-gate check "<cmd>" --cwd REPO [--task TEXT] [--json] one command: effective commands, evidence, p, decision
7
+ llav-gate expand "<cmd>" --cwd REPO what the command really runs (no model)
8
+ llav-gate serve the local judge for the hooks (127.0.0.1 only)
9
+ llav-gate install-hook --agent claude|codex [--deciding] [--uninstall] add the PreToolUse hook (shadow mode first)
10
+ llav-gate hook --agent claude|codex [--shadow] the hook itself (reads the agent's hook JSON on stdin)
11
+ llav-gate pilot [--yes] replay your own past agent commands through the gate (local only)
12
+
13
+ Everything runs locally: llav 4B, the open llav model, judges each command; nothing is sent anywhere.
14
+ The judged command is never executed. The default policy never auto-allows (see gate.Policy).
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import json
20
+ import os
21
+ import sys
22
+
23
+ from .hardened import from_transcript, log_record, read_hook_input, redact
24
+
25
+
26
+ def _print_expansion(res, out):
27
+ out.write(f"effective commands ({len(res.units)}):\n")
28
+ for u in res.units:
29
+ flag = " UNRESOLVED: " + "; ".join(u.unresolved) if u.unresolved else ""
30
+ out.write(f" {' ' * u.depth}[{u.lang}] {redact(u.text)[:160]}\n")
31
+ out.write(f" {' ' * u.depth} from: {u.provenance()[:160]}{flag}\n")
32
+ for n in res.notes:
33
+ out.write(f" note: {n}\n")
34
+ out.write(f"unresolved: {'yes' if res.unresolved else 'no'}\n")
35
+
36
+
37
+ def cmd_expand(a):
38
+ from .expand import Expander
39
+ from .repo import RepoView
40
+ cwd = os.path.abspath(os.path.expanduser(a.cwd))
41
+ res = Expander(RepoView.real(cwd)).expand(a.command, cwd)
42
+ if a.json:
43
+ print(json.dumps({"command": redact(a.command), "unresolved": res.unresolved,
44
+ "unresolved_reasons": res.unresolved_reasons(), "notes": res.notes,
45
+ "effective": [{"command": redact(u.text), "lang": u.lang, "depth": u.depth, "cwd": u.cwd,
46
+ "from": [str(p) for p in u.chain], "unresolved": u.unresolved,
47
+ "notes": u.notes, "tool": u.tool, "sub": u.sub} for u in res.units],
48
+ "definitions": [{"label": d.label, "file": d.file} for d in res.definitions]}, indent=1))
49
+ else:
50
+ _print_expansion(res, sys.stdout)
51
+ return 0
52
+
53
+
54
+ def cmd_check(a):
55
+ from .gate import JudgeClient, Policy, check
56
+ cwd = os.path.abspath(os.path.expanduser(a.cwd))
57
+ pol = Policy.load(a.policy)
58
+ if a.auto_allow:
59
+ pol.auto_allow = True
60
+ v = check(a.command, cwd, a.task or os.environ.get("LLAV_TASK") or "(not given)", a.step, policy=pol,
61
+ judge=JudgeClient(url=a.url, in_process=a.in_process or not _judge_up(a.url), device=a.device))
62
+ if a.json:
63
+ d = {k: getattr(v, k) for k in ("decision", "reason", "p_system", "p_model_only", "p_second", "p_next", "floor",
64
+ "unresolved", "hard_rule", "effective", "docs", "error")}
65
+ print(json.dumps(d, indent=1, ensure_ascii=False))
66
+ return 0
67
+ print(f"command: {redact(a.command)}")
68
+ print("effective commands:")
69
+ for e in v.effective:
70
+ print(f" {' ' * e['depth']}[{e['lang']}] {e['command'][:160]}")
71
+ if e["depth"]:
72
+ print(f" {' ' * e['depth']} from: {e['from'][:160]}")
73
+ if v.unresolved:
74
+ print("unresolved: " + "; ".join(v.unresolved))
75
+ if v.docs:
76
+ print("evidence:\n " + v.docs.replace("\n", "\n "))
77
+ if v.p_system is not None:
78
+ req = max(v.p_model_only, v.p_second or 0.0)
79
+ print(f"p(destructive) gate {v.p_system:.3f} request only {req:.3f} p(next step) {v.p_next:.3f}")
80
+ if v.floor:
81
+ print("novelty floor: " + "; ".join(v.floor))
82
+ print(f"decision: {v.decision}\nreason: {v.reason}")
83
+ return 0
84
+
85
+
86
+ def cmd_serve(a):
87
+ from .server import serve
88
+ import platform
89
+ backend = a.backend or ("mlx" if platform.system() == "Darwin" and platform.machine() == "arm64" else "torch")
90
+ serve(a.port, a.idle_exit, a.device, backend)
91
+ return 0
92
+
93
+
94
+ def _judge_up(url: str) -> bool:
95
+ import urllib.request
96
+ try:
97
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
98
+ with opener.open(url.rstrip("/") + "/health", timeout=0.5) as r:
99
+ return r.status == 200
100
+ except OSError:
101
+ return False
102
+
103
+
104
+ def _start_judge(url: str, log: str | None, agent: str = "claude") -> bool:
105
+ """Start `llav-gate serve` in the background on a GPU (once: a lock file stops a second start for 2 minutes); it
106
+ exits after 15 minutes without requests. Never starts on the CPU or with too little free memory: then it prints one
107
+ line for the user (at most once an hour) and the command goes ahead without a decision."""
108
+ import subprocess
109
+ import time
110
+ import urllib.parse
111
+ from .resources import IDLE_EXIT_S, judge_can_start, not_started_line
112
+ state = os.path.expanduser("~/.llav")
113
+ os.makedirs(state, mode=0o700, exist_ok=True)
114
+ ok, why = judge_can_start()
115
+ if not ok:
116
+ note = os.path.join(state, "gate-not-started")
117
+ line = not_started_line(why)
118
+ log_record(log, {"recipe": "gate-v2", "decision": "none", "note": line})
119
+ if not os.path.exists(note) or time.time() - os.path.getmtime(note) > 3600:
120
+ open(note, "w").close()
121
+ print(json.dumps({"systemMessage": line}))
122
+ print(line, file=sys.stderr)
123
+ return False
124
+ lock = os.path.join(state, "gate-serve.starting")
125
+ if os.path.exists(lock) and time.time() - os.path.getmtime(lock) < 120:
126
+ return True
127
+ open(lock, "w").close()
128
+ port = urllib.parse.urlparse(url).port or 18450
129
+ with open(os.path.join(state, "gate-serve.log"), "ab") as fh:
130
+ subprocess.Popen([sys.executable, "-m", "llav_gate.cli", "serve", "--port", str(port),
131
+ "--idle-exit", str(IDLE_EXIT_S), "--backend", "torch" if why == "torch" else "mlx"],
132
+ stdout=fh, stderr=fh, stdin=subprocess.DEVNULL, start_new_session=True)
133
+ log_record(log, {"recipe": "gate-v2", "decision": "none", "note": f"judge was not running; started it ({why})"})
134
+ return True
135
+
136
+
137
+ def cmd_hook(a):
138
+ """PreToolUse hook for Claude Code (--agent claude) or Codex (--agent codex). Always exits 0. deny / ask are explicit
139
+ (Codex: ask becomes a note to the agent, or a deny with --codex-ask deny); allow only with --auto-allow; pass and
140
+ errors print nothing (the user's normal permission flow decides). --shadow logs and never decides."""
141
+ from .gate import JudgeClient, Policy, check
142
+ from .hooks import output
143
+ hook = read_hook_input()
144
+ tool = hook.get("tool_name") or ""
145
+ tin = hook.get("tool_input") if isinstance(hook.get("tool_input"), dict) else {}
146
+ if tool != "Bash" or not tin.get("command"):
147
+ return 0
148
+ command = str(tin["command"])[:8000]
149
+ cwd = hook.get("cwd") or os.getcwd()
150
+ no_tx = a.no_transcript or a.agent == "codex" or os.environ.get("LLAV_NO_TRANSCRIPT", "") not in ("", "0")
151
+ task = a.task or os.environ.get("LLAV_TASK") or ("" if no_tx else from_transcript(hook.get("transcript_path"), "user"))
152
+ task = (task or "(not given)")[:2000]
153
+ pol = Policy.load(a.policy)
154
+ if a.auto_allow:
155
+ pol.auto_allow = True
156
+ if a.autostart and not _judge_up(a.url):
157
+ _start_judge(a.url, a.log, a.agent)
158
+ return 0
159
+ try:
160
+ v = check(command, cwd, task, None, policy=pol, judge=JudgeClient(url=a.url))
161
+ except Exception as e: # noqa: BLE001 never block the agent on a gate failure
162
+ log_record(a.log, {"recipe": "gate-v2", "command": redact(command)[:300], "decision": "error",
163
+ "error": str(e)[:300], "shadow": a.shadow})
164
+ return 0
165
+ log_record(a.log, {"recipe": "gate-v2", "command": redact(command)[:300], "decision": v.decision,
166
+ "reason": v.reason[:400], "p_system": v.p_system, "p_model_only": v.p_model_only,
167
+ "p_next": v.p_next, "floor": v.floor[:2], "unresolved": v.unresolved[:2],
168
+ "p_second": v.p_second, "hard_rule": v.hard_rule, "shadow": a.shadow, "error": v.error,
169
+ "agent": a.agent})
170
+ if a.shadow:
171
+ return 0
172
+ if v.decision in ("deny", "ask", "allow") and not v.error or (v.decision == "ask" and v.hard_rule):
173
+ o = output(a.agent, v.decision, v.reason, a.codex_ask)
174
+ if o:
175
+ print(json.dumps(o))
176
+ return 0
177
+
178
+
179
+ def cmd_install_hook(a):
180
+ from .hooks import install
181
+ return install(a.agent, a.scope, shadow=not a.deciding, uninstall=a.uninstall, log=a.log,
182
+ autostart=not a.no_autostart, codex_ask=a.codex_ask)
183
+
184
+
185
+ def cmd_demo(a):
186
+ from .demo import run
187
+ from .gate import JudgeClient
188
+ from .cli_util import ensure_ready
189
+ if not ensure_ready(a.yes):
190
+ return 1
191
+ return run(JudgeClient(url=a.url, in_process=a.in_process or not _judge_up(a.url), device=a.device),
192
+ verbose=a.verbose)
193
+
194
+
195
+ def cmd_pilot(a):
196
+ from .gate import JudgeClient
197
+ from .pilot import run
198
+ if not a.no_model and not _judge_up(a.url):
199
+ print(f"the local judge is not running at {a.url}; start it with `llav-gate serve &` (or use --no-model)")
200
+ return 1
201
+ return run(a.transcripts, a.limit, None if a.no_model else JudgeClient(url=a.url), yes=a.yes, json_out=a.json_out)
202
+
203
+
204
+ def cmd_setup(a):
205
+ from .setup_models import run
206
+ return run(a.src, a.copy, a.yes)
207
+
208
+
209
+ def cmd_doctor(a):
210
+ from .doctor import run
211
+ return run(a.json, a.verify, a.url, network=not a.offline)
212
+
213
+
214
+ def main(argv=None):
215
+ ap = argparse.ArgumentParser(prog="llav-gate", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
216
+ try:
217
+ from importlib.metadata import version
218
+ ver = version("llav-gate")
219
+ except Exception: # noqa: BLE001
220
+ ver = "dev"
221
+ ap.add_argument("--version", action="version", version=f"llav-gate {ver}")
222
+ sp = ap.add_subparsers(dest="cmd", required=True)
223
+ c = sp.add_parser("check")
224
+ c.add_argument("command")
225
+ c.add_argument("--cwd", default=".")
226
+ c.add_argument("--task", default=None)
227
+ c.add_argument("--step", default=None)
228
+ c.add_argument("--policy", default=os.path.expanduser("~/.llav/gate-v2-policy.json"))
229
+ c.add_argument("--auto-allow", action="store_true")
230
+ c.add_argument("--in-process", action="store_true", help="load the judge in this process instead of `serve`")
231
+ c.add_argument("--device", default=None, help="gpu|cpu (MLX), cuda|cpu (torch)")
232
+ c.add_argument("--json", action="store_true")
233
+ c.add_argument("--url", default=os.environ.get("LLAV_GATE_URL", "http://127.0.0.1:18450"))
234
+ e = sp.add_parser("expand")
235
+ e.add_argument("command")
236
+ e.add_argument("--cwd", default=".")
237
+ e.add_argument("--json", action="store_true")
238
+ s = sp.add_parser("serve")
239
+ s.add_argument("--port", type=int, default=18450)
240
+ s.add_argument("--idle-exit", type=float, default=0.0, help="exit after this many idle seconds (0 = never; the "
241
+ "hooks start it with 900 = 15 minutes)")
242
+ s.add_argument("--backend", default=None, choices=("mlx", "torch"),
243
+ help="mlx (Apple silicon, the default there) or torch (CUDA / CPU, the default elsewhere)")
244
+ s.add_argument("--device", default=None, help="mlx: gpu|cpu (default gpu); torch: cuda|cpu (default cuda)")
245
+ h = sp.add_parser("hook")
246
+ h.add_argument("--shadow", action="store_true")
247
+ h.add_argument("--log", default=None)
248
+ h.add_argument("--task", default=None)
249
+ h.add_argument("--no-transcript", action="store_true")
250
+ h.add_argument("--auto-allow", action="store_true")
251
+ h.add_argument("--policy", default=os.path.expanduser("~/.llav/gate-v2-policy.json"))
252
+ h.add_argument("--url", default=os.environ.get("LLAV_GATE_URL", "http://127.0.0.1:18450"))
253
+ h.add_argument("--agent", default="claude", choices=("claude", "codex"))
254
+ h.add_argument("--codex-ask", default="warn", choices=("warn", "deny"),
255
+ help="Codex cannot show an approval prompt from a hook: warn = tell the agent, deny = block")
256
+ h.add_argument("--autostart", action="store_true", help="start the local judge if it is not running")
257
+ ih = sp.add_parser("install-hook", help="add the gate's PreToolUse hook to Claude Code or Codex")
258
+ ih.add_argument("--agent", default="claude", choices=("claude", "codex"))
259
+ ih.add_argument("--scope", default="user", choices=("user", "project"))
260
+ ih.add_argument("--deciding", action="store_true", help="let the gate decide (default: shadow mode, logs only)")
261
+ ih.add_argument("--uninstall", action="store_true")
262
+ ih.add_argument("--log", default="~/.llav/gate.jsonl")
263
+ ih.add_argument("--no-autostart", action="store_true")
264
+ ih.add_argument("--codex-ask", default="warn", choices=("warn", "deny"))
265
+ d = sp.add_parser("doctor")
266
+ d.add_argument("--json", action="store_true")
267
+ d.add_argument("--verify", action="store_true", help="also check every weight file's sha256 (about 20 s)")
268
+ d.add_argument("--offline", action="store_true", help="skip the download speed sample")
269
+ d.add_argument("--url", default=os.environ.get("LLAV_GATE_URL", "http://127.0.0.1:18450"))
270
+ m = sp.add_parser("demo")
271
+ m.add_argument("--url", default=os.environ.get("LLAV_GATE_URL", "http://127.0.0.1:18450"))
272
+ m.add_argument("--in-process", action="store_true")
273
+ m.add_argument("--device", default=None, help="gpu|cpu (MLX), cuda|cpu (torch)")
274
+ m.add_argument("--yes", action="store_true", help="download the weights without asking")
275
+ m.add_argument("--verbose", action="store_true")
276
+ pl = sp.add_parser("pilot")
277
+ pl.add_argument("--transcripts", default="~/.claude/projects")
278
+ pl.add_argument("--limit", type=int, default=300)
279
+ pl.add_argument("--no-model", action="store_true", help="layers 1-3 statistics only (no judge needed)")
280
+ pl.add_argument("--yes", action="store_true", help="confirm reading the local session history without a prompt")
281
+ pl.add_argument("--json", dest="json_out", default=None, help="also write the summary to this JSON file")
282
+ pl.add_argument("--url", default=os.environ.get("LLAV_GATE_URL", "http://127.0.0.1:18450"))
283
+ su = sp.add_parser("setup", help="download llav 4B (pinned, sha256-checked; shared with llavRAG)")
284
+ su.add_argument("--from", dest="src", default=None, help="use a local copy (folder) instead of downloading")
285
+ su.add_argument("--copy", action="store_true", help="copy files from --from instead of linking them")
286
+ su.add_argument("--yes", action="store_true")
287
+ a = ap.parse_args(argv)
288
+ return {"check": cmd_check, "expand": cmd_expand, "serve": cmd_serve, "hook": cmd_hook,
289
+ "doctor": cmd_doctor, "demo": cmd_demo, "pilot": cmd_pilot, "setup": cmd_setup,
290
+ "install-hook": cmd_install_hook}[a.cmd](a)
291
+
292
+
293
+ if __name__ == "__main__":
294
+ sys.exit(main())
llav_gate/cli_util.py ADDED
@@ -0,0 +1,26 @@
1
+ """Small helpers shared by the commands that need the judge weights (demo)."""
2
+ from __future__ import annotations
3
+
4
+ from . import models
5
+
6
+
7
+ def ensure_ready(yes: bool = False, out=print) -> bool:
8
+ """True when the weights are in place; otherwise offer to put them there (doctor's checks first)."""
9
+ if models.ready():
10
+ return True
11
+ from .doctor import checks
12
+ cs, _ = checks(network=True)
13
+ fails = [c for c in cs if c["status"] == "fail"]
14
+ for c in cs:
15
+ if c["status"] in ("fail", "todo", "warn") and c["check"] in ("python", "backend", "memory", "disk",
16
+ "llav 4B", "download", "coding files"):
17
+ out(f"{c['status']:>4} {c['check']:<14} {c['detail']}" + (f"\n fix: {c['fix']}" if c["fix"] else ""))
18
+ if fails and not yes:
19
+ out("Fix the failed checks first (or pass --yes to try anyway).")
20
+ return False
21
+ if not yes:
22
+ ans = input("Download llav 4B now? [Y/n] ").strip().lower()
23
+ if ans not in ("", "y", "yes"):
24
+ return False
25
+ from .setup_models import run
26
+ return run(yes=yes) == 0 and models.ready()
@@ -0,0 +1,32 @@
1
+ <!-- markdownlint-disable MD041 -->
2
+ Copyright © 2014—present the [tldr-pages team](https://github.com/orgs/tldr-pages/people)
3
+ and [contributors](https://github.com/tldr-pages/tldr/graphs/contributors).
4
+
5
+ **This work is licensed under the
6
+ [Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/)
7
+ (CC-BY).**
8
+
9
+ ----
10
+
11
+ The contents of the [scripts/](https://github.com/tldr-pages/tldr/tree/main/scripts) directory
12
+ are licensed under the MIT license:
13
+
14
+ > **The MIT License**
15
+ >
16
+ > Permission is hereby granted, free of charge, to any person obtaining a copy
17
+ > of this software and associated documentation files (the "Software"), to deal
18
+ > in the Software without restriction, including without limitation the rights
19
+ > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20
+ > copies of the Software, and to permit persons to whom the Software is
21
+ > furnished to do so, subject to the following conditions:
22
+ >
23
+ > The above copyright notice and this permission notice shall be included in
24
+ > all copies or substantial portions of the Software.
25
+ >
26
+ > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27
+ > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28
+ > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29
+ > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30
+ > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31
+ > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32
+ > THE SOFTWARE.
Binary file