probegate-cli 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.
@@ -0,0 +1 @@
1
+ """Internal client for the assessment platform; execution stays on workers."""
probegate_cli/api.py ADDED
@@ -0,0 +1,75 @@
1
+ """Bounded platform HTTP client; POSTs are never automatically replayed."""
2
+
3
+ import re
4
+ import time
5
+ from datetime import UTC, datetime
6
+ from email.utils import parsedate_to_datetime
7
+
8
+ import httpx
9
+
10
+ from probegate_cli.config import CliError
11
+
12
+
13
+ class Api:
14
+ """Call only the selected origin's existing /api/v1 endpoints."""
15
+
16
+ def __init__(self, platform: str, token: str | None = None):
17
+ """Use TLS verification, finite timeouts and no redirects or ambient proxy credentials."""
18
+ self.client = httpx.Client(
19
+ base_url=platform + "/api/v1/",
20
+ timeout=15,
21
+ follow_redirects=False,
22
+ trust_env=False,
23
+ headers={"Authorization": f"Bearer {token}"} if token else {},
24
+ )
25
+
26
+ def __enter__(self):
27
+ """Manage the connection pool for one command."""
28
+ return self
29
+
30
+ def __exit__(self, *args):
31
+ """Close all pooled connections even when a command fails."""
32
+ self.client.close()
33
+
34
+ def request(self, method: str, path: str, **kwargs) -> httpx.Response:
35
+ """Retry GET transport/5xx/429 failures at most three times; sanitize all errors."""
36
+ for attempt in range(4):
37
+ try:
38
+ response = self.client.request(method, path, **kwargs)
39
+ except httpx.HTTPError:
40
+ if method == "GET" and attempt < 3:
41
+ time.sleep(2**attempt)
42
+ continue
43
+ raise CliError("Network error; server state is unknown.") from None
44
+ if method == "GET" and (response.status_code >= 500 or response.status_code == 429) and attempt < 3:
45
+ delay = 2**attempt
46
+ if response.status_code == 429:
47
+ raw = response.headers.get("Retry-After", "")
48
+ if raw.isdigit():
49
+ delay = min(30, int(raw)) if len(raw) < 10 else 30
50
+ else:
51
+ try:
52
+ delay = max(0, min(30, (parsedate_to_datetime(raw) - datetime.now(UTC)).total_seconds()))
53
+ except (ValueError, TypeError, OverflowError):
54
+ delay = 30
55
+ time.sleep(delay)
56
+ continue
57
+ if not 200 <= response.status_code < 300:
58
+ # Never echo arbitrary server messages, request bodies, URLs or auth headers.
59
+ code = "api_error"
60
+ try:
61
+ candidate = response.json().get("error", "")
62
+ if isinstance(candidate, str) and re.fullmatch(r"[a-z_]{1,64}", candidate):
63
+ code = candidate
64
+ except (ValueError, AttributeError):
65
+ pass
66
+ raise CliError(f"HTTP {response.status_code} ({code}); check platform permissions/configuration.")
67
+ return response
68
+ raise CliError("Retry limit reached.")
69
+
70
+ def json(self, method: str, path: str, **kwargs):
71
+ """Require valid JSON without printing the response on decoding failure."""
72
+ try:
73
+ return self.request(method, path, **kwargs).json()
74
+ except ValueError:
75
+ raise CliError("Platform returned invalid JSON.") from None
@@ -0,0 +1,116 @@
1
+ """Atomic local persistence and strict platform origin validation."""
2
+
3
+ import json
4
+ import os
5
+ import tempfile
6
+ from pathlib import Path
7
+ from urllib.parse import urlsplit
8
+
9
+ from platformdirs import user_config_path, user_state_path
10
+
11
+ from probegate_cli.models import Config, Intent
12
+
13
+
14
+ class CliError(Exception):
15
+ """Safe diagnostic with a documented process exit code."""
16
+
17
+ def __init__(self, message: str, code: int = 1):
18
+ """Store only a user-safe message, never a raw HTTP exception."""
19
+ super().__init__(message)
20
+ self.code = code
21
+
22
+
23
+ def origin(value: str) -> str:
24
+ """Accept HTTPS origins and explicit loopback HTTP, without URL credentials."""
25
+ try:
26
+ if any(char.isspace() or not char.isprintable() for char in value):
27
+ raise ValueError
28
+ parsed = urlsplit(value)
29
+ port = parsed.port
30
+ if (
31
+ parsed.scheme not in {"http", "https"}
32
+ or not parsed.hostname
33
+ or parsed.username is not None
34
+ or parsed.password is not None
35
+ or parsed.query
36
+ or parsed.fragment
37
+ or parsed.path not in {"", "/"}
38
+ ):
39
+ raise ValueError
40
+ if parsed.scheme == "http" and parsed.hostname not in {"localhost", "127.0.0.1", "::1"}:
41
+ raise ValueError
42
+ host = parsed.hostname.lower()
43
+ host = f"[{host}]" if ":" in host else host
44
+ suffix = f":{port}" if port and port != (443 if parsed.scheme == "https" else 80) else ""
45
+ return f"{parsed.scheme}://{host}{suffix}"
46
+ except ValueError:
47
+ raise CliError("Platform must be an HTTPS origin (HTTP allowed only on loopback).", 2) from None
48
+
49
+
50
+ def config_path() -> Path:
51
+ """Locate non-secret config, allowing an explicit isolated config file."""
52
+ return Path(os.environ.get("PROBEGATE_CONFIG", user_config_path("probegate") / "config.json"))
53
+
54
+
55
+ def state_path() -> Path:
56
+ """Locate intent journals separately from credentials."""
57
+ return Path(os.environ.get("PROBEGATE_STATE_DIR", user_state_path("probegate") / "intents"))
58
+
59
+
60
+ def atomic_write(path: Path, data: bytes, overwrite: bool = True) -> None:
61
+ """Publish complete bytes atomically; preserve any previous file on failure."""
62
+ path.parent.mkdir(parents=True, exist_ok=True)
63
+ fd, temporary = tempfile.mkstemp(prefix=".probegate-", dir=path.parent)
64
+ try:
65
+ with os.fdopen(fd, "wb") as stream:
66
+ stream.write(data)
67
+ stream.flush()
68
+ os.fsync(stream.fileno())
69
+ if overwrite:
70
+ os.replace(temporary, path)
71
+ else:
72
+ # Hard-link publication is atomic and refuses races with existing destinations.
73
+ os.link(temporary, path)
74
+ finally:
75
+ Path(temporary).unlink(missing_ok=True)
76
+
77
+
78
+ def load_config() -> Config | None:
79
+ """Read config strictly and reject corrupt data without exposing its contents."""
80
+ path = config_path()
81
+ if not path.exists():
82
+ return None
83
+ try:
84
+ config = Config.model_validate_json(path.read_bytes())
85
+ config.platform_url = origin(config.platform_url)
86
+ return config
87
+ except (ValueError, OSError):
88
+ raise CliError("Invalid or unreadable config; repair it or select PROBEGATE_CONFIG.", 2) from None
89
+
90
+
91
+ def save_config(config: Config) -> None:
92
+ """Persist only validated non-secret defaults."""
93
+ atomic_write(config_path(), config.model_dump_json(indent=2).encode())
94
+
95
+
96
+ def save_intent(intent: Intent, overwrite: bool = True) -> None:
97
+ """Persist a validated request before any network mutation."""
98
+ atomic_write(state_path() / f"{intent.id}.json", intent.model_dump_json(indent=2).encode(), overwrite)
99
+
100
+
101
+ def load_intent(identifier) -> Intent:
102
+ """Load an exact intent by UUID, refusing arbitrary filesystem paths."""
103
+ try:
104
+ from uuid import UUID
105
+
106
+ intent = Intent.model_validate_json((state_path() / f"{UUID(str(identifier))}.json").read_bytes())
107
+ if str(intent.id) != str(identifier) or origin(intent.platform_url) != intent.platform_url:
108
+ raise ValueError
109
+ return intent
110
+ except (ValueError, OSError):
111
+ raise CliError("Invalid or unreadable intent.", 2) from None
112
+
113
+
114
+ def json_bytes(value) -> bytes:
115
+ """Encode deterministic JSON without terminal formatting."""
116
+ return json.dumps(value, ensure_ascii=True, sort_keys=True).encode()
@@ -0,0 +1,63 @@
1
+ """Credential store access without plaintext or insecure backend fallback."""
2
+
3
+ import os
4
+
5
+ import keyring
6
+ from keyring.errors import KeyringError, PasswordDeleteError
7
+
8
+ from probegate_cli.config import CliError
9
+
10
+
11
+ def service(platform: str) -> str:
12
+ """Bind credentials to a normalized origin and this CLI."""
13
+ return f"probegate:{platform}"
14
+
15
+
16
+ def secure_backend():
17
+ """Allow only native OS stores or the Linux Secret Service implementation."""
18
+ try:
19
+ backend = keyring.get_keyring()
20
+ except (KeyringError, RuntimeError):
21
+ raise CliError("OS credential store unavailable.") from None
22
+ module = type(backend).__module__
23
+ if module not in {"keyring.backends.Windows", "keyring.backends.macOS", "keyring.backends.SecretService"}:
24
+ raise CliError("No supported secure keyring; configure an OS store or explicitly set PROBEGATE_TOKEN.")
25
+ return backend
26
+
27
+
28
+ def token(platform: str, account: str | None) -> str:
29
+ """Prefer an explicit environment token; otherwise read the selected OS account."""
30
+ value = os.environ.get("PROBEGATE_TOKEN")
31
+ if value is not None:
32
+ if not value.strip() or any(char.isspace() for char in value):
33
+ raise CliError("Invalid PROBEGATE_TOKEN.", 2)
34
+ return value
35
+ if not account:
36
+ raise CliError("Login first or explicitly set PROBEGATE_TOKEN.")
37
+ try:
38
+ value = secure_backend().get_password(service(platform), account)
39
+ except (KeyringError, RuntimeError):
40
+ raise CliError("OS credential store unavailable; unlock it or explicitly set PROBEGATE_TOKEN.") from None
41
+ if not value:
42
+ raise CliError("No saved credential; login again.")
43
+ return value
44
+
45
+
46
+ def store(platform: str, account: str, value: str) -> None:
47
+ """Save only the token in a native credential store."""
48
+ try:
49
+ secure_backend().set_password(service(platform), account, value)
50
+ except (KeyringError, RuntimeError):
51
+ raise CliError("Could not save token securely; no plaintext fallback is available.") from None
52
+
53
+
54
+ def remove(platform: str, account: str) -> None:
55
+ """Remove the selected stored credential without claiming JWT revocation."""
56
+ try:
57
+ backend = secure_backend()
58
+ if backend.get_password(service(platform), account) is not None:
59
+ backend.delete_password(service(platform), account)
60
+ except PasswordDeleteError:
61
+ raise CliError("Credential deletion failed; check the OS store.") from None
62
+ except (KeyringError, RuntimeError):
63
+ raise CliError("OS credential store unavailable; credential deletion was not verified.") from None
probegate_cli/main.py ADDED
@@ -0,0 +1,395 @@
1
+ """Cloud-only CLI commands with explicit confirmation and durable POST recovery."""
2
+
3
+ import functools
4
+ import json
5
+ import os
6
+ import re
7
+ import sys
8
+ import time
9
+ from datetime import UTC, datetime
10
+ from pathlib import Path
11
+ from uuid import UUID, uuid4
12
+
13
+ import typer
14
+ from pydantic import ValidationError
15
+ from rich.console import Console
16
+
17
+ from probegate_cli import credentials
18
+ from probegate_cli.api import Api
19
+ from probegate_cli.config import (
20
+ CliError,
21
+ atomic_write,
22
+ load_config,
23
+ load_intent,
24
+ origin,
25
+ save_config,
26
+ save_intent,
27
+ )
28
+ from probegate_cli.models import AgentConfig, Config, Intent, RunBody, Status
29
+
30
+ app = typer.Typer(no_args_is_help=True, pretty_exceptions_enable=False, context_settings={"color": False})
31
+
32
+
33
+ def safe_text(value: str) -> str:
34
+ """Remove terminal control sequences and control characters from diagnostics."""
35
+ value = re.sub(r"\x1b\][^\x07]*(?:\x07|\x1b\\)", "", value)
36
+ value = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", value)
37
+ return "".join(char for char in value if char.isprintable() or char == "\n")
38
+
39
+
40
+ def diagnostic(value: str) -> None:
41
+ """Write plain, markup-free diagnostics to stderr."""
42
+ Console(stderr=True, color_system=None, highlight=False, markup=False).print(safe_text(value))
43
+
44
+
45
+ def guarded(function):
46
+ """Convert expected failures to safe diagnostics and documented exit codes."""
47
+
48
+ @functools.wraps(function)
49
+ def wrapper(*args, **kwargs):
50
+ """Execute a command without exposing validation inputs or raw exceptions."""
51
+ try:
52
+ return function(*args, **kwargs)
53
+ except CliError as exc:
54
+ diagnostic(str(exc))
55
+ raise typer.Exit(exc.code) from None
56
+ except ValidationError:
57
+ diagnostic("Invalid configuration, parameters, or platform response; check required fields and types.")
58
+ raise typer.Exit(2) from None
59
+ except OSError:
60
+ diagnostic("Local file operation failed; check paths and permissions.")
61
+ raise typer.Exit(1) from None
62
+
63
+ return wrapper
64
+
65
+
66
+ def emit(value, as_json: bool) -> None:
67
+ """Emit one complete JSON document or plain text with no ANSI escapes."""
68
+ if as_json:
69
+ typer.echo(json.dumps(value, ensure_ascii=True, sort_keys=True))
70
+ else:
71
+ diagnostic(json.dumps(value, ensure_ascii=True, indent=2))
72
+
73
+
74
+ def context(platform: str | None, account: str | None = None) -> Config:
75
+ """Resolve flags over published environment settings over saved defaults."""
76
+ saved = load_config()
77
+ url = platform or os.environ.get("PROBEGATE_PLATFORM") or (saved.platform_url if saved else None)
78
+ if not url:
79
+ raise CliError("Select --platform or PROBEGATE_PLATFORM, or run init.", 2)
80
+ normalized = origin(url)
81
+ # Never carry an account selection across origins.
82
+ selected = account or os.environ.get("PROBEGATE_ACCOUNT")
83
+ if saved and saved.platform_url == normalized:
84
+ return saved.model_copy(update={"account": selected or saved.account})
85
+ return Config(platform_url=normalized, account=selected)
86
+
87
+
88
+ def confirm(message: str, yes: bool) -> None:
89
+ """Require explicit consent, failing closed when stdin is not interactive."""
90
+ if yes:
91
+ return
92
+ if not sys.stdin.isatty():
93
+ raise CliError("Non-interactive input requires --yes.", 2)
94
+ if not typer.confirm(message, err=True):
95
+ raise CliError("Cancelled.", 2)
96
+
97
+
98
+ def authenticated(config: Config) -> Api:
99
+ """Construct an API client with a credential scoped to the selected origin."""
100
+ return Api(config.platform_url, credentials.token(config.platform_url, config.account))
101
+
102
+
103
+ def parse_status(value) -> Status:
104
+ """Treat malformed platform status as an API failure, independent of local config errors."""
105
+ try:
106
+ return Status.model_validate(value)
107
+ except ValidationError:
108
+ raise CliError("Platform returned an invalid run status.") from None
109
+
110
+
111
+ def status_code(status: str) -> int:
112
+ """Map lifecycle results to operation exits without applying any quality gate."""
113
+ return {"FAILED": 1, "STOPPED": 3}.get(status, 0)
114
+
115
+
116
+ @app.callback()
117
+ def options(no_color: bool = typer.Option(False, "--no-color")):
118
+ """Control platform assessments; all execution occurs on platform workers."""
119
+ # Output is deliberately plain, so redirected output never contains animation/ANSI.
120
+
121
+
122
+ @app.command()
123
+ @guarded
124
+ def init(
125
+ platform: str | None = None,
126
+ project: UUID | None = None,
127
+ target: UUID | None = None,
128
+ suite: UUID | None = None,
129
+ suite_version: str | None = None,
130
+ category: str | None = None,
131
+ account: str | None = None,
132
+ polling_interval: float = 2,
133
+ overwrite: bool = False,
134
+ as_json: bool = typer.Option(False, "--json"),
135
+ ):
136
+ """Save non-secret local defaults without creating resources or contacting a chatbot."""
137
+ config = context(platform, account)
138
+ if load_config() and not overwrite:
139
+ confirm("Replace local defaults?", False)
140
+ config = Config.model_validate(
141
+ {
142
+ **config.model_dump(),
143
+ "project_id": project or config.project_id,
144
+ "target_id": target or config.target_id,
145
+ "suite_id": suite or config.suite_id,
146
+ "suite_version": suite_version or config.suite_version,
147
+ "category": category.upper() if category else config.category,
148
+ "polling_interval": polling_interval,
149
+ }
150
+ )
151
+ save_config(config)
152
+ emit(config.model_dump(mode="json"), as_json)
153
+
154
+
155
+ @app.command()
156
+ @guarded
157
+ def login(platform: str | None = None, email: str = typer.Option(..., prompt=True)):
158
+ """Prompt privately for a password and save the returned token only in the OS store."""
159
+ config = context(platform, email)
160
+ credentials.secure_backend()
161
+ password = typer.prompt("Password", hide_input=True, err=True)
162
+ with Api(config.platform_url) as api:
163
+ result = api.json("POST", "auth/login", json={"email": email, "password": password})
164
+ if (
165
+ not isinstance(result, dict)
166
+ or result.get("token_type") != "bearer"
167
+ or not isinstance(result.get("access_token"), str)
168
+ or not result["access_token"]
169
+ or any(char.isspace() for char in result["access_token"])
170
+ ):
171
+ raise CliError("Invalid authentication response.")
172
+ credentials.store(config.platform_url, email, result["access_token"])
173
+ config.account = email
174
+ save_config(config)
175
+ diagnostic("Login saved securely. PROBEGATE_TOKEN, if set, takes precedence.")
176
+
177
+
178
+ @app.command()
179
+ @guarded
180
+ def logout(platform: str | None = None, account: str | None = None):
181
+ """Delete a selected local credential; the platform JWT is not revoked."""
182
+ config = context(platform, account)
183
+ if config.account:
184
+ credentials.remove(config.platform_url, config.account)
185
+ elif "PROBEGATE_TOKEN" not in os.environ:
186
+ raise CliError("Select --account to remove a stored credential.", 2)
187
+ diagnostic("Selected local credential removed; server JWT was not revoked.")
188
+ if "PROBEGATE_TOKEN" in os.environ:
189
+ diagnostic("Unset PROBEGATE_TOKEN in the parent shell to stop using the environment token.")
190
+
191
+
192
+ @app.command()
193
+ @guarded
194
+ def run(
195
+ platform: str | None = None,
196
+ project: UUID | None = None,
197
+ target: UUID | None = None,
198
+ suite: UUID | None = None,
199
+ suite_version: str | None = None,
200
+ category: str | None = None,
201
+ mode: str | None = None,
202
+ max_requests: int | None = None,
203
+ timeout_s: int | None = None,
204
+ max_steps: int | None = None,
205
+ max_tokens: int | None = None,
206
+ resume_intent: UUID | None = None,
207
+ yes: bool = False,
208
+ as_json: bool = typer.Option(False, "--json"),
209
+ ):
210
+ """Confirm one independent run, or explicitly replay a durable intent with the same key/body."""
211
+ config = context(platform)
212
+ if resume_intent:
213
+ if any(
214
+ value is not None
215
+ for value in (
216
+ platform,
217
+ project,
218
+ target,
219
+ suite,
220
+ suite_version,
221
+ category,
222
+ mode,
223
+ max_requests,
224
+ timeout_s,
225
+ max_steps,
226
+ max_tokens,
227
+ )
228
+ ):
229
+ raise CliError(
230
+ "Resume forbids origin and payload overrides; select the original platform in config/env.", 2
231
+ )
232
+ intent = load_intent(resume_intent)
233
+ if config.platform_url != intent.platform_url:
234
+ raise CliError("Resume platform differs from the saved intent.", 2)
235
+ if intent.run_id:
236
+ emit({"run_id": str(intent.run_id), "intent_id": str(intent.id), "attached": True}, as_json)
237
+ return
238
+ else:
239
+ project_id = project or config.project_id
240
+ if project_id is None:
241
+ raise CliError("Select --project or configure a Project ID.", 2)
242
+ agent = None
243
+ if max_steps is not None or max_tokens is not None:
244
+ agent = AgentConfig(max_steps=max_steps, max_tokens=max_tokens)
245
+ body = RunBody(
246
+ target_id=target or config.target_id,
247
+ suite_id=suite or config.suite_id,
248
+ category=(category.upper() if category else config.category),
249
+ suite_version=suite_version or config.suite_version,
250
+ mode=(mode or "pipeline").upper(),
251
+ max_requests=max_requests,
252
+ timeout_s=timeout_s,
253
+ agent_config=agent,
254
+ )
255
+ intent = Intent(
256
+ id=uuid4(),
257
+ platform_url=config.platform_url,
258
+ project_id=project_id,
259
+ key=uuid4(),
260
+ body=body,
261
+ created_at=datetime.now(UTC).isoformat(),
262
+ )
263
+ diagnostic(json.dumps({"project_id": str(intent.project_id), **intent.body.model_dump(mode="json")}))
264
+ confirm("Submit this assessment to platform workers?", yes)
265
+ # Resolve credentials before journaling, but finish durable persistence before any POST.
266
+ with authenticated(config) as api:
267
+ if not resume_intent:
268
+ save_intent(intent, overwrite=False)
269
+ diagnostic(f"Intent {intent.id}; recover with: probegate run --resume-intent {intent.id} --yes")
270
+ result = api.json(
271
+ "POST",
272
+ f"projects/{intent.project_id}/runs",
273
+ json=intent.body.model_dump(mode="json"),
274
+ headers={"Idempotency-Key": str(intent.key)},
275
+ )
276
+ try:
277
+ run_id = UUID(result["run_id"])
278
+ if result["status"] != "QUEUED":
279
+ raise ValueError
280
+ except (KeyError, TypeError, ValueError):
281
+ raise CliError("Invalid create response; recover using the saved intent.") from None
282
+ diagnostic(f"Run {run_id}")
283
+ intent.run_id = run_id
284
+ save_intent(intent)
285
+ emit({"run_id": str(run_id), "intent_id": str(intent.id), "status": "QUEUED"}, as_json)
286
+
287
+
288
+ @app.command()
289
+ @guarded
290
+ def watch(
291
+ run: UUID = typer.Option(..., "--run"),
292
+ platform: str | None = None,
293
+ interval: float | None = typer.Option(None, min=0.2, max=60),
294
+ once: bool = False,
295
+ as_json: bool = typer.Option(False, "--json"),
296
+ ):
297
+ """Attach by run ID; Ctrl+C detaches without sending a stop request."""
298
+ config = context(platform)
299
+ diagnostic(f"Run {run}; attach: probegate watch --run {run}; stop: probegate stop --run {run}")
300
+ try:
301
+ with authenticated(config) as api:
302
+ while True:
303
+ status = parse_status(api.json("GET", f"runs/{run}"))
304
+ value = {"run_id": str(run), **status.model_dump()}
305
+ if not as_json:
306
+ label = (
307
+ "reserved steps (remaining is unused capacity)" if status.mode == "AGENT" else "completed cases"
308
+ )
309
+ diagnostic(
310
+ f"{status.status}: {status.counts.done}/{status.counts.total} {label}; "
311
+ f"reason={status.stopped_reason}; findings require server review"
312
+ )
313
+ terminal = status.status in {"COMPLETED", "FAILED", "STOPPED"}
314
+ if once or terminal:
315
+ if as_json:
316
+ emit(value, True)
317
+ raise typer.Exit(status_code(status.status))
318
+ time.sleep(interval or config.polling_interval)
319
+ except KeyboardInterrupt:
320
+ diagnostic(f"Detached from {run}; attach: probegate watch --run {run}; stop: probegate stop --run {run}")
321
+ raise typer.Exit(130) from None
322
+
323
+
324
+ @app.command()
325
+ @guarded
326
+ def stop(
327
+ run: UUID = typer.Option(..., "--run"),
328
+ platform: str | None = None,
329
+ yes: bool = False,
330
+ as_json: bool = typer.Option(False, "--json"),
331
+ ):
332
+ """Confirm stop separately and verify the server lifecycle before claiming it stopped."""
333
+ config = context(platform)
334
+ diagnostic(f"Run {run}")
335
+ with authenticated(config) as api:
336
+ before = parse_status(api.json("GET", f"runs/{run}"))
337
+ diagnostic(json.dumps(before.model_dump()))
338
+ confirm("Request stop for this run?", yes)
339
+ api.json("POST", f"runs/{run}/stop")
340
+ status = parse_status(api.json("GET", f"runs/{run}"))
341
+ emit({"run_id": str(run), **status.model_dump()}, as_json)
342
+ if status.status in {"RUNNING", "QUEUED"}:
343
+ raise CliError(f"Stop requested but not yet verified; watch --run {run}.")
344
+ raise typer.Exit(status_code(status.status))
345
+
346
+
347
+ @app.command()
348
+ @guarded
349
+ def findings(
350
+ run: UUID = typer.Option(..., "--run"),
351
+ platform: str | None = None,
352
+ as_json: bool = typer.Option(False, "--json"),
353
+ ):
354
+ """Read server finding review states without classifying pending findings as confirmed bugs."""
355
+ with authenticated(context(platform)) as api:
356
+ value = api.json("GET", f"runs/{run}/findings")
357
+ emit(value, as_json)
358
+
359
+
360
+ @app.command()
361
+ @guarded
362
+ def report(
363
+ run: UUID = typer.Option(..., "--run"),
364
+ output: Path = typer.Option(...),
365
+ format: str = "json",
366
+ platform: str | None = None,
367
+ overwrite: bool = False,
368
+ as_json: bool = typer.Option(False, "--json"),
369
+ ):
370
+ """Download the exact server HTML/JSON body and atomically publish a complete report."""
371
+ if format not in {"html", "json"}:
372
+ raise CliError("Report format must be html or json.", 2)
373
+ if output.exists() and not overwrite:
374
+ raise CliError("Output exists; use --overwrite.", 2)
375
+ with authenticated(context(platform)) as api:
376
+ response = api.request("GET", f"runs/{run}/report", params={"format": format})
377
+ data = response.content
378
+ content_type = response.headers.get("content-type", "").split(";")[0].strip()
379
+ if format == "json":
380
+ try:
381
+ document = json.loads(data)
382
+ if not isinstance(document, dict) or document.get("schema_version") != "1.0":
383
+ raise ValueError
384
+ except (ValueError, UnicodeError):
385
+ raise CliError("Invalid report JSON/schema_version; destination was not changed.") from None
386
+ if content_type != "application/json":
387
+ raise CliError("Unexpected JSON report media type.")
388
+ elif content_type != "text/html" or not data:
389
+ raise CliError("Unexpected or empty HTML report.")
390
+ atomic_write(output, data, overwrite)
391
+ # Report JSON on stdout retains the report schema, rather than wrapping it in metadata.
392
+ if as_json and format == "json":
393
+ sys.stdout.write(data.decode("utf-8"))
394
+ else:
395
+ emit({"output": str(output), "format": format, "bytes": len(data)}, as_json)
@@ -0,0 +1,83 @@
1
+ """Validated local configuration and wire request/response subsets."""
2
+
3
+ from typing import Literal
4
+ from uuid import UUID
5
+
6
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
7
+
8
+
9
+ class Config(BaseModel):
10
+ """Non-secret defaults for one explicitly selected platform account."""
11
+
12
+ model_config = ConfigDict(extra="forbid")
13
+ version: Literal[1] = 1
14
+ platform_url: str
15
+ account: str | None = None
16
+ project_id: UUID | None = None
17
+ target_id: UUID | None = None
18
+ suite_id: UUID | None = None
19
+ suite_version: str | None = None
20
+ category: Literal["QUALITY", "SECURITY", "SAFETY"] | None = None
21
+ polling_interval: float = Field(default=2, ge=0.2, le=60)
22
+
23
+
24
+ class AgentConfig(BaseModel):
25
+ """Explicit budgets for an independent Agent execution."""
26
+
27
+ model_config = ConfigDict(extra="forbid")
28
+ max_steps: int = Field(gt=0, strict=True)
29
+ max_tokens: int = Field(gt=0, strict=True)
30
+
31
+
32
+ class RunBody(BaseModel):
33
+ """Contract fields submitted after local confirmation, without Project defaults."""
34
+
35
+ model_config = ConfigDict(extra="forbid")
36
+ target_id: UUID
37
+ suite_id: UUID
38
+ category: Literal["QUALITY", "SECURITY", "SAFETY"]
39
+ suite_version: str = Field(min_length=1)
40
+ mode: Literal["PIPELINE", "AGENT"]
41
+ max_requests: int = Field(gt=0, strict=True)
42
+ timeout_s: int = Field(gt=0, strict=True)
43
+ agent_config: AgentConfig | None = None
44
+ confirm: Literal[True] = True
45
+ use_project_defaults: Literal[False] = False
46
+
47
+ @model_validator(mode="after")
48
+ def check_agent(self):
49
+ """Require Agent limits only for Agent mode."""
50
+ if (self.mode == "AGENT") != (self.agent_config is not None):
51
+ raise ValueError("AGENT requires max_steps/max_tokens; PIPELINE forbids them")
52
+ return self
53
+
54
+
55
+ class Intent(BaseModel):
56
+ """Durable replay identity, destination and exact non-secret request body."""
57
+
58
+ model_config = ConfigDict(extra="forbid")
59
+ id: UUID
60
+ platform_url: str
61
+ project_id: UUID
62
+ key: UUID
63
+ body: RunBody
64
+ created_at: str
65
+ run_id: UUID | None = None
66
+
67
+
68
+ class Counts(BaseModel):
69
+ """Server progress counts; Agent done counts reserved steps."""
70
+
71
+ total: int = Field(ge=0)
72
+ done: int = Field(ge=0)
73
+ remaining: int = Field(ge=0)
74
+
75
+
76
+ class Status(BaseModel):
77
+ """Server-owned lifecycle and outcome; completion does not imply PASS."""
78
+
79
+ status: Literal["QUEUED", "RUNNING", "COMPLETED", "FAILED", "STOPPED"]
80
+ mode: Literal["PIPELINE", "AGENT"]
81
+ counts: Counts
82
+ stopped_reason: str | None = None
83
+ outcome: dict
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: probegate-cli
3
+ Version: 0.1.0
4
+ Summary: Internal cloud assessment platform CLI
5
+ Requires-Python: >=3.12
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: typer==0.27.2
8
+ Requires-Dist: rich==15.0.0
9
+ Requires-Dist: httpx==0.28.1
10
+ Requires-Dist: pydantic==2.14.3
11
+ Requires-Dist: keyring==25.7.0
12
+ Requires-Dist: platformdirs==4.5.1
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest<10,>=8; extra == "test"
15
+ Requires-Dist: ruff<1,>=0.11; extra == "test"
16
+ Requires-Dist: build<2,>=1; extra == "test"
17
+
18
+ # ProbeGate CLI (internal 0.1.0)
19
+
20
+ Cloud-only client: assessments execute on existing platform workers. Prepare Project,
21
+ authorized Target and published Suite on the platform first. No backend, DB, Redis,
22
+ MinIO or LLM key is required on the client. No registry release is authorized.
23
+
24
+ Build/install with Python 3.12 (from repository root):
25
+
26
+ ```text
27
+ python -m pip install build
28
+ python -m build --wheel cli
29
+ python -m pip install cli/dist/probegate_cli-0.1.0-py3-none-any.whl
30
+ probegate --help
31
+ ```
32
+
33
+ Development/checks: `python -m pip install -e "cli[test]"`, then `make lint` and
34
+ `make test`. Existing root tests remain enabled. `PYTHON` selects the interpreter;
35
+ `PYTEST_ARGS` supplies optional pytest arguments. GNU Make is needed for make commands.
36
+
37
+ ```text
38
+ probegate login --platform https://assessment.example --email qa@example.org
39
+ probegate init --project <uuid> --target <uuid> --suite <uuid> --suite-version 1.0 --category QUALITY --overwrite
40
+ probegate run --mode pipeline --max-requests 20 --timeout-s 120 --yes --json
41
+ probegate run --mode agent --max-requests 10 --timeout-s 120 --max-steps 10 --max-tokens 2000 --yes --json
42
+ probegate watch --run <uuid>
43
+ probegate watch --run <uuid> --once --json
44
+ probegate findings --run <uuid> --json
45
+ probegate stop --run <uuid> --yes --json
46
+ probegate report --run <uuid> --format json --output report.json --json
47
+ probegate report --run <uuid> --format html --output report.html
48
+ probegate logout
49
+ ```
50
+
51
+ `--platform` is an origin, without `/api/v1`; the client adds that existing prefix.
52
+ Remote origins require HTTPS. HTTP is accepted only for explicit localhost/127.0.0.1/::1
53
+ origins. TLS verification stays enabled. Redirects and ambient HTTP proxy configuration
54
+ are disabled, so bearer credentials cannot be forwarded to a redirected origin.
55
+
56
+ Passwords are prompted with hidden input, never accepted as arguments. Native Windows
57
+ Credential Manager and Linux Secret Service are supported secure stores. A missing,
58
+ locked or unsupported backend fails loudly. There is no plaintext fallback. An explicit
59
+ `PROBEGATE_TOKEN` overrides the saved token; logout cannot unset it in the parent shell
60
+ or revoke the JWT server-side. A saved token is scoped to platform origin and account.
61
+ Use `PROBEGATE_ACCOUNT` or `init --account` to select an account for data commands.
62
+
63
+ Config contains non-secret defaults only. Paths default to platformdirs user config/state
64
+ locations. Override them with `PROBEGATE_CONFIG` (file) and `PROBEGATE_STATE_DIR` (directory).
65
+ Configuration precedence is flags > `PROBEGATE_PLATFORM`/`PROBEGATE_ACCOUNT` > config.
66
+ Resource IDs, category, version and polling interval come from flags/config; resource-ID
67
+ environment variables are not supported. Poll interval defaults to 2 seconds and may be
68
+ changed by `init --polling-interval` or `watch --interval` (0.2–60 seconds).
69
+ Malformed config fails; repair it or select a new config file. `init` replaces existing
70
+ config only after interactive confirmation or `--overwrite`.
71
+
72
+ Run budgets are mandatory. Each invocation creates one PIPELINE or independent AGENT
73
+ run. Project defaults are explicitly disabled (`use_project_defaults:false`), so they
74
+ cannot silently add strategies/rubric/profile. Agent uses the server's documented
75
+ strategy defaults; this CLI does not expose custom strategies or pipeline_first.
76
+ Confirmation displays the exact request plus Project ID. Noninteractive submission
77
+ and stop require `--yes`. Target authorization, suite publication, tenant/RBAC and
78
+ execution limits continue to be enforced by the backend and worker.
79
+
80
+ Before creating a run, the client writes an atomic non-secret intent containing UUID,
81
+ origin, Project, idempotency key, exact body, timestamp and nullable run ID. If POST loses
82
+ its response, keep that intent and resume explicitly:
83
+
84
+ ```text
85
+ probegate run --resume-intent <intent-uuid> --yes --json
86
+ ```
87
+
88
+ Select the original origin through config or `PROBEGATE_PLATFORM`; resume forbids
89
+ all origin/payload flags. It reuses the saved Project/body/key. If the run ID was
90
+ already saved, it returns that ID without POST. If response persistence failed after
91
+ creation, resubmitting the same intent still recovers the server run. Never edit a
92
+ journal to create a new payload or remove it while recovering. Same key/different body
93
+ is a backend 409. POSTs never automatically retry. Auth failures require explicit login
94
+ and explicit retry; the client never replays writes after login automatically.
95
+
96
+ GET retries transport errors, 5xx and 429 at most three times after the initial attempt.
97
+ Delays are 1/2/4 seconds; Retry-After seconds/date is capped at 30 seconds per retry.
98
+ Other HTTP errors do not retry. Each HTTP request has a 15 second timeout, separate
99
+ from the run's worker execution timeout. Watch exits after exhausted retries without
100
+ changing server state. Ctrl+C detaches (130) and prints attach/stop instructions.
101
+
102
+ Agent progress means reserved steps, and remaining means unused capacity. COMPLETED
103
+ does not imply PASS. Finding states remain server-owned; pending findings are not
104
+ confirmed bugs. Status does not depend on findings/report permissions. Stop verifies
105
+ the current server status; an unverified stop request fails with guidance to watch.
106
+
107
+ All terminal output is plain, without animation or markup interpretation. Data commands
108
+ accept `--json`: one complete document on stdout, diagnostics on stderr. Watch JSON
109
+ waits for terminal status unless `--once` is selected. Report JSON stdout retains the
110
+ original report schema; files always retain exact server response bytes.
111
+ Downloads validate media type/JSON schema_version 1.0 before atomic publication.
112
+ Existing files require `--overwrite`; failed downloads keep any previous destination.
113
+ Files are not opened automatically. Reports may contain sensitive redacted evidence;
114
+ protect and share downloaded files under your organization's rules.
115
+
116
+ Exit codes: 0 successful operation/COMPLETED (even with FAIL findings); 1 API/auth/network,
117
+ local I/O, invalid server report or FAILED; 2 invalid parameters/config; 3 STOPPED;
118
+ 130 interrupted watch. Stop returning STOPPED also exits 3. No quality gate exit policy.
119
+
120
+ Evidence and limitations: [verification](../docs/qa/cli-platform/verification.md),
121
+ [contract review](../docs/specs/cli-platform/review.md). Windows and Ubuntu WSL wheel
122
+ checks do not certify staging, a native Linux desktop credential store or all Linux
123
+ systems. Local runner, extension and CI gate remain outside scope.
@@ -0,0 +1,11 @@
1
+ probegate_cli/__init__.py,sha256=UzGUWSve6ZeOXMkS_US2yqJ1vvqr9APnW8Ct3ABd_Dw,80
2
+ probegate_cli/api.py,sha256=y55ifGX9vZUj9MpJ25zpKF1R1kczSUnFabu0vPbfjnw,3287
3
+ probegate_cli/config.py,sha256=KqphsYxazwikK0Lh23t54RRmMUQaUxdt2_U7TTnjzUE,4474
4
+ probegate_cli/credentials.py,sha256=95EKfmsKSd9ZMT3P7p7SlGyqLyhyhbk2_1CrnDM8VI8,2670
5
+ probegate_cli/main.py,sha256=y-yGpx6WScHoqEfiE_nqxNGWELenuS1KicgBi5SfqMk,15839
6
+ probegate_cli/models.py,sha256=9BQC7eSQBfpG2Q5THm6iPKJaWpSLDObRQupahcdqXT4,2564
7
+ probegate_cli-0.1.0.dist-info/METADATA,sha256=U0wf9uH2nEHAAOLxtK14hSIRhx_Np-y94FhIL455nx0,7072
8
+ probegate_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ probegate_cli-0.1.0.dist-info/entry_points.txt,sha256=_SdgYkA-hdMQfQ74YFDWlYMGJItq9n9Afzi9tM_6-5w,53
10
+ probegate_cli-0.1.0.dist-info/top_level.txt,sha256=tsTothPwNq0ZslCZRzXmG-nFwRJ7Np66HOt9bPnFMNc,14
11
+ probegate_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ probegate = probegate_cli.main:app
@@ -0,0 +1 @@
1
+ probegate_cli