zyonix-cli 0.1.13__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 (45) hide show
  1. zyonix_cli/__init__.py +2 -0
  2. zyonix_cli/agent_init.py +228 -0
  3. zyonix_cli/auth_cmd.py +499 -0
  4. zyonix_cli/auth_store.py +124 -0
  5. zyonix_cli/brief.py +271 -0
  6. zyonix_cli/checks_cmd.py +160 -0
  7. zyonix_cli/client.py +130 -0
  8. zyonix_cli/cmdkit.py +142 -0
  9. zyonix_cli/common.py +94 -0
  10. zyonix_cli/context_view.py +116 -0
  11. zyonix_cli/deploy_cmd.py +52 -0
  12. zyonix_cli/drafts_cmd.py +260 -0
  13. zyonix_cli/explain.py +283 -0
  14. zyonix_cli/fix_cmd.py +284 -0
  15. zyonix_cli/guard_cmd.py +125 -0
  16. zyonix_cli/helpview.py +171 -0
  17. zyonix_cli/importer.py +274 -0
  18. zyonix_cli/issues_cmd.py +597 -0
  19. zyonix_cli/jobs_cmd.py +71 -0
  20. zyonix_cli/junit.py +49 -0
  21. zyonix_cli/mcp_cmd.py +96 -0
  22. zyonix_cli/mcp_server.py +375 -0
  23. zyonix_cli/monitor_cmd.py +120 -0
  24. zyonix_cli/perf_view.py +51 -0
  25. zyonix_cli/progress.py +57 -0
  26. zyonix_cli/prompts_cmd.py +166 -0
  27. zyonix_cli/regression_cmd.py +216 -0
  28. zyonix_cli/render.py +313 -0
  29. zyonix_cli/replay_cmd.py +215 -0
  30. zyonix_cli/review_cmd.py +169 -0
  31. zyonix_cli/runner.py +213 -0
  32. zyonix_cli/runs_cmd.py +638 -0
  33. zyonix_cli/spec_cmd.py +74 -0
  34. zyonix_cli/status_cmd.py +488 -0
  35. zyonix_cli/term.py +206 -0
  36. zyonix_cli/test_cmd.py +248 -0
  37. zyonix_cli/triage.py +215 -0
  38. zyonix_cli/usage.py +172 -0
  39. zyonix_cli/verify.py +223 -0
  40. zyonix_cli/verify_view.py +87 -0
  41. zyonix_cli-0.1.13.dist-info/METADATA +58 -0
  42. zyonix_cli-0.1.13.dist-info/RECORD +45 -0
  43. zyonix_cli-0.1.13.dist-info/WHEEL +4 -0
  44. zyonix_cli-0.1.13.dist-info/entry_points.txt +21 -0
  45. zyonix_cli-0.1.13.dist-info/licenses/LICENSE +202 -0
