qmpass-cli 0.2.0__tar.gz

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,5 @@
1
+ Qmpass Test CLI
2
+ Copyright (c) 2026 Qmpass. All rights reserved.
3
+
4
+ This software is proprietary. It is made available solely for use with a Qmpass subscription, to
5
+ start and follow Qmpass release gate evaluations from your own CI/CD pipelines.
@@ -0,0 +1,191 @@
1
+ Metadata-Version: 2.4
2
+ Name: qmpass-cli
3
+ Version: 0.2.0
4
+ Summary: Run Qmpass release gate evaluations from your CI/CD pipeline.
5
+ Author: Qmpass
6
+ License-Expression: LicenseRef-Proprietary
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: httpx==0.28.1
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
13
+ Requires-Dist: ruff>=0.6.0; extra == "dev"
14
+ Dynamic: license-file
15
+
16
+ # Qmpass CLI
17
+
18
+ Run a [Qmpass](https://qmpass.ai) release gate evaluation from your CI/CD pipeline. The pipeline
19
+ deploys a release candidate, `qmpass-cli` evaluates the stage's gate, and the job passes or fails on
20
+ the gate's automated checks. Manual checks stay open in Qmpass for your testers — the pipeline never
21
+ waits for them.
22
+
23
+ ## Requirements
24
+
25
+ - Python 3.10 or newer
26
+ - A project API token with **write** access: **Project settings → API tokens** (Pro plan and up)
27
+ - For `--agent auto` (the default): Docker on the runner. Otherwise, an agent your team runs (see "Which agent runs the checks"
28
+ below).
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ pipx install qmpass-cli
34
+ ```
35
+
36
+ Use pipx (or `pipx run`) so the CLI gets its own environment and never clashes with your job's
37
+ packages. Pin the version in pipelines (`qmpass-cli==0.2.0`) to upgrade on your schedule.
38
+
39
+ ## Run
40
+
41
+ ```bash
42
+ export QMPASS_TOKEN=qmp_proj_… # keep it in your CI secrets
43
+ qmpass-cli gate evaluate --release 10023 --stage PST-02
44
+ ```
45
+
46
+ Name the gate by its ref (`--gate PGT-0007`, shown at the end of the gate page's breadcrumb) or by
47
+ release id + stage ref (`--release 10023 --stage PST-02`, stage refs are in Project settings →
48
+ Release stages). The evaluation tests the stage's **App Address**.
49
+
50
+ | Option | Default | |
51
+ |---|---|---|
52
+ | `--agent` | `auto` | `auto` starts a temporary agent in Docker on the runner and removes it afterwards. Or the name of an agent your team runs (it must be online). |
53
+ | `--timeout` | `45m` | Stop waiting and cancel the evaluation. |
54
+ | `--no-wait` | | Start and exit 0 (named agents only). |
55
+ | `--name` | `<pipeline> #<build number>` | Evaluation name in Qmpass. |
56
+ | `--build-version`, `--commit`, `--branch`, `--build-url` | from the CI environment | Shown on the Evaluation page. |
57
+ | `--idempotency-key` | the CI run id | Same key = same evaluation, so a re-run of the job doesn't start a second one. |
58
+ | `--agent-image` | the release this CLI was tested with | Another agent image (env `QMPASS_AGENT_IMAGE`). |
59
+ | `--agent-variant rpa` | | The agent image with the RPA framework (Salesforce, Excel, PDF, Email, …). |
60
+
61
+ `QMPASS_URL` defaults to `https://api.qmpass.ai`.
62
+
63
+ ## Which agent runs the checks
64
+
65
+ The CLI only needs the **project API token** (`QMPASS_TOKEN`). It never needs an agent token.
66
+
67
+ **`--agent auto` (default) — a temporary agent on the runner**
68
+
69
+ ```bash
70
+ qmpass-cli gate evaluate --release 10023 --stage PST-02
71
+ ```
72
+
73
+ 1. The CLI starts the evaluation; Qmpass creates a temporary agent for this evaluation only.
74
+ 2. The CLI runs the Qmpass test agent image with `docker run` on the runner.
75
+ 3. The agent connects to Qmpass, runs the gate's automated checks and reports the results.
76
+ 4. When the checks are done, Qmpass removes the agent and its token, and the container stops.
77
+
78
+ Needs Docker on the runner. The agent runs on the runner, so it reaches whatever the runner reaches —
79
+ preview deploys, or internal URLs on self-hosted runners. Use `--agent-variant rpa` when the gate's
80
+ runbooks use the RPA framework.
81
+
82
+ **`--agent "<name>"` — an agent your team runs**
83
+
84
+ ```bash
85
+ qmpass-cli gate evaluate --release 10023 --stage PST-02 --agent "QA runner"
86
+ ```
87
+
88
+ The checks run on an agent you installed and connected beforehand (`pipx install qmpass-test-agent`,
89
+ then `qmpass-agent run` with that agent's own token from **Project settings → Agents**). It must be
90
+ online when the evaluation starts, otherwise the CLI stops with exit code 3. Use it when:
91
+
92
+ - the runner has no Docker;
93
+ - the app under test is reachable only from a particular machine (private network, VPN);
94
+ - the checks need a desktop or Windows machine.
95
+
96
+ With a named agent, `--no-wait` starts the evaluation and exits straight away; follow it in Qmpass.
97
+
98
+ Either way the CLI waits only for the automated checks — manual checks stay open in Qmpass for your
99
+ testers.
100
+
101
+ Build details are read from GitHub Actions, Bitbucket Pipelines, GitLab CI, Jenkins and Azure
102
+ Pipelines.
103
+
104
+ ### Exit codes
105
+
106
+ | Code | Meaning |
107
+ |---|---|
108
+ | `0` | The automated checks passed. Manual checks may still be open in Qmpass. |
109
+ | `1` | An automated check failed, was blocked or couldn't run. |
110
+ | `3` | Setup or infrastructure: token, gate not found, agent offline or not started, Docker missing, timeout, evaluation abandoned. |
111
+
112
+ Qmpass is an advisory gate: if you don't want a failed check to fail the job, allow the step to fail
113
+ (`continue-on-error` / `allow_failure`).
114
+
115
+ The CLI prints progress and a summary with the failed checks and a link to the evaluation, and writes
116
+ `qmpass-evaluation.json`. On GitHub Actions it also writes the job summary and the step outputs
117
+ `evaluation`, `state`, `outcome` and `url`.
118
+
119
+ ## In your pipeline
120
+
121
+ Two commands in any CI: install the CLI, then evaluate. Keep `QMPASS_TOKEN` in your CI's secrets — the token
122
+ belongs to one project, so nothing else is needed. `--agent auto` (the default) needs Docker on the runner.
123
+
124
+ GitHub Actions (`ubuntu-*` runners have pipx and Docker):
125
+
126
+ ```yaml
127
+ - name: Qmpass gate
128
+ run: |
129
+ pipx install qmpass-cli==0.2.0
130
+ qmpass-cli gate evaluate --release 10023 --stage PST-02 --build-version "${{ github.ref_name }}"
131
+ env:
132
+ QMPASS_TOKEN: ${{ secrets.QMPASS_TOKEN }}
133
+ ```
134
+
135
+ On GitHub the CLI also writes the job summary and the step outputs `evaluation`, `state`, `outcome`, `url`.
136
+
137
+ Bitbucket Pipelines (secured repository variable `QMPASS_TOKEN`; the `docker` service runs the temporary agent):
138
+
139
+ ```yaml
140
+ - step:
141
+ name: Qmpass gate
142
+ image: python:3.12
143
+ services: [docker]
144
+ script:
145
+ - python3 -m pip install pipx
146
+ - python3 -m pipx run --spec qmpass-cli==0.2.0 qmpass-cli gate evaluate --release 10023 --stage PST-02
147
+ ```
148
+
149
+ GitLab CI (masked CI/CD variable `QMPASS_TOKEN`; Docker-in-Docker for the agent):
150
+
151
+ ```yaml
152
+ qmpass-gate:
153
+ image: python:3.12
154
+ services: [docker:dind]
155
+ variables: { DOCKER_HOST: "tcp://docker:2375" }
156
+ script:
157
+ - python3 -m pip install pipx
158
+ - python3 -m pipx run --spec qmpass-cli==0.2.0 qmpass-cli gate evaluate --release 10023 --stage PST-02
159
+ ```
160
+
161
+ Azure DevOps (secret variable `QMPASS_TOKEN` — secrets must be mapped into `env`; Microsoft-hosted
162
+ `ubuntu-latest` has pipx and Docker):
163
+
164
+ ```yaml
165
+ - script: |
166
+ pipx install qmpass-cli==0.2.0
167
+ qmpass-cli gate evaluate --release 10023 --stage PST-02
168
+ displayName: Qmpass gate
169
+ env:
170
+ QMPASS_TOKEN: $(QMPASS_TOKEN)
171
+ ```
172
+
173
+ Jenkins (declarative; a secret-text credential `qmpass-token`; the agent needs Python 3.10+, pipx and Docker):
174
+
175
+ ```groovy
176
+ stage('Qmpass gate') {
177
+ environment {
178
+ QMPASS_TOKEN = credentials('qmpass-token')
179
+ }
180
+ steps {
181
+ sh 'pipx install qmpass-cli==0.2.0'
182
+ sh 'qmpass-cli gate evaluate --release 10023 --stage PST-02'
183
+ }
184
+ }
185
+ ```
186
+
187
+ No Docker on the runner? Run the Qmpass agent on a machine your team controls and add `--agent <name>`.
188
+
189
+ The temporary agent runs on your runner, so it reaches whatever the runner reaches (preview
190
+ deploys, internal URLs on self-hosted runners). Its token is issued for this evaluation only and
191
+ is removed when the evaluation is done with it.
@@ -0,0 +1,50 @@
1
+ # qmpass-test-cli
2
+
3
+ The `qmpass-cli` package (PyPI `qmpass-cli`, command `qmpass-cli`; it was `qmpass-test-cli` up to 0.1.1) — run Qmpass release gate evaluations from CI/CD pipelines. User docs: [README.pypi.md](README.pypi.md).
4
+ Every CI uses it the same way — two commands (install, evaluate); there are no per-CI plug-ins (GitHub Action,
5
+ Bitbucket pipe, Azure DevOps extension) for now.
6
+ Design: `qmpass-development-plan/docs/gates/CI_GATE_EVALUATION.md` (§4 endpoint, §6 temporary agent, §8 CLI).
7
+
8
+ ## Develop
9
+
10
+ ```bash
11
+ python3 -m venv .venv && .venv/bin/pip install -e ".[dev]" # Python 3.10+
12
+ .venv/bin/pytest -q && .venv/bin/ruff check src tests
13
+ ```
14
+
15
+ Against the local compose stack (gateway on `:30085`) with a locally built agent image:
16
+
17
+ ```bash
18
+ docker build -f ../qmpass-test-agent/docker/Dockerfile -t qmpass-test-agent:base ../qmpass-test-agent
19
+ export QMPASS_URL=http://localhost:30085 QMPASS_TOKEN=qmp_proj_… # the token picks its project
20
+ .venv/bin/qmpass-cli gate evaluate --gate PGT-0010 --agent-image qmpass-test-agent:base
21
+ ```
22
+
23
+ A `localhost` `QMPASS_URL` is passed to the agent container as `host.docker.internal`.
24
+
25
+ ## Release
26
+
27
+ Two wheels, same version: `qmpass-cli` (this package) and the old name `qmpass-test-cli`
28
+ (`packaging/qmpass-test-cli/`, depends on `qmpass-cli==<same version>` only — bump both together).
29
+
30
+ ```bash
31
+ .venv/bin/python -m build && .venv/bin/python -m build packaging/qmpass-test-cli --outdir dist
32
+ .venv/bin/twine check dist/*
33
+ ```
34
+
35
+ ## Layout
36
+
37
+ | Module | |
38
+ |---|---|
39
+ | `main.py` | argparse, env, signals |
40
+ | `evaluate.py` | start → temporary agent → follow → report; exit codes |
41
+ | `api.py` | CI endpoint client (retries 429 / 5xx; start is idempotent) |
42
+ | `agent.py` | `docker run` of the agent image; token only through the environment |
43
+ | `ci_env.py` | GitHub / Bitbucket / GitLab / Jenkins / Azure run details |
44
+ | `report.py` | progress, summary, GitHub job summary + outputs |
45
+
46
+ ## Release
47
+
48
+ Same as the test agent: bump `version` in `pyproject.toml` and `__init__.py`, `python -m build`,
49
+ `twine check dist/*`; the upload to PyPI is done by hand. `DEFAULT_AGENT_IMAGE` in `agent.py` pins
50
+ the agent image the release was tested with.
@@ -0,0 +1,176 @@
1
+ # Qmpass CLI
2
+
3
+ Run a [Qmpass](https://qmpass.ai) release gate evaluation from your CI/CD pipeline. The pipeline
4
+ deploys a release candidate, `qmpass-cli` evaluates the stage's gate, and the job passes or fails on
5
+ the gate's automated checks. Manual checks stay open in Qmpass for your testers — the pipeline never
6
+ waits for them.
7
+
8
+ ## Requirements
9
+
10
+ - Python 3.10 or newer
11
+ - A project API token with **write** access: **Project settings → API tokens** (Pro plan and up)
12
+ - For `--agent auto` (the default): Docker on the runner. Otherwise, an agent your team runs (see "Which agent runs the checks"
13
+ below).
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pipx install qmpass-cli
19
+ ```
20
+
21
+ Use pipx (or `pipx run`) so the CLI gets its own environment and never clashes with your job's
22
+ packages. Pin the version in pipelines (`qmpass-cli==0.2.0`) to upgrade on your schedule.
23
+
24
+ ## Run
25
+
26
+ ```bash
27
+ export QMPASS_TOKEN=qmp_proj_… # keep it in your CI secrets
28
+ qmpass-cli gate evaluate --release 10023 --stage PST-02
29
+ ```
30
+
31
+ Name the gate by its ref (`--gate PGT-0007`, shown at the end of the gate page's breadcrumb) or by
32
+ release id + stage ref (`--release 10023 --stage PST-02`, stage refs are in Project settings →
33
+ Release stages). The evaluation tests the stage's **App Address**.
34
+
35
+ | Option | Default | |
36
+ |---|---|---|
37
+ | `--agent` | `auto` | `auto` starts a temporary agent in Docker on the runner and removes it afterwards. Or the name of an agent your team runs (it must be online). |
38
+ | `--timeout` | `45m` | Stop waiting and cancel the evaluation. |
39
+ | `--no-wait` | | Start and exit 0 (named agents only). |
40
+ | `--name` | `<pipeline> #<build number>` | Evaluation name in Qmpass. |
41
+ | `--build-version`, `--commit`, `--branch`, `--build-url` | from the CI environment | Shown on the Evaluation page. |
42
+ | `--idempotency-key` | the CI run id | Same key = same evaluation, so a re-run of the job doesn't start a second one. |
43
+ | `--agent-image` | the release this CLI was tested with | Another agent image (env `QMPASS_AGENT_IMAGE`). |
44
+ | `--agent-variant rpa` | | The agent image with the RPA framework (Salesforce, Excel, PDF, Email, …). |
45
+
46
+ `QMPASS_URL` defaults to `https://api.qmpass.ai`.
47
+
48
+ ## Which agent runs the checks
49
+
50
+ The CLI only needs the **project API token** (`QMPASS_TOKEN`). It never needs an agent token.
51
+
52
+ **`--agent auto` (default) — a temporary agent on the runner**
53
+
54
+ ```bash
55
+ qmpass-cli gate evaluate --release 10023 --stage PST-02
56
+ ```
57
+
58
+ 1. The CLI starts the evaluation; Qmpass creates a temporary agent for this evaluation only.
59
+ 2. The CLI runs the Qmpass test agent image with `docker run` on the runner.
60
+ 3. The agent connects to Qmpass, runs the gate's automated checks and reports the results.
61
+ 4. When the checks are done, Qmpass removes the agent and its token, and the container stops.
62
+
63
+ Needs Docker on the runner. The agent runs on the runner, so it reaches whatever the runner reaches —
64
+ preview deploys, or internal URLs on self-hosted runners. Use `--agent-variant rpa` when the gate's
65
+ runbooks use the RPA framework.
66
+
67
+ **`--agent "<name>"` — an agent your team runs**
68
+
69
+ ```bash
70
+ qmpass-cli gate evaluate --release 10023 --stage PST-02 --agent "QA runner"
71
+ ```
72
+
73
+ The checks run on an agent you installed and connected beforehand (`pipx install qmpass-test-agent`,
74
+ then `qmpass-agent run` with that agent's own token from **Project settings → Agents**). It must be
75
+ online when the evaluation starts, otherwise the CLI stops with exit code 3. Use it when:
76
+
77
+ - the runner has no Docker;
78
+ - the app under test is reachable only from a particular machine (private network, VPN);
79
+ - the checks need a desktop or Windows machine.
80
+
81
+ With a named agent, `--no-wait` starts the evaluation and exits straight away; follow it in Qmpass.
82
+
83
+ Either way the CLI waits only for the automated checks — manual checks stay open in Qmpass for your
84
+ testers.
85
+
86
+ Build details are read from GitHub Actions, Bitbucket Pipelines, GitLab CI, Jenkins and Azure
87
+ Pipelines.
88
+
89
+ ### Exit codes
90
+
91
+ | Code | Meaning |
92
+ |---|---|
93
+ | `0` | The automated checks passed. Manual checks may still be open in Qmpass. |
94
+ | `1` | An automated check failed, was blocked or couldn't run. |
95
+ | `3` | Setup or infrastructure: token, gate not found, agent offline or not started, Docker missing, timeout, evaluation abandoned. |
96
+
97
+ Qmpass is an advisory gate: if you don't want a failed check to fail the job, allow the step to fail
98
+ (`continue-on-error` / `allow_failure`).
99
+
100
+ The CLI prints progress and a summary with the failed checks and a link to the evaluation, and writes
101
+ `qmpass-evaluation.json`. On GitHub Actions it also writes the job summary and the step outputs
102
+ `evaluation`, `state`, `outcome` and `url`.
103
+
104
+ ## In your pipeline
105
+
106
+ Two commands in any CI: install the CLI, then evaluate. Keep `QMPASS_TOKEN` in your CI's secrets — the token
107
+ belongs to one project, so nothing else is needed. `--agent auto` (the default) needs Docker on the runner.
108
+
109
+ GitHub Actions (`ubuntu-*` runners have pipx and Docker):
110
+
111
+ ```yaml
112
+ - name: Qmpass gate
113
+ run: |
114
+ pipx install qmpass-cli==0.2.0
115
+ qmpass-cli gate evaluate --release 10023 --stage PST-02 --build-version "${{ github.ref_name }}"
116
+ env:
117
+ QMPASS_TOKEN: ${{ secrets.QMPASS_TOKEN }}
118
+ ```
119
+
120
+ On GitHub the CLI also writes the job summary and the step outputs `evaluation`, `state`, `outcome`, `url`.
121
+
122
+ Bitbucket Pipelines (secured repository variable `QMPASS_TOKEN`; the `docker` service runs the temporary agent):
123
+
124
+ ```yaml
125
+ - step:
126
+ name: Qmpass gate
127
+ image: python:3.12
128
+ services: [docker]
129
+ script:
130
+ - python3 -m pip install pipx
131
+ - python3 -m pipx run --spec qmpass-cli==0.2.0 qmpass-cli gate evaluate --release 10023 --stage PST-02
132
+ ```
133
+
134
+ GitLab CI (masked CI/CD variable `QMPASS_TOKEN`; Docker-in-Docker for the agent):
135
+
136
+ ```yaml
137
+ qmpass-gate:
138
+ image: python:3.12
139
+ services: [docker:dind]
140
+ variables: { DOCKER_HOST: "tcp://docker:2375" }
141
+ script:
142
+ - python3 -m pip install pipx
143
+ - python3 -m pipx run --spec qmpass-cli==0.2.0 qmpass-cli gate evaluate --release 10023 --stage PST-02
144
+ ```
145
+
146
+ Azure DevOps (secret variable `QMPASS_TOKEN` — secrets must be mapped into `env`; Microsoft-hosted
147
+ `ubuntu-latest` has pipx and Docker):
148
+
149
+ ```yaml
150
+ - script: |
151
+ pipx install qmpass-cli==0.2.0
152
+ qmpass-cli gate evaluate --release 10023 --stage PST-02
153
+ displayName: Qmpass gate
154
+ env:
155
+ QMPASS_TOKEN: $(QMPASS_TOKEN)
156
+ ```
157
+
158
+ Jenkins (declarative; a secret-text credential `qmpass-token`; the agent needs Python 3.10+, pipx and Docker):
159
+
160
+ ```groovy
161
+ stage('Qmpass gate') {
162
+ environment {
163
+ QMPASS_TOKEN = credentials('qmpass-token')
164
+ }
165
+ steps {
166
+ sh 'pipx install qmpass-cli==0.2.0'
167
+ sh 'qmpass-cli gate evaluate --release 10023 --stage PST-02'
168
+ }
169
+ }
170
+ ```
171
+
172
+ No Docker on the runner? Run the Qmpass agent on a machine your team controls and add `--agent <name>`.
173
+
174
+ The temporary agent runs on your runner, so it reaches whatever the runner reaches (preview
175
+ deploys, internal URLs on self-hosted runners). Its token is issued for this evaluation only and
176
+ is removed when the evaluation is done with it.
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "qmpass-cli"
7
+ version = "0.2.0"
8
+ description = "Run Qmpass release gate evaluations from your CI/CD pipeline."
9
+ readme = "README.pypi.md"
10
+ requires-python = ">=3.10"
11
+ license = "LicenseRef-Proprietary"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Qmpass" }]
14
+ dependencies = [
15
+ # Exact pin, like qmpass-test-agent: the same client on every runner. Install with pipx (own venv) so it
16
+ # never clashes with a job's own packages.
17
+ "httpx==0.28.1",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ dev = ["pytest>=7.0.0", "ruff>=0.6.0"]
22
+
23
+ [project.scripts]
24
+ qmpass-cli = "qmpass_cli.main:main"
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
28
+ include = ["qmpass_cli*"]
29
+
30
+ [tool.pytest.ini_options]
31
+ testpaths = ["tests"]
32
+ pythonpath = ["src"]
33
+
34
+ [tool.ruff]
35
+ line-length = 120
36
+ target-version = "py310"
37
+
38
+ [tool.ruff.lint]
39
+ select = ["E", "F", "I", "W"]
40
+ ignore = ["E501"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """Qmpass CLI: run release gate evaluations from a CI/CD pipeline."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,105 @@
1
+ """The temporary agent container for ``--agent auto`` (CI_GATE_EVALUATION §6).
2
+
3
+ The agent token from the start answer goes to ``docker run`` only through the environment (``-e QMPASS_TOKEN``
4
+ without a value), never on the command line, so it doesn't show in process lists or logs.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ from collections import deque
13
+ from pathlib import Path
14
+ from typing import List, Optional, Sequence, Tuple
15
+ from urllib.parse import urlsplit, urlunsplit
16
+
17
+ # The released test agent the CLI was tested with (ECR Public, pulled without login). --agent-image overrides it.
18
+ DEFAULT_AGENT_IMAGE = "public.ecr.aws/qmpass/test-agent:1.0.21"
19
+ LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
20
+
21
+
22
+ def image_for(image: Optional[str], variant: Optional[str]) -> str:
23
+ """The image to run: the override as given, else the pinned release (``-rpa`` variant on request)."""
24
+ if image:
25
+ return image
26
+ if variant == "rpa":
27
+ return DEFAULT_AGENT_IMAGE + "-rpa"
28
+ return DEFAULT_AGENT_IMAGE
29
+
30
+
31
+ def docker_problem() -> Optional[str]:
32
+ """Why Docker can't run the agent here, or None when it can."""
33
+ if not shutil.which("docker"):
34
+ return "Docker isn't installed on this runner."
35
+ try:
36
+ done = subprocess.run(
37
+ ["docker", "version", "--format", "{{.Server.Version}}"],
38
+ capture_output=True, text=True, timeout=30,
39
+ )
40
+ except (OSError, subprocess.TimeoutExpired):
41
+ return "Docker didn't answer on this runner."
42
+ if done.returncode != 0:
43
+ return "Docker is installed but its daemon isn't reachable (Bitbucket: add the docker service to the step)."
44
+ return None
45
+
46
+
47
+ def container_url(qmpass_url: str) -> Tuple[str, List[str]]:
48
+ """QMPASS_URL as seen from inside the container: a local stack is reached through host.docker.internal."""
49
+ parts = urlsplit(qmpass_url)
50
+ host = (parts.hostname or "").lower()
51
+ if host not in LOCAL_HOSTS:
52
+ return qmpass_url, []
53
+ netloc = "host.docker.internal" + (f":{parts.port}" if parts.port else "")
54
+ return (urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment)),
55
+ ["--add-host", "host.docker.internal:host-gateway"])
56
+
57
+
58
+ def run_command(image: str, name: str, extra: Sequence[str] = ()) -> List[str]:
59
+ return ["docker", "run", "--rm", "--pull=missing", "--name", name,
60
+ "-e", "QMPASS_TOKEN", "-e", "QMPASS_URL", *extra, image]
61
+
62
+
63
+ class AgentContainer:
64
+ """One agent container: started with the evaluation's agent token, stopped when the CLI is done."""
65
+
66
+ def __init__(self, image: str, name: str, log_path: Path):
67
+ self.image = image
68
+ self.name = name
69
+ self.log_path = log_path
70
+ self._proc: Optional[subprocess.Popen] = None
71
+ self._log = None
72
+
73
+ def start(self, agent_token: str, qmpass_url: str) -> None:
74
+ url, extra = container_url(qmpass_url)
75
+ env = dict(os.environ)
76
+ env["QMPASS_TOKEN"] = agent_token
77
+ env["QMPASS_URL"] = url
78
+ self._log = open(self.log_path, "w", encoding="utf-8")
79
+ self._proc = subprocess.Popen(
80
+ run_command(self.image, self.name, extra), stdout=self._log, stderr=subprocess.STDOUT, env=env,
81
+ )
82
+
83
+ def exited(self) -> Optional[int]:
84
+ """The container's exit code once it stopped, else None."""
85
+ return self._proc.poll() if self._proc else None
86
+
87
+ def stop(self) -> None:
88
+ if not self._proc:
89
+ return
90
+ if self._proc.poll() is None:
91
+ subprocess.run(["docker", "stop", "-t", "10", self.name], capture_output=True, timeout=60)
92
+ try:
93
+ self._proc.wait(timeout=30)
94
+ except subprocess.TimeoutExpired:
95
+ self._proc.kill()
96
+ if self._log:
97
+ self._log.close()
98
+ self._log = None
99
+
100
+ def log_tail(self, lines: int = 15) -> List[str]:
101
+ try:
102
+ with open(self.log_path, encoding="utf-8", errors="replace") as f:
103
+ return [line.rstrip("\n") for line in deque(f, maxlen=lines)]
104
+ except OSError:
105
+ return []
@@ -0,0 +1,87 @@
1
+ """Qmpass CI endpoint client (``/api/v1/projects/current/ci/gate-evaluations``, CI_GATE_EVALUATION §4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any, Callable, Dict, Optional
7
+
8
+ import httpx
9
+
10
+ from . import __version__
11
+
12
+ DEFAULT_URL = "https://api.qmpass.ai"
13
+ # Network errors, rate limits and platform hiccups are retried; a start is safe to retry (Idempotency-Key).
14
+ RETRY_STATUSES = {429, 502, 503, 504}
15
+
16
+
17
+ class ApiError(Exception):
18
+ """Qmpass refused the call (or couldn't be reached). ``code`` is the platform's errorType when it sent one."""
19
+
20
+ def __init__(self, message: str, status: Optional[int] = None, code: Optional[str] = None):
21
+ super().__init__(message)
22
+ self.status = status
23
+ self.code = code
24
+
25
+
26
+ class QmpassApi:
27
+ def __init__(
28
+ self,
29
+ base_url: str,
30
+ token: str,
31
+ *,
32
+ transport: Optional[httpx.BaseTransport] = None,
33
+ retries: int = 4,
34
+ sleep: Callable[[float], None] = time.sleep,
35
+ ):
36
+ self._retries = retries
37
+ self._sleep = sleep
38
+ self._client = httpx.Client(
39
+ base_url=base_url.rstrip("/"),
40
+ headers={"Authorization": f"Bearer {token}", "User-Agent": f"qmpass-cli/{__version__}"},
41
+ timeout=httpx.Timeout(30.0),
42
+ transport=transport,
43
+ )
44
+
45
+ def close(self) -> None:
46
+ self._client.close()
47
+
48
+ def _path(self, suffix: str = "") -> str:
49
+ # `current` = the token's own project (the gateway puts in its id): a token can only reach its project.
50
+ return f"/api/v1/projects/current/ci/gate-evaluations{suffix}"
51
+
52
+ def start(self, idempotency_key: str, body: Dict[str, Any]) -> Dict[str, Any]:
53
+ return self._call("POST", self._path(), json=body, headers={"Idempotency-Key": idempotency_key})
54
+
55
+ def status(self, evaluation: str) -> Dict[str, Any]:
56
+ return self._call("GET", self._path(f"/{evaluation}"))
57
+
58
+ def cancel(self, evaluation: str) -> Dict[str, Any]:
59
+ return self._call("POST", self._path(f"/{evaluation}/cancel"))
60
+
61
+ def _call(self, method: str, path: str, **kwargs: Any) -> Dict[str, Any]:
62
+ attempt = 0
63
+ while True:
64
+ try:
65
+ response = self._client.request(method, path, **kwargs)
66
+ except httpx.HTTPError as e:
67
+ if attempt >= self._retries:
68
+ raise ApiError(f"Couldn't reach Qmpass: {e.__class__.__name__}") from e
69
+ else:
70
+ if response.status_code < 400:
71
+ return response.json() if response.content else {}
72
+ if response.status_code not in RETRY_STATUSES or attempt >= self._retries:
73
+ raise _error(response)
74
+ attempt += 1
75
+ self._sleep(min(2 ** attempt, 20))
76
+
77
+
78
+ def _error(response: httpx.Response) -> ApiError:
79
+ message, code = None, None
80
+ try:
81
+ body = response.json()
82
+ message, code = body.get("message"), body.get("errorType")
83
+ except ValueError:
84
+ pass
85
+ if response.status_code in (401, 403) and not message:
86
+ message = "Qmpass refused the token: check QMPASS_TOKEN (a project API token with write access)."
87
+ return ApiError(message or f"Qmpass answered HTTP {response.status_code}", response.status_code, code)