zyonix_cli/brief.py ADDED
@@ -0,0 +1,271 @@
1
+ """The default view of `zyonix status`, `findings`, `issues` and `runs show`: per problem,
2
+
3
+ ERROR what went wrong
4
+ ROOT CAUSE why, with how sure Zyonix is (or that it does not know)
5
+ FIX what is recommended, and separately what has already been done
6
+
7
+ Everything shown comes from the server's own evidence: the issue's root cause (RCA), its
8
+ evidence chain, the recommended action the server derives from the cause, fix suggestions
9
+ derived from the findings, and the fix proposals with their verification. Nothing is inferred
10
+ here; when the evidence does not decide a cause or a fix, the text says so. The full reports
11
+ are one flag away (``--verbose``) or in the detail commands (`zyonix issues show <n>`)."""
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Iterable
16
+ from dataclasses import dataclass, field
17
+ from typing import Any
18
+
19
+ from zyonix_cli import term
20
+ from zyonix_cli.client import ApiClient, CliError
21
+ from zyonix_cli.render import badge, plural, wrap
22
+
23
+ # What each taxonomy label means, in plain words (a description of the label, not a guess).
24
+ CAUSE = {
25
+ "INFRA_PROVIDER": "The call to the LLM provider failed (an error, a timeout or a rate limit).",
26
+ "INFRA_TOOL": "A service the pipeline depends on (OCR, retrieval) failed.",
27
+ "CODE_EXCEPTION": "The pipeline code raised an exception.",
28
+ "CONFIG_LIMITS": "The model's output was cut off by its max_tokens limit.",
29
+ "POSTPROCESS_BUG": "Post-processing changed a correct model output into a wrong one.",
30
+ "UPSTREAM_INPUT": "The input the model was given was the problem, not the model.",
31
+ "SCHEMA_GAP": "The document has an amount the output schema has no field for, so the "
32
+ "rule cannot balance.",
33
+ "DOCUMENT_INCONSISTENT": "The document itself is inconsistent: its own numbers do not add up.",
34
+ }
35
+ UPSTREAM = {
36
+ "OCR_QUALITY": "The document text was garbled (OCR) before the model saw it.",
37
+ "RETRIEVAL_MISS": "Retrieval did not supply the part of the document that holds the value.",
38
+ "INPUT_UNSUPPORTED": "The document is of a kind the pipeline does not support.",
39
+ "NOT_IN_SOURCE": "The value is not in the document text the model was given.",
40
+ }
41
+ MODEL = {
42
+ "OMISSION": "left out a value the document contains",
43
+ "HALLUCINATION": "returned a value that is not in the document",
44
+ "FORMAT": "returned the value in the wrong format",
45
+ "RULE_VIOLATION": "returned values that break a business rule",
46
+ "MISREAD": "misread a value in the document",
47
+ "WRONG_LABEL": "took the value from the wrong label",
48
+ "PLACEHOLDER": "returned a placeholder instead of a value",
49
+ "UNSTABLE": "returned different values for the same document",
50
+ }
51
+ CERTAINTY = {"high": "established from deterministic evidence",
52
+ "medium": "suspected: inferred from the evidence, not verified"}
53
+ FIX_STATE = {
54
+ "proposed": "proposed, not verified yet",
55
+ "verifying": "being verified (replay running)",
56
+ "verified": "verified by replay, waiting for human approval",
57
+ "approved": "approved, not deployed yet",
58
+ "deployed": "deployed",
59
+ "rejected": "rejected",
60
+ "failed": "failed verification",
61
+ }
62
+ ORDER = {"REOPENED": 0, "DETECTED": 1, "DIAGNOSED": 1, "FIX_PENDING": 2, "VERIFYING": 3,
63
+ "AWAITING_APPROVAL": 3, "AWAITING_DEPLOY": 4, "MONITORING": 5, "RESOLVED": 9}
64
+ SEVERITY = {"critical": 0, "high": 1, "medium": 2, "low": 3}
65
+
66
+
67
+ @dataclass
68
+ class Brief:
69
+ title: str # "ISS-3 DIAGNOSED 4 runs" (one line above the sections)
70
+ error: list[str]
71
+ cause: list[str]
72
+ certainty: str # how sure: shown next to ROOT CAUSE
73
+ recommended: list[str] = field(default_factory=list)
74
+ done: list[str] = field(default_factory=list)
75
+ next: list[str] = field(default_factory=list)
76
+ # set for an issue: which one, its short cause label, its size, its evidence example runs
77
+ issue_id: int | None = None
78
+ label: str = ""
79
+ runs: int = 0
80
+ examples: list[str] = field(default_factory=list)
81
+
82
+
83
+ # ------------------------------------------------------------------------------ causes
84
+
85
+
86
+ def cause_text(rc: dict[str, Any], step: str | None = None) -> tuple[list[str], str]:
87
+ """(sentences, certainty) for an issue's root cause, or "not determined"."""
88
+ cat, sub = rc.get("category"), rc.get("subtype")
89
+ if not cat or cat == "UNDETERMINED":
90
+ return (["Not determined: the evidence does not point to one cause yet."],
91
+ "insufficient evidence")
92
+ if cat == "MODEL_EXTRACTION":
93
+ what = MODEL.get(sub or "")
94
+ line = (f"The model {what}." if what else
95
+ "The model extracted the value wrongly although the evidence was in its input.")
96
+ elif cat == "UPSTREAM_INPUT":
97
+ line = UPSTREAM.get(sub or "", CAUSE["UPSTREAM_INPUT"])
98
+ else:
99
+ line = CAUSE.get(cat, f"{cat}{'/' + sub if sub else ''}.")
100
+ where = step or rc.get("step")
101
+ label = f"{cat}/{sub}" if sub else cat
102
+ lines = [line, f"({label}" + (f", at step {where}" if where else "") + ")"]
103
+ return lines, CERTAINTY.get(rc.get("confidence") or "medium", CERTAINTY["medium"])
104
+
105
+
106
+ def _evidence_lines(ev: dict[str, Any]) -> list[str]:
107
+ out = []
108
+ chain = ev.get("chain") or []
109
+ if chain:
110
+ e = chain[0]
111
+ snippet = f" `{e['snippet']}`" if e.get("snippet") not in (None, "") else ""
112
+ out.append(f"Evidence: [{e.get('step') or 'run'}] {e['what']}{snippet} -> {e['result']}")
113
+ change = ev.get("recent_change")
114
+ if change:
115
+ out.append(f"Started with a change of {change['attribute']} "
116
+ f"(first seen {str(change.get('first_seen') or '')[:16].replace('T', ' ')}).")
117
+ return out
118
+
119
+
120
+ # ------------------------------------------------------------------------------ fixes
121
+
122
+
123
+ def done_lines(fixes: Iterable[dict[str, Any]], issue: dict[str, Any]) -> list[str]:
124
+ """Fixes that exist (proposed, verified, deployed): never mixed with recommendations."""
125
+ out = []
126
+ for f in fixes:
127
+ if f.get("status") == "superseded":
128
+ continue
129
+ state = FIX_STATE.get(f.get("status"), f.get("status") or "?")
130
+ replay = f.get("replay") or {}
131
+ if replay and "passed" in replay and f.get("status") not in ("verified", "deployed"):
132
+ state += "; replay " + ("passed" if replay["passed"] else "FAILED")
133
+ out.append(f"Fix #{f['id']} ({f['kind']}): {state}. {f.get('title') or ''}".rstrip())
134
+ m = issue.get("monitoring")
135
+ if m:
136
+ out.append(f"Monitoring since deploy: {m['eligible_runs']}/{m['min_runs']} runs, "
137
+ f"{m['days']:.1f}/{m['min_days']:.0f} days, "
138
+ f"{m['delivered_recurrences']} recurrence(s).")
139
+ return out
140
+
141
+
142
+ def _suggestions(client: ApiClient, path: str, check: str | None = None) -> list[str]:
143
+ try:
144
+ sugg = client.get(path).get("suggestions") or []
145
+ except CliError: # a server from before fix suggestions
146
+ return []
147
+ out = []
148
+ for s in sugg:
149
+ if check and s.get("check_key") not in (None, check):
150
+ continue
151
+ code = s.get("requires_app_code_change", s.get("needs_code_change"))
152
+ how = ", needs an application code change" if code else ""
153
+ out.append(f"Suggested change ({s['kind']}{how}): "
154
+ f"{_printable(s.get('patch') or s.get('title'))}")
155
+ return out[:2]
156
+
157
+
158
+ def _printable(value: Any) -> str:
159
+ from zyonix_cli.fix_cmd import _printable as clean # strips control / bidi characters
160
+
161
+ return clean(value)
162
+
163
+
164
+ # ------------------------------------------------------------------------------ issues
165
+
166
+
167
+ def issue_brief(client: ApiClient, issue_id: int, *, issue: dict[str, Any] | None = None,
168
+ evidence: dict[str, Any] | None = None, suggestions: bool = True) -> Brief:
169
+ from zyonix_cli.issues_cmd import issue_next
170
+
171
+ i = issue if issue is not None else client.get(f"/v1/issues/{issue_id}")
172
+ ev = evidence if evidence is not None else client.get(f"/v1/issues/{issue_id}/evidence")
173
+ pf = ev.get("primary_finding") or {}
174
+ where = f" on field {i['field']}" if i.get("field") else ""
175
+ # the heading (server headings.py) says what went wrong; an older server sends the title
176
+ error = [_printable(i.get("heading") or i.get("title") or i["check"])]
177
+ if i.get("origin") == "agent_reported":
178
+ error.append("Reported by your agent (zyonix.check / zyonix.flag).")
179
+ detail = f": {_printable(pf['detail'])}" if pf.get("detail") else ""
180
+ share = (f", {ev['pct']:.1f}% of {ev['runs_checked']} checked"
181
+ if ev.get("runs_checked") else "")
182
+ error.append(f"Check {i['check']}{where} failed{detail} "
183
+ f"({plural(i['member_count'], 'run')}{share}).")
184
+ cause, certainty = cause_text(i["root_cause"])
185
+ if certainty != "insufficient evidence":
186
+ cause += _evidence_lines(ev)
187
+ action = [_printable(ev["action"])] if ev.get("action") and \
188
+ certainty != "insufficient evidence" else []
189
+ suggested = _suggestions(client, f"/v1/issues/{i['id']}/suggestions") if suggestions else []
190
+ # what to do, from the issue's evidence (server recommendations.py), most specific first
191
+ recs = [_printable(f"{r['title']} ({r.get('basis', 'suspected')}): "
192
+ + " ".join(r.get("steps") or [])[:400])
193
+ for r in (i.get("recommendations") or [])[:2]]
194
+ recommended = merge_recommended(recs + action + suggested, certainty, i["id"])
195
+ steps = [c for c, _ in issue_next(i)[:1]]
196
+ if suggested and steps and steps[0].startswith("zyonix fix propose"):
197
+ # Zyonix already derived a candidate: write it as files instead of starting from nothing
198
+ steps = [f"zyonix fix suggest --issue {i['id']} --out zyonix-fixes"]
199
+ rc = i["root_cause"]
200
+ label = "/".join(x for x in (rc.get("category"), rc.get("subtype")) if x) or "UNDETERMINED"
201
+ return Brief(title=f"ISS-{i['id']} {badge(i['status'])} {plural(i['member_count'], 'run')}"
202
+ f" severity {i.get('severity') or '-'}",
203
+ error=error, cause=cause, certainty=certainty, recommended=recommended,
204
+ done=done_lines(i.get("fixes") or [], i),
205
+ next=steps + [f"zyonix issues show {i['id']}"],
206
+ issue_id=i["id"], label=label, runs=i.get("member_count") or 0,
207
+ examples=[x["run_id"] for x in ev.get("examples") or [] if x.get("run_id")])
208
+
209
+
210
+ def merge_recommended(items: list[str], certainty: str, issue_id: int | None = None) -> list[str]:
211
+ """Recommendations without duplicates; the server's generic "Review the examples." only when
212
+ nothing more specific exists; an explicit "none" when nothing does."""
213
+ out = list(dict.fromkeys(x for x in items if x))
214
+ if len(out) > 1:
215
+ out = [x for x in out if x.strip() != "Review the examples."]
216
+ if not out:
217
+ out.append("No fix can be recommended from the evidence yet"
218
+ + (": review the examples and attach corrections so the cause can be decided."
219
+ if certainty == "insufficient evidence" or issue_id is None
220
+ else f": see the evidence in `zyonix issues show {issue_id}`."))
221
+ return out
222
+
223
+
224
+ def several(title: str, error: list[str], briefs: list[Brief], intro: str) -> Brief:
225
+ """One problem that several issues (with different recorded causes) could explain: every
226
+ candidate is listed with its own cause, never one chosen on the reader's behalf."""
227
+ cause = [intro] + [f"ISS-{b.issue_id} ({plural(b.runs, 'run')}, {b.label}, {b.certainty}): "
228
+ f"{b.cause[0]}" for b in briefs]
229
+ recommended = [f"For ISS-{b.issue_id}: {r}" for b in briefs for r in b.recommended[:1]]
230
+ done = [f"ISS-{b.issue_id}: {d}" for b in briefs for d in b.done]
231
+ return Brief(title=title, error=error, cause=cause,
232
+ certainty="ambiguous: more than one recorded cause for this check",
233
+ recommended=recommended, done=done,
234
+ next=[f"zyonix issues show {b.issue_id}" for b in briefs][:3])
235
+
236
+
237
+ def priority(issues: Iterable[dict[str, Any]]) -> list[dict[str, Any]]:
238
+ """Open issues, most important first: recurring, then unfixed, then waiting on a human;
239
+ within a state the higher severity and the larger issue first. Resolved ones are left out."""
240
+ open_ = [i for i in issues if i.get("status") != "RESOLVED"]
241
+ return sorted(open_, key=lambda i: (ORDER.get(i.get("status"), 6),
242
+ SEVERITY.get(i.get("severity") or "", 4),
243
+ -(i.get("member_count") or 0), i.get("id") or 0))
244
+
245
+
246
+ # ------------------------------------------------------------------------------ text
247
+
248
+
249
+ def render(header: str, briefs: list[Brief], *, more: str | None = None) -> str:
250
+ out = [term.paint(f"ZYONIX - {header}", "head")]
251
+ for n, b in enumerate(briefs, 1):
252
+ out.append("")
253
+ if len(briefs) > 1 or b.title:
254
+ out.append(term.paint(f"[{n}] " if len(briefs) > 1 else "", "head") + b.title)
255
+ out.append("")
256
+ out.append(term.paint("ERROR", "bad"))
257
+ out += [wrap(x) for x in b.error]
258
+ out.append("")
259
+ out.append(term.paint("ROOT CAUSE", "warn") + f" ({b.certainty})")
260
+ out += [wrap(x) for x in b.cause]
261
+ out.append("")
262
+ out.append(term.paint("FIX", "good"))
263
+ out.append(" Recommended (not applied):")
264
+ out += [wrap(x, indent=4) for x in b.recommended]
265
+ out.append(" Already done:")
266
+ out += [wrap(x, indent=4) for x in (b.done or ["Nothing yet: no fix has been proposed."])]
267
+ if b.next:
268
+ out.append(" Next: " + " | ".join(term.paint(c, "info") for c in b.next))
269
+ if more:
270
+ out += ["", more]
271
+ return "\n".join(out)
@@ -0,0 +1,160 @@
1
+ """`zyonix checks`: problems you want Zyonix to watch for on every new document.
2
+
3
+ zyonix checks [list] # your checks, and the fields a check can read
4
+ zyonix checks test --title .. --field invoice_no --kind filled # past documents, no change
5
+ zyonix checks add --title .. --field grand_total --kind at_most --value 500000 # admin key
6
+ zyonix checks add --title .. --kind error_text --value "quota exceeded" --cause INFRA_PROVIDER
7
+ zyonix checks remove <id> # admin key
8
+ zyonix checks mode check:saved review # default | review | off; admin key
9
+
10
+ A check is a rule in a new spec version, so it applies to new documents. `zyonix feedback` reports
11
+ a problem on one document.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ from typing import Any
18
+ from urllib.parse import quote
19
+
20
+ from zyonix_cli.client import ApiClient
21
+ from zyonix_cli.cmdkit import default_action, emit, group, leaf
22
+ from zyonix_cli.render import heading, next_steps, table
23
+
24
+ KINDS = ("filled", "at_least", "at_most", "equals", "not_equals", "one_of", "contains",
25
+ "not_contains", "starts_with", "length", "at_most_field", "at_least_field",
26
+ "same_as_field", "expression", "error_text")
27
+
28
+
29
+ def _form(p: argparse.ArgumentParser) -> None:
30
+ p.add_argument("--title", required=True, help="what to call this problem")
31
+ p.add_argument("--kind", required=True, choices=KINDS, help="the condition")
32
+ p.add_argument("--field", help="the value to check (see `zyonix checks`)")
33
+ p.add_argument("--value", help="the value to compare with, or the error text")
34
+ p.add_argument("--other", help="the second field of an *_field condition")
35
+ p.add_argument("--expression", help="a rule in the spec's language (--kind expression)")
36
+ p.add_argument("--when-field", help="check only documents where this field ...")
37
+ p.add_argument("--when-value", help="... has this value (empty: is filled in)")
38
+ p.add_argument("--severity", choices=("low", "medium", "high"), default="medium")
39
+ p.add_argument("--review", action="store_true",
40
+ help="ask a person to review it instead of failing the document")
41
+ p.add_argument("--cause", help="the cause to report (a root-cause label; see `zyonix checks`)")
42
+ p.add_argument("--fix", help="what someone should do when this happens")
43
+
44
+
45
+ def register(sub: Any) -> None:
46
+ gp, actions = group(sub, "checks", "problems you want watched: list, test, add, remove, mode")
47
+ leaf(actions, "list", "your checks and the fields they can read", cmd_list, label="checks list")
48
+ default_action(gp, "list")
49
+ _form(leaf(actions, "test", "what a check would have found on past documents (admin key)",
50
+ cmd_test, label="checks test"))
51
+ _form(leaf(actions, "add", "watch every new document for this (admin key)", cmd_add,
52
+ label="checks add"))
53
+ rm = leaf(actions, "remove", "stop checking for this (admin key)", cmd_remove,
54
+ label="checks remove")
55
+ rm.add_argument("id")
56
+ md = leaf(actions, "mode", "how a check counts on new documents (admin key)", cmd_mode,
57
+ label="checks mode")
58
+ md.add_argument("check", help="a check (check:saved, exec:llm_error, a rule id) or a family "
59
+ "ending in ':' (grounding:)")
60
+ md.add_argument("mode", choices=("default", "review", "off"),
61
+ help="default: as Zyonix decides; review: a person decides; off: ignored")
62
+
63
+
64
+ def _body(args: argparse.Namespace) -> dict[str, Any]:
65
+ return {"title": args.title, "kind": args.kind, "field": args.field, "value": args.value,
66
+ "other": args.other, "expression": args.expression, "when_field": args.when_field,
67
+ "when_value": args.when_value, "severity": args.severity, "soft": args.review,
68
+ "cause": args.cause, "fix": args.fix}
69
+
70
+
71
+ MODE_WORDS = {"default": "as Zyonix decides", "review": "a person reviews it", "off": "off"}
72
+
73
+
74
+ def _found(item: dict[str, Any]) -> tuple[str, str, str]:
75
+ """Failed documents, documents waiting for a person, and open problems (#ids)."""
76
+ act = item.get("activity") or {}
77
+ problems = ", ".join(f"#{i}" for i in act.get("problems") or []) or "-"
78
+ return str(act.get("failed", 0)), str(act.get("doubtful", 0)), problems
79
+
80
+
81
+ def cmd_list(client: ApiClient, args: argparse.Namespace) -> int:
82
+ data = client.get("/v1/checks")
83
+ if emit(args, data):
84
+ return 0
85
+ days = data.get("days", 14)
86
+ if data["version"]:
87
+ print(f"Checks on spec version {data['version']} ({data['schema']}), "
88
+ f"last {days} days")
89
+ else:
90
+ print("No spec is active: value checks need one (zyonix spec push). Error types and the "
91
+ f"checks below work without it. Last {days} days.")
92
+ rows = [(c["id"], c["title"], *(_found(c) if c.get("activity") else ("-", "-", "-")),
93
+ MODE_WORDS.get(c.get("mode") or "", "-")) for c in data["custom"]]
94
+ print(heading("Your checks"))
95
+ print(table(["ID", "PROBLEM", "FAILED", "TO REVIEW", "PROBLEMS", "COUNTS"], rows) if rows
96
+ else "no checks of your own yet")
97
+ print(heading("Checks your agent reports (zyonix.check / zyonix.flag)"))
98
+ rows = [(c["check"], str(c["runs"]), *_found(c), MODE_WORDS[c["mode"]])
99
+ for c in data["reported"]]
100
+ print(table(["CHECK", "RUNS", "FAILED", "TO REVIEW", "PROBLEMS", "COUNTS"], rows) if rows
101
+ else "none reported yet")
102
+ print(heading("Checked automatically"))
103
+ print(table(["CHECK", "WHAT", "FAILED", "TO REVIEW", "PROBLEMS", "COUNTS"],
104
+ [(c["check"], c["what"], *_found(c), MODE_WORDS[c["mode"]])
105
+ for c in data["automatic"]]))
106
+ if data["version"]:
107
+ print(heading("From your spec"))
108
+ print(table(["CHECK", "WHAT", "FAILED", "TO REVIEW", "PROBLEMS", "COUNTS"],
109
+ [(r["id"], r["description"] or r["expr"], *_found(r), MODE_WORDS[r["mode"]])
110
+ for r in data["built_in"]]
111
+ + [(f["check"] + "*", f["what"], *_found(f), MODE_WORDS[f["mode"]])
112
+ for f in data["families"]]))
113
+ print(heading("Fields a check can read"))
114
+ print(table(["FIELD", "TYPE"], [(f["path"], f["type"]) for f in data["fields"]]))
115
+ print(heading("Causes"))
116
+ print(table(["LABEL", "MEANING"], [(c["value"], c["title"]) for c in data["causes"]]))
117
+ print(next_steps([('zyonix checks test --title "..." --field <field> --kind filled',
118
+ "try one on past documents"),
119
+ ("zyonix checks mode <check> review|off|default",
120
+ "change how a check counts (admin key)")]))
121
+ return 0
122
+
123
+
124
+ def cmd_mode(client: ApiClient, args: argparse.Namespace) -> int:
125
+ out = client.put("/v1/checks/mode", {"check": args.check, "mode": args.mode})
126
+ if emit(args, out):
127
+ return 0
128
+ print(f"{out['check']}: {MODE_WORDS[out['mode']]}. It applies to new documents.")
129
+ return 0
130
+
131
+
132
+ def cmd_test(client: ApiClient, args: argparse.Namespace) -> int:
133
+ out = client.post("/v1/checks/test", _body(args))
134
+ if emit(args, out):
135
+ return 0
136
+ print(f"It watches: {out['watches']}")
137
+ print(f"{out['failed']} of {out['checked']} past documents would have failed it; "
138
+ f"{out['not_applicable']} did not have the value.")
139
+ for item in out["examples"]:
140
+ doc = item.get("document") or {}
141
+ print(f" {item['trace_id'][:12]} {doc.get('file') or doc.get('label') or '-'}")
142
+ print(next_steps([("zyonix checks add ...", "same options: watch every new document")]))
143
+ return 0
144
+
145
+
146
+ def cmd_add(client: ApiClient, args: argparse.Namespace) -> int:
147
+ out = client.post("/v1/checks", _body(args))
148
+ if emit(args, out):
149
+ return 0
150
+ print(f"Check {out['id']} added (spec version {out['version']}): {out['watches']}")
151
+ print("It applies to new documents.")
152
+ return 0
153
+
154
+
155
+ def cmd_remove(client: ApiClient, args: argparse.Namespace) -> int:
156
+ out = client.delete(f"/v1/checks/{quote(args.id, safe='')}")
157
+ if emit(args, out):
158
+ return 0
159
+ print(f"Check {out['id']} removed (spec version {out['version']}).")
160
+ return 0
zyonix_cli/client.py ADDED
@@ -0,0 +1,130 @@
1
+ """Thin authenticated HTTP client for the Zyonix API (used by test / replay / deploy)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+
8
+ import httpx
9
+ from zyonix._config import Config, http_verify
10
+
11
+
12
+ class CliError(Exception):
13
+ """A user-facing failure (bad config, backend unreachable, request rejected)."""
14
+
15
+
16
+ # The server answers a missing permission with "key lacks scope '<scope>'" (auth.py). The
17
+ # hint only explains that answer in words; the server decides.
18
+ _LACKS = re.compile(r"lacks scope '([a-z_]+)'")
19
+
20
+
21
+ def _status_hint(status: int, detail: str) -> str:
22
+ if status == 401:
23
+ return (
24
+ " (authentication failed: run `zyonix auth login`, or check ZYONIX_API_KEY or "
25
+ "--api-key)"
26
+ )
27
+ m = _LACKS.search(detail) if status == 403 else None
28
+ if m:
29
+ from zyonix_cli.explain import keys_with
30
+
31
+ return f" (this needs {keys_with(m.group(1))})"
32
+ return ""
33
+
34
+
35
+ class ApiClient:
36
+ def __init__(self, cfg: Config, timeout_s: float = 60.0, *, require_credential: bool = True):
37
+ if cfg.boundary_problem: # never connect: not local/allowed, or plain http outside
38
+ hint = (
39
+ ""
40
+ if "egress_allow" not in cfg.boundary_problem
41
+ else (
42
+ ". If it is your own Zyonix deployment, add the host to egress_allow in "
43
+ "zyonix.yaml (or ZYONIX_EGRESS_ALLOW)"
44
+ )
45
+ )
46
+ raise CliError(f"{cfg.boundary_problem}{hint}")
47
+ if not cfg.api_key and require_credential:
48
+ from zyonix_cli import auth_store
49
+
50
+ cfg.api_key = auth_store.get(cfg.endpoint)
51
+ if not cfg.api_key and require_credential:
52
+ raise CliError(
53
+ "no API key or user session: set ZYONIX_API_KEY (a `cli` key from "
54
+ "`zyonix-server create-key --kind cli`), pass --api-key, or run `zyonix auth login`"
55
+ )
56
+ self.base = cfg.endpoint
57
+ try:
58
+ verify = http_verify(cfg.ca_file)
59
+ except Exception as exc:
60
+ raise CliError(f"cannot load the CA bundle {cfg.ca_file}: {exc}") from None
61
+ # redirects are never followed: one could lead to another host or to plain http
62
+ headers = {"Authorization": f"Bearer {cfg.api_key}"} if cfg.api_key else {}
63
+ self._http = httpx.Client(
64
+ timeout=timeout_s, verify=verify, follow_redirects=False, headers=headers
65
+ )
66
+
67
+ def _call(self, method: str, path: str, text: bool = False, **kw: Any) -> Any:
68
+ try:
69
+ r = self._http.request(method, f"{self.base}{path}", **kw)
70
+ except httpx.HTTPError as exc:
71
+ hint = (
72
+ "; check that the deployment is running and the endpoint is right "
73
+ "(`zyonix doctor` checks both)"
74
+ )
75
+ if "CERTIFICATE_VERIFY_FAILED" in str(exc):
76
+ hint = (
77
+ " (the server's certificate is not trusted here: for a deployment with "
78
+ "a private CA set ZYONIX_CA_FILE or pass --ca-file)"
79
+ )
80
+ raise CliError(f"cannot reach {self.base}: {exc}{hint}") from None
81
+ if 300 <= r.status_code < 400: # e.g. the deployment's port 80, which only redirects
82
+ raise CliError(
83
+ f"{self.base} answered with a redirect to "
84
+ f"{r.headers.get('location', 'another address')}: set the endpoint "
85
+ "to the https:// address of your Zyonix deployment"
86
+ )
87
+ if r.status_code >= 400:
88
+ try:
89
+ detail = r.json().get("detail", r.text)
90
+ except (ValueError, AttributeError):
91
+ detail = r.text
92
+ raise CliError(
93
+ f"{method} {path} -> HTTP {r.status_code}: {detail}"
94
+ + _status_hint(r.status_code, str(detail))
95
+ )
96
+ if text:
97
+ return r.text
98
+ try:
99
+ return r.json()
100
+ except ValueError:
101
+ raise CliError(
102
+ f"{method} {path}: {self.base} did not answer with JSON; is it a Zyonix endpoint?"
103
+ ) from None
104
+
105
+ def get(self, path: str, **params: Any) -> Any:
106
+ return self._call(
107
+ "GET", path, params={k: v for k, v in params.items() if v is not None} or None
108
+ )
109
+
110
+ def get_text(self, path: str, **params: Any) -> str:
111
+ return self._call(
112
+ "GET",
113
+ path,
114
+ text=True,
115
+ params={k: v for k, v in params.items() if v is not None} or None,
116
+ )
117
+
118
+ def post(self, path: str, body: dict[str, Any] | None = None, **params: Any) -> Any:
119
+ return self._call(
120
+ "POST", path, json=body if body is not None else {}, params=params or None
121
+ )
122
+
123
+ def put(self, path: str, body: dict[str, Any]) -> Any:
124
+ return self._call("PUT", path, json=body)
125
+
126
+ def delete(self, path: str) -> Any:
127
+ return self._call("DELETE", path)
128
+
129
+ def close(self) -> None:
130
+ self._http.close()