xqo-flows-runner 3.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dudikkocak
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: xqo-flows-runner
3
+ Version: 3.2.0
4
+ Summary: Headless remote worker for xqo flows: runs flow steps and whole flows with its own agents
5
+ Author: dudikkocak
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/dudikkocak/xqo
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: xqo<4,>=3.0
12
+ Requires-Dist: xqo-flows==3.2.0
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=8; extra == "dev"
15
+ Requires-Dist: pytest-timeout>=2.3; extra == "dev"
16
+ Requires-Dist: httpx>=0.27; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # xqo-flows-runner
20
+
21
+ A headless remote worker for [xqo-flows](../xqo-flows). It adds the `xqo worker` command, which polls an HQ's
22
+ flows worker API and runs jobs with this machine's own agents. There is no dashboard, no office and no open
23
+ port: the worker only makes outgoing HTTP calls to the HQ.
24
+
25
+ ```bash
26
+ pip install xqo-flows-runner # brings xqo and xqo-flows
27
+ ```
28
+
29
+ ## Set up a worker
30
+
31
+ 1. **On the HQ**, make a token and list the worker with its labels (`agents.json`):
32
+
33
+ ```bash
34
+ xqo flows token # prints a random token
35
+ export XQO_WORKER_GPU_BOX_TOKEN=... # the HQ reads the worker's token from this variable
36
+ ```
37
+
38
+ ```json
39
+ "flows": {"listen": "0.0.0.0:8200",
40
+ "workers": {"allow": {"gpu-box": {"token_env": "XQO_WORKER_GPU_BOX_TOKEN", "labels": ["gpu", "linux"]}}}}
41
+ ```
42
+
43
+ Restart `xqo serve`. Its banner shows `Flows worker API and webhooks: http://0.0.0.0:8200/flows/v1/`.
44
+
45
+ 2. **On the worker machine**, give it its own `agents.json` with its agents and a `flows_worker` block:
46
+
47
+ ```json
48
+ {"agents": [{"name": "builder", "skills": ["python", "build"]}],
49
+ "flows_worker": {"hq": "http://hq.example.internal:8200", "name": "gpu-box", "token_env": "XQO_WORKER_TOKEN", "jobs": 2}}
50
+ ```
51
+
52
+ ```bash
53
+ export XQO_WORKER_TOKEN=... # the same token as on the HQ
54
+ export ANTHROPIC_API_KEY=... # the worker's own model access
55
+ xqo --config agents.json worker
56
+ # xqo worker gpu-box: connected to HQ 'Main HQ' at http://hq.example.internal:8200, labels: gpu, linux, ...
57
+ ```
58
+
59
+ Flags override the file: `--hq`, `--name`, `--token-env`, `--jobs`, `--once` (run one job, then exit). The
60
+ environment variables `XQO_WORKER_HQ`, `XQO_WORKER_NAME` and `XQO_WORKER_JOBS` work too. Global flags such as
61
+ `--data-dir`, `--mock` and `--departments` go before `worker`, as with any xqo command.
62
+
63
+ 3. **Use it**: add a **Remote** step with label `gpu` to a flow, or run a whole flow on the worker with
64
+ `xqo flows run NAME --labels gpu`. `xqo flows workers` on the HQ shows whether the worker is online.
65
+
66
+ A complete sample is in [`../xqo-flows/examples/setup/`](../xqo-flows/examples/setup). It has the HQ and worker
67
+ configs, a remote flow, `docker-compose.worker.yml` (a worker in Docker, with no published port) and an `.env`
68
+ template.
69
+
70
+ ## What the worker does
71
+
72
+ | Job | Runs as |
73
+ |---|---|
74
+ | `task`: one Remote step | An ordinary root task on the worker, for the step's agent (empty = the worker's first agent). It is unattended unless the step says otherwise. Its result goes back to the HQ. |
75
+ | `flow`: a whole flow | The same flow engine as the HQ, using the worker's agents. Step states go back with every heartbeat, so the HQ's editor shows the run live. Approval steps are asked on the HQ and the answer comes back with a heartbeat. A resumed run brings the finished steps' results, so they do not run again. |
76
+
77
+ - **Heartbeats** go out every `lease_seconds / 3`, and every second while an approval waits. If the HQ answers "cancel" (the run was cancelled there), the
78
+ worker cancels the task and reports `cancelled`.
79
+ - **HQ unreachable:** the worker keeps retrying with a growing pause, up to 30 s. If the outage outlasts the lease,
80
+ the HQ gives the job to another worker. A rejected token (401/403) stops the worker.
81
+ - **Data:** each worker has its own data dir (tasks, workspaces, logs), so its tasks can be inspected with the
82
+ usual tools. To see them in a dashboard, run `xqo serve` on the same data dir while the worker is stopped (one
83
+ process per data dir).
@@ -0,0 +1,65 @@
1
+ # xqo-flows-runner
2
+
3
+ A headless remote worker for [xqo-flows](../xqo-flows). It adds the `xqo worker` command, which polls an HQ's
4
+ flows worker API and runs jobs with this machine's own agents. There is no dashboard, no office and no open
5
+ port: the worker only makes outgoing HTTP calls to the HQ.
6
+
7
+ ```bash
8
+ pip install xqo-flows-runner # brings xqo and xqo-flows
9
+ ```
10
+
11
+ ## Set up a worker
12
+
13
+ 1. **On the HQ**, make a token and list the worker with its labels (`agents.json`):
14
+
15
+ ```bash
16
+ xqo flows token # prints a random token
17
+ export XQO_WORKER_GPU_BOX_TOKEN=... # the HQ reads the worker's token from this variable
18
+ ```
19
+
20
+ ```json
21
+ "flows": {"listen": "0.0.0.0:8200",
22
+ "workers": {"allow": {"gpu-box": {"token_env": "XQO_WORKER_GPU_BOX_TOKEN", "labels": ["gpu", "linux"]}}}}
23
+ ```
24
+
25
+ Restart `xqo serve`. Its banner shows `Flows worker API and webhooks: http://0.0.0.0:8200/flows/v1/`.
26
+
27
+ 2. **On the worker machine**, give it its own `agents.json` with its agents and a `flows_worker` block:
28
+
29
+ ```json
30
+ {"agents": [{"name": "builder", "skills": ["python", "build"]}],
31
+ "flows_worker": {"hq": "http://hq.example.internal:8200", "name": "gpu-box", "token_env": "XQO_WORKER_TOKEN", "jobs": 2}}
32
+ ```
33
+
34
+ ```bash
35
+ export XQO_WORKER_TOKEN=... # the same token as on the HQ
36
+ export ANTHROPIC_API_KEY=... # the worker's own model access
37
+ xqo --config agents.json worker
38
+ # xqo worker gpu-box: connected to HQ 'Main HQ' at http://hq.example.internal:8200, labels: gpu, linux, ...
39
+ ```
40
+
41
+ Flags override the file: `--hq`, `--name`, `--token-env`, `--jobs`, `--once` (run one job, then exit). The
42
+ environment variables `XQO_WORKER_HQ`, `XQO_WORKER_NAME` and `XQO_WORKER_JOBS` work too. Global flags such as
43
+ `--data-dir`, `--mock` and `--departments` go before `worker`, as with any xqo command.
44
+
45
+ 3. **Use it**: add a **Remote** step with label `gpu` to a flow, or run a whole flow on the worker with
46
+ `xqo flows run NAME --labels gpu`. `xqo flows workers` on the HQ shows whether the worker is online.
47
+
48
+ A complete sample is in [`../xqo-flows/examples/setup/`](../xqo-flows/examples/setup). It has the HQ and worker
49
+ configs, a remote flow, `docker-compose.worker.yml` (a worker in Docker, with no published port) and an `.env`
50
+ template.
51
+
52
+ ## What the worker does
53
+
54
+ | Job | Runs as |
55
+ |---|---|
56
+ | `task`: one Remote step | An ordinary root task on the worker, for the step's agent (empty = the worker's first agent). It is unattended unless the step says otherwise. Its result goes back to the HQ. |
57
+ | `flow`: a whole flow | The same flow engine as the HQ, using the worker's agents. Step states go back with every heartbeat, so the HQ's editor shows the run live. Approval steps are asked on the HQ and the answer comes back with a heartbeat. A resumed run brings the finished steps' results, so they do not run again. |
58
+
59
+ - **Heartbeats** go out every `lease_seconds / 3`, and every second while an approval waits. If the HQ answers "cancel" (the run was cancelled there), the
60
+ worker cancels the task and reports `cancelled`.
61
+ - **HQ unreachable:** the worker keeps retrying with a growing pause, up to 30 s. If the outage outlasts the lease,
62
+ the HQ gives the job to another worker. A rejected token (401/403) stops the worker.
63
+ - **Data:** each worker has its own data dir (tasks, workspaces, logs), so its tasks can be inspected with the
64
+ usual tools. To see them in a dashboard, run `xqo serve` on the same data dir while the worker is stopped (one
65
+ process per data dir).
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "xqo-flows-runner"
7
+ version = "3.2.0"
8
+ description = "Headless remote worker for xqo flows: runs flow steps and whole flows with its own agents"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{name = "dudikkocak"}]
13
+ dependencies = [
14
+ "xqo>=3.0,<4",
15
+ "xqo-flows==3.2.0",
16
+ ]
17
+
18
+ [project.optional-dependencies]
19
+ dev = ["pytest>=8", "pytest-timeout>=2.3", "httpx>=0.27"]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/dudikkocak/xqo"
23
+
24
+ [project.entry-points."xqo.plugins"]
25
+ flows_runner = "xqo_flows_runner:RunnerPlugin"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,120 @@
1
+ """xqo-flows-runner: `xqo worker`, a headless remote worker for xqo flows (see worker.py).
2
+
3
+ On the worker machine, next to its own agents.json:
4
+
5
+ "flows_worker": {"hq": "http://hq.example:8200", "name": "gpu-box", "token_env": "XQO_WORKER_TOKEN", "jobs": 1}
6
+
7
+ then `xqo --config worker.json worker` (flags override the file: --hq, --name, --token-env, --jobs, --once).
8
+ The plugin does nothing inside `xqo serve`; it only adds the command."""
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import json
13
+ import os
14
+ import signal
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ from xqo.api import Plugin, build
19
+
20
+ from .worker import HQClient, HQError, Worker
21
+
22
+ __all__ = ["RunnerPlugin", "Worker", "HQClient", "HQError", "settings"]
23
+
24
+ KEYS = {"hq", "name", "token_env", "jobs", "poll_wait"}
25
+
26
+
27
+ def settings(cfg: dict, a=None) -> dict:
28
+ """The worker's settings: command-line flag, then environment, then "flows_worker" in the config file."""
29
+ fw = cfg.get("flows_worker") or {}
30
+ if not isinstance(fw, dict):
31
+ raise ValueError("\"flows_worker\" must be an object")
32
+ if fw.get("token"):
33
+ raise ValueError("flows_worker has a plaintext token; put it in an environment variable and name that "
34
+ "with token_env")
35
+ bad = set(fw) - KEYS
36
+ if bad:
37
+ raise ValueError(f"flows_worker: unknown key(s) {', '.join(sorted(bad))}; known: {', '.join(sorted(KEYS))}")
38
+
39
+ def pick(flag, env, key, default=None):
40
+ v = getattr(a, flag, None) if a is not None else None
41
+ if v not in (None, ""):
42
+ return v
43
+ if os.getenv(env):
44
+ return os.environ[env]
45
+ return fw.get(key, default)
46
+
47
+ s = {"hq": pick("hq", "XQO_WORKER_HQ", "hq"), "name": pick("name", "XQO_WORKER_NAME", "name"),
48
+ "token_env": pick("token_env", "XQO_WORKER_TOKEN_ENV", "token_env", "XQO_WORKER_TOKEN"),
49
+ "jobs": int(pick("jobs", "XQO_WORKER_JOBS", "jobs", 1)),
50
+ "poll_wait": float(fw.get("poll_wait", 20))}
51
+ if not s["hq"] or not s["name"]:
52
+ raise ValueError("the worker needs the HQ's worker API address and its own name: --hq URL --name NAME "
53
+ "(or \"flows_worker\": {\"hq\": ..., \"name\": ...} in its agents.json)")
54
+ s["token"] = os.getenv(s["token_env"], "")
55
+ if not s["token"]:
56
+ raise ValueError(f"set {s['token_env']} to this worker's token (the HQ lists the same token in "
57
+ f"flows.workers.allow.{s['name']})")
58
+ return s
59
+
60
+
61
+ def _main(a) -> None:
62
+ try:
63
+ cfg = json.loads(Path(a.config).read_text(encoding="utf-8")) if Path(a.config).is_file() else {}
64
+ s = settings(cfg, a)
65
+ except (OSError, ValueError) as e:
66
+ sys.exit(f"config error: {e}")
67
+ data = Path(a.data_dir)
68
+ try:
69
+ bus = build(a.config, data / "artifacts", str(data / "logs" / "events.jsonl"), mock=a.mock or None,
70
+ departments=a.departments, departments_dir=a.departments_dir)
71
+ except ValueError as e:
72
+ sys.exit(f"config error: {e}")
73
+ hq = HQClient(s["hq"], s["name"], s["token"])
74
+ worker = Worker(bus, hq, s["jobs"], s["poll_wait"])
75
+
76
+ async def go():
77
+ loop = asyncio.get_running_loop()
78
+ for sig in (signal.SIGINT, signal.SIGTERM):
79
+ try:
80
+ loop.add_signal_handler(sig, worker.stop)
81
+ except (NotImplementedError, RuntimeError): # Windows
82
+ pass
83
+ try:
84
+ info = await worker.ping()
85
+ except HQError as e:
86
+ sys.exit(f"the HQ at {s['hq']} refused worker {s['name']}: {e}")
87
+ except OSError as e:
88
+ sys.exit(f"cannot reach the HQ at {s['hq']}: {e}")
89
+ print(f"xqo worker {s['name']}: connected to HQ {info['hq']!r} at {s['hq']}, labels: "
90
+ f"{', '.join(info['labels']) or '-'}, agents: {', '.join(bus.agents)}, jobs at a time: {s['jobs']}",
91
+ flush=True)
92
+ try:
93
+ await worker.run(max_jobs=1 if a.once else None)
94
+ except HQError as e:
95
+ sys.exit(str(e))
96
+
97
+ asyncio.run(go())
98
+
99
+
100
+ class RunnerPlugin(Plugin):
101
+ name = "flows_runner"
102
+ description = "Headless remote worker for xqo flows (the `xqo worker` command)"
103
+ config_keys = ("flows_worker",)
104
+
105
+ @classmethod
106
+ def add_cli(cls, sub, url) -> list[str]:
107
+ w = sub.add_parser("worker", help="run as a headless flows worker for an HQ (xqo-flows-runner)")
108
+ w.add_argument("--hq", help="the HQ's worker API, e.g. http://hq.example:8200 (XQO_WORKER_HQ)")
109
+ w.add_argument("--name", help="this worker's name as listed on the HQ (XQO_WORKER_NAME)")
110
+ w.add_argument("--token-env", help="environment variable with the token (default XQO_WORKER_TOKEN)")
111
+ w.add_argument("--jobs", type=int, help="jobs at a time (default 1)")
112
+ w.add_argument("--once", action="store_true", help="run one job, then exit")
113
+ return ["worker"]
114
+
115
+ @classmethod
116
+ def run_cli(cls, a) -> None:
117
+ _main(a)
118
+
119
+ def configure(self, ctx, cfg):
120
+ return None # nothing to do inside `xqo serve`: the worker is its own command
@@ -0,0 +1,260 @@
1
+ """The headless worker: polls an HQ's flows worker API for jobs and runs them with this machine's own agents.
2
+
3
+ No dashboard, no office, no listener: the worker only makes outgoing HTTP calls to the HQ (workers.py in
4
+ xqo-flows), so it can run behind NAT. Its agents, API keys, sandbox and budgets come from its own agents.json.
5
+
6
+ Jobs
7
+ - "task": one agent step of a flow that runs on the HQ ({agent, prompt, title, unattended}). The step becomes an
8
+ ordinary root task here; its result goes back to the HQ.
9
+ - "flow": a whole flow ({flow, inputs, run_id, approval_timeout, nodes}), run here by the same engine as on the HQ.
10
+ Node states go back with every heartbeat, so the HQ's editor shows the run live. An approval step is asked on
11
+ the HQ: the question goes up with the heartbeats (progress["approvals"]) and the HQ's answer comes back in the
12
+ heartbeat's reply ({"answers": {node: "approve"|"reject"}}). "nodes" is set when the HQ resumes a run: steps
13
+ already done keep their results.
14
+
15
+ While a job runs the worker sends a heartbeat every lease/3 seconds; when the HQ answers {"cancel": true} the job's
16
+ task is cancelled here. If the HQ cannot be reached the worker keeps trying with a growing pause (up to 30 s)."""
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import contextlib
21
+ import json
22
+ import sys
23
+ import urllib.error
24
+ import urllib.request
25
+
26
+ from xqo.api import __version__
27
+
28
+ from xqo_flows import BusSteps, Engine, FlowError, Run, run_task, validate
29
+
30
+
31
+ class HQError(RuntimeError):
32
+ def __init__(self, status: int, detail: str):
33
+ super().__init__(f"{status}: {detail}")
34
+ self.status = status
35
+
36
+
37
+ class HQClient:
38
+ """The worker API of one HQ (blocking calls, run in a thread)."""
39
+
40
+ def __init__(self, url: str, name: str, token: str, timeout: float = 60):
41
+ self.url, self.name, self.token, self.timeout = url.rstrip("/"), name, token, timeout
42
+
43
+ def call(self, method: str, path: str, body: dict | None = None, timeout: float | None = None) -> dict:
44
+ req = urllib.request.Request(self.url + path, method=method,
45
+ data=json.dumps(body).encode() if body is not None else None,
46
+ headers={"Content-Type": "application/json", "X-XQO-Worker": self.name,
47
+ "Authorization": f"Bearer {self.token}"})
48
+ try:
49
+ with urllib.request.urlopen(req, timeout=timeout or self.timeout) as r:
50
+ return json.loads(r.read() or b"{}")
51
+ except urllib.error.HTTPError as e:
52
+ try:
53
+ detail = json.loads(e.read()).get("detail")
54
+ except ValueError:
55
+ detail = e.reason
56
+ raise HQError(e.code, str(detail)) from None
57
+
58
+ async def acall(self, method: str, path: str, body: dict | None = None, timeout: float | None = None) -> dict:
59
+ return await asyncio.to_thread(self.call, method, path, body, timeout)
60
+
61
+
62
+ class WorkerSteps(BusSteps):
63
+ """Agent steps run here; approval steps are asked on the HQ through the heartbeats."""
64
+
65
+ where = "a worker (remote steps run on the HQ)"
66
+
67
+ def __init__(self, bus, changed, progress: dict, poke: asyncio.Event, approval_timeout: float | None):
68
+ super().__init__(bus, changed)
69
+ self.progress = progress
70
+ self.poke = poke
71
+ self.approval_timeout = approval_timeout
72
+ self.waiting: dict[str, asyncio.Future] = {}
73
+
74
+ async def approval(self, run: Run, node: dict, question: str) -> str:
75
+ nid = node["id"]
76
+ fut = asyncio.get_running_loop().create_future()
77
+ self.waiting[nid] = fut
78
+ self.progress.setdefault("approvals", {})[nid] = {"question": question}
79
+ run.nodes[nid]["question"] = question
80
+ self._changed(run, nid)
81
+ self.poke.set() # tell the HQ now, not at the next regular heartbeat
82
+ timeout = node["data"].get("timeout") or self.approval_timeout
83
+ try:
84
+ answer, by = await asyncio.wait_for(asyncio.shield(fut), timeout), "user"
85
+ except asyncio.TimeoutError:
86
+ answer, by = node["data"].get("default", "reject"), "timeout"
87
+ finally:
88
+ self.waiting.pop(nid, None)
89
+ self.progress.get("approvals", {}).pop(nid, None)
90
+ self.poke.set()
91
+ run.nodes[nid].update(answer=answer, answered_by=by)
92
+ return answer
93
+
94
+ def answers(self, answers: dict) -> None:
95
+ for nid, a in (answers or {}).items():
96
+ fut = self.waiting.get(nid)
97
+ if fut and not fut.done() and a in ("approve", "reject"):
98
+ fut.set_result(a)
99
+
100
+
101
+ class Worker:
102
+ def __init__(self, bus, hq: HQClient, jobs: int = 1, poll_wait: float = 20, log=None):
103
+ self.bus, self.hq = bus, hq
104
+ self.slots = max(1, int(jobs))
105
+ self.poll_wait = poll_wait
106
+ self.lease = 60.0
107
+ self.active: dict[str, asyncio.Task] = {}
108
+ self.done = 0
109
+ self.log = log or (lambda msg: print(msg, file=sys.stderr, flush=True))
110
+ self._stop = asyncio.Event()
111
+
112
+ def stop(self) -> None:
113
+ self._stop.set()
114
+
115
+ async def ping(self) -> dict:
116
+ info = await self.hq.acall("GET", "/flows/v1/ping")
117
+ self.lease = float(info.get("lease_seconds", self.lease))
118
+ return info
119
+
120
+ async def run(self, max_jobs: int | None = None) -> None:
121
+ """Poll and run jobs until stop() (or until max_jobs jobs have finished)."""
122
+ pause = 1.0
123
+ await self.bus.mcp.start()
124
+ try:
125
+ while not self._stop.is_set():
126
+ if max_jobs is not None and self.done + len(self.active) >= max_jobs:
127
+ if not self.active:
128
+ break
129
+ await asyncio.wait(set(self.active.values()), return_when=asyncio.FIRST_COMPLETED)
130
+ continue
131
+ if len(self.active) >= self.slots:
132
+ await asyncio.wait(set(self.active.values()), return_when=asyncio.FIRST_COMPLETED)
133
+ continue
134
+ try:
135
+ r = await self.hq.acall("POST", "/flows/v1/next", {"wait": self.poll_wait, "version": __version__},
136
+ timeout=self.poll_wait + 30)
137
+ pause = 1.0
138
+ except HQError as e:
139
+ if e.status in (401, 403):
140
+ self.log(f"the HQ refused this worker: {e}")
141
+ raise
142
+ self.log(f"HQ error: {e}; retrying in {pause:.0f}s")
143
+ await self._sleep(pause)
144
+ pause = min(pause * 2, 30)
145
+ continue
146
+ except (urllib.error.URLError, OSError, ValueError) as e:
147
+ self.log(f"HQ not reachable ({e}); retrying in {pause:.0f}s")
148
+ await self._sleep(pause)
149
+ pause = min(pause * 2, 30)
150
+ continue
151
+ self.lease = float(r.get("lease_seconds", self.lease))
152
+ job = r.get("job")
153
+ if job:
154
+ self.active[job["id"]] = asyncio.ensure_future(self.handle(job))
155
+ finally:
156
+ for t in list(self.active.values()):
157
+ t.cancel()
158
+ if self.active:
159
+ await asyncio.wait(set(self.active.values()), timeout=60)
160
+ await self.bus.mcp.stop()
161
+
162
+ async def _sleep(self, s: float) -> None:
163
+ with contextlib.suppress(asyncio.TimeoutError):
164
+ await asyncio.wait_for(self._stop.wait(), s)
165
+
166
+ async def handle(self, job: dict) -> None:
167
+ jid = job["id"]
168
+ progress: dict = {}
169
+ poke = asyncio.Event()
170
+ box: dict = {} # the job's WorkerSteps, for answers that come back with heartbeats
171
+ self.log(f"job {jid}: {job['kind']} {job['spec'].get('title', '')}")
172
+ work = asyncio.ensure_future(self._work(job, progress, poke, box))
173
+ beat = asyncio.ensure_future(self._heartbeat(jid, work, progress, poke, box))
174
+ status, result, error = "error", "", ""
175
+ try:
176
+ out = await work
177
+ status, result, error = out.get("status", "done"), out.get("result", ""), out.get("error", "")
178
+ except asyncio.CancelledError:
179
+ status, error = "cancelled", "cancelled on the worker"
180
+ except FlowError as e:
181
+ error = str(e)
182
+ except Exception as e: # a job never stops the worker
183
+ error = f"{type(e).__name__}: {e}"
184
+ finally:
185
+ beat.cancel()
186
+ with contextlib.suppress(BaseException):
187
+ await beat
188
+ body = {"status": status, "result": result, "error": error, "task_id": progress.get("task_id", ""),
189
+ **({"progress": progress} if progress.get("nodes") else {})}
190
+ for attempt in range(5):
191
+ try:
192
+ await self.hq.acall("POST", f"/flows/v1/jobs/{jid}/result", body)
193
+ break
194
+ except HQError as e:
195
+ self.log(f"job {jid}: the HQ did not take the result: {e}")
196
+ break
197
+ except (urllib.error.URLError, OSError) as e:
198
+ self.log(f"job {jid}: sending the result failed ({e}); retry {attempt + 1}/5")
199
+ await asyncio.sleep(min(2 ** attempt, 15))
200
+ self.active.pop(jid, None)
201
+ self.done += 1
202
+ self.log(f"job {jid}: {status}" + (f" ({error[:200]})" if error else ""))
203
+
204
+ async def _heartbeat(self, jid: str, work: asyncio.Task, progress: dict, poke: asyncio.Event | None = None,
205
+ box: dict | None = None) -> None:
206
+ poke = poke or asyncio.Event()
207
+ box = box if box is not None else {}
208
+ while not work.done():
209
+ # every lease/3; every second while an approval waits (so its answer comes back quickly)
210
+ pause = 1.0 if progress.get("approvals") else self.lease / 3
211
+ with contextlib.suppress(asyncio.TimeoutError):
212
+ await asyncio.wait_for(poke.wait(), max(0.05, pause))
213
+ poke.clear()
214
+ if work.done():
215
+ return
216
+ try:
217
+ r = await self.hq.acall("POST", f"/flows/v1/jobs/{jid}/heartbeat", {"progress": progress})
218
+ except HQError as e:
219
+ if e.status == 404:
220
+ work.cancel()
221
+ return
222
+ continue
223
+ except (urllib.error.URLError, OSError, ValueError):
224
+ continue # the lease decides; a short outage is fine
225
+ if r.get("cancel"):
226
+ self.log(f"job {jid}: cancelled by the HQ")
227
+ work.cancel()
228
+ return
229
+ if r.get("answers") and box.get("steps"):
230
+ box["steps"].answers(r["answers"])
231
+
232
+ async def _work(self, job: dict, progress: dict, poke: asyncio.Event | None = None, box: dict | None = None) -> dict:
233
+ spec = job.get("spec") or {}
234
+ if job["kind"] == "task":
235
+ def created(task):
236
+ progress["task_id"] = task.id
237
+ return await run_task(self.bus, str(spec.get("prompt") or ""), spec.get("agent") or None,
238
+ str(spec.get("title") or "flow step"), unattended=spec.get("unattended", True) is not False,
239
+ on_created=created)
240
+ if job["kind"] == "flow":
241
+ doc = validate(spec.get("flow"), (spec.get("flow") or {}).get("name"))
242
+ resume = isinstance(spec.get("nodes"), dict) and bool(spec["nodes"])
243
+ run = Run(flow=doc["name"], title=doc.get("title", ""), inputs=spec.get("inputs") or {},
244
+ id=spec.get("run_id") or job["id"], by="hq", where="worker-local",
245
+ nodes=json.loads(json.dumps(spec["nodes"])) if resume else {})
246
+
247
+ def changed(r, nid):
248
+ progress["nodes"] = r.nodes
249
+
250
+ try:
251
+ timeout = float(spec.get("approval_timeout") or 0) or None
252
+ except (TypeError, ValueError):
253
+ timeout = None
254
+ steps = WorkerSteps(self.bus, changed, progress, poke or asyncio.Event(), timeout)
255
+ if box is not None:
256
+ box["steps"] = steps
257
+ run = await Engine(steps, changed).run(doc, run, resume=resume)
258
+ return {"status": run.status if run.status in ("done", "error", "cancelled") else "error",
259
+ "result": run.result, "error": run.error}
260
+ raise FlowError(f"unknown job kind {job['kind']!r}")
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: xqo-flows-runner
3
+ Version: 3.2.0
4
+ Summary: Headless remote worker for xqo flows: runs flow steps and whole flows with its own agents
5
+ Author: dudikkocak
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/dudikkocak/xqo
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: xqo<4,>=3.0
12
+ Requires-Dist: xqo-flows==3.2.0
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=8; extra == "dev"
15
+ Requires-Dist: pytest-timeout>=2.3; extra == "dev"
16
+ Requires-Dist: httpx>=0.27; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # xqo-flows-runner
20
+
21
+ A headless remote worker for [xqo-flows](../xqo-flows). It adds the `xqo worker` command, which polls an HQ's
22
+ flows worker API and runs jobs with this machine's own agents. There is no dashboard, no office and no open
23
+ port: the worker only makes outgoing HTTP calls to the HQ.
24
+
25
+ ```bash
26
+ pip install xqo-flows-runner # brings xqo and xqo-flows
27
+ ```
28
+
29
+ ## Set up a worker
30
+
31
+ 1. **On the HQ**, make a token and list the worker with its labels (`agents.json`):
32
+
33
+ ```bash
34
+ xqo flows token # prints a random token
35
+ export XQO_WORKER_GPU_BOX_TOKEN=... # the HQ reads the worker's token from this variable
36
+ ```
37
+
38
+ ```json
39
+ "flows": {"listen": "0.0.0.0:8200",
40
+ "workers": {"allow": {"gpu-box": {"token_env": "XQO_WORKER_GPU_BOX_TOKEN", "labels": ["gpu", "linux"]}}}}
41
+ ```
42
+
43
+ Restart `xqo serve`. Its banner shows `Flows worker API and webhooks: http://0.0.0.0:8200/flows/v1/`.
44
+
45
+ 2. **On the worker machine**, give it its own `agents.json` with its agents and a `flows_worker` block:
46
+
47
+ ```json
48
+ {"agents": [{"name": "builder", "skills": ["python", "build"]}],
49
+ "flows_worker": {"hq": "http://hq.example.internal:8200", "name": "gpu-box", "token_env": "XQO_WORKER_TOKEN", "jobs": 2}}
50
+ ```
51
+
52
+ ```bash
53
+ export XQO_WORKER_TOKEN=... # the same token as on the HQ
54
+ export ANTHROPIC_API_KEY=... # the worker's own model access
55
+ xqo --config agents.json worker
56
+ # xqo worker gpu-box: connected to HQ 'Main HQ' at http://hq.example.internal:8200, labels: gpu, linux, ...
57
+ ```
58
+
59
+ Flags override the file: `--hq`, `--name`, `--token-env`, `--jobs`, `--once` (run one job, then exit). The
60
+ environment variables `XQO_WORKER_HQ`, `XQO_WORKER_NAME` and `XQO_WORKER_JOBS` work too. Global flags such as
61
+ `--data-dir`, `--mock` and `--departments` go before `worker`, as with any xqo command.
62
+
63
+ 3. **Use it**: add a **Remote** step with label `gpu` to a flow, or run a whole flow on the worker with
64
+ `xqo flows run NAME --labels gpu`. `xqo flows workers` on the HQ shows whether the worker is online.
65
+
66
+ A complete sample is in [`../xqo-flows/examples/setup/`](../xqo-flows/examples/setup). It has the HQ and worker
67
+ configs, a remote flow, `docker-compose.worker.yml` (a worker in Docker, with no published port) and an `.env`
68
+ template.
69
+
70
+ ## What the worker does
71
+
72
+ | Job | Runs as |
73
+ |---|---|
74
+ | `task`: one Remote step | An ordinary root task on the worker, for the step's agent (empty = the worker's first agent). It is unattended unless the step says otherwise. Its result goes back to the HQ. |
75
+ | `flow`: a whole flow | The same flow engine as the HQ, using the worker's agents. Step states go back with every heartbeat, so the HQ's editor shows the run live. Approval steps are asked on the HQ and the answer comes back with a heartbeat. A resumed run brings the finished steps' results, so they do not run again. |
76
+
77
+ - **Heartbeats** go out every `lease_seconds / 3`, and every second while an approval waits. If the HQ answers "cancel" (the run was cancelled there), the
78
+ worker cancels the task and reports `cancelled`.
79
+ - **HQ unreachable:** the worker keeps retrying with a growing pause, up to 30 s. If the outage outlasts the lease,
80
+ the HQ gives the job to another worker. A rejected token (401/403) stops the worker.
81
+ - **Data:** each worker has its own data dir (tasks, workspaces, logs), so its tasks can be inspected with the
82
+ usual tools. To see them in a dashboard, run `xqo serve` on the same data dir while the worker is stopped (one
83
+ process per data dir).
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/xqo_flows_runner/__init__.py
5
+ src/xqo_flows_runner/worker.py
6
+ src/xqo_flows_runner.egg-info/PKG-INFO
7
+ src/xqo_flows_runner.egg-info/SOURCES.txt
8
+ src/xqo_flows_runner.egg-info/dependency_links.txt
9
+ src/xqo_flows_runner.egg-info/entry_points.txt
10
+ src/xqo_flows_runner.egg-info/requires.txt
11
+ src/xqo_flows_runner.egg-info/top_level.txt
12
+ tests/test_worker.py
@@ -0,0 +1,2 @@
1
+ [xqo.plugins]
2
+ flows_runner = xqo_flows_runner:RunnerPlugin
@@ -0,0 +1,7 @@
1
+ xqo<4,>=3.0
2
+ xqo-flows==3.2.0
3
+
4
+ [dev]
5
+ pytest>=8
6
+ pytest-timeout>=2.3
7
+ httpx>=0.27
@@ -0,0 +1 @@
1
+ xqo_flows_runner
@@ -0,0 +1,328 @@
1
+ """End to end: an HQ (dashboard + worker API on real ports) and a headless worker with its own agents."""
2
+ import asyncio
3
+ import json
4
+ import socket
5
+ import threading
6
+ import time
7
+ import urllib.request
8
+
9
+ import pytest
10
+ import uvicorn
11
+
12
+ from xqo.api import build
13
+ from xqo.web import create_app
14
+ from xqo_flows.workers import create_worker_app
15
+ from xqo_flows_runner import HQClient, HQError, Worker, settings
16
+
17
+ TOKEN = "s3cret-token-for-tests"
18
+
19
+
20
+ def free_port() -> int:
21
+ with socket.socket() as s:
22
+ s.bind(("127.0.0.1", 0))
23
+ return s.getsockname()[1]
24
+
25
+
26
+ def node(nid, type_, **data):
27
+ return {"id": nid, "type": type_, "data": data}
28
+
29
+
30
+ def edge(s, t, port=None):
31
+ return {"sourceNodeID": s, "targetNodeID": t, **({"sourcePortID": port} if port else {})}
32
+
33
+
34
+ class HQ:
35
+ """xqo serve in a thread: the dashboard app and the flows worker API on one event loop."""
36
+
37
+ def __init__(self, tmp_path, monkeypatch, lease=60):
38
+ monkeypatch.setenv("XQO_WORKER_GPU_TOKEN", TOKEN)
39
+ self.wport, self.port = free_port(), free_port()
40
+ cfg = tmp_path / "hq.json"
41
+ cfg.write_text(json.dumps({
42
+ "agents": [{"name": "planner2", "skills": ["python"]}],
43
+ "flows": {"examples": False, "workers": {"listen": f"127.0.0.1:{self.wport}", "lease_seconds": lease,
44
+ "allow": {"gpu": {"labels": ["gpu", "linux"]}}}}}))
45
+ self.bus = build(cfg, tmp_path / "hq" / "artifacts", str(tmp_path / "hq" / "logs" / "e.jsonl"), mock=True,
46
+ departments="none")
47
+ disp = self.bus.plugins.service("flows").dispatcher
48
+ self.servers = [uvicorn.Server(uvicorn.Config(create_app(self.bus), "127.0.0.1", self.port, log_level="warning")),
49
+ uvicorn.Server(uvicorn.Config(create_worker_app(disp, self.bus.plugins.service("flows")), "127.0.0.1", self.wport, log_level="warning"))]
50
+ self.thread = threading.Thread(target=lambda: asyncio.run(self._serve()), daemon=True)
51
+
52
+ async def _serve(self):
53
+ await asyncio.gather(*(s.serve() for s in self.servers))
54
+
55
+ def __enter__(self):
56
+ self.thread.start()
57
+ t0 = time.time()
58
+ while not all(s.started for s in self.servers):
59
+ assert time.time() - t0 < 10, "HQ did not start"
60
+ time.sleep(0.05)
61
+ return self
62
+
63
+ def __exit__(self, *exc):
64
+ for s in self.servers:
65
+ s.should_exit = True
66
+ self.thread.join(10)
67
+
68
+ def api(self, method, path, body=None):
69
+ req = urllib.request.Request(f"http://127.0.0.1:{self.port}{path}", method=method,
70
+ data=json.dumps(body).encode() if body is not None else None,
71
+ headers={"Content-Type": "application/json"})
72
+ with urllib.request.urlopen(req, timeout=30) as r:
73
+ return json.loads(r.read())
74
+
75
+ def wait_run(self, rid, timeout=30):
76
+ t0 = time.time()
77
+ while time.time() - t0 < timeout:
78
+ r = self.api("GET", f"/api/flows/runs/{rid}")
79
+ if r["status"] in ("done", "error", "cancelled", "interrupted"):
80
+ return r
81
+ time.sleep(0.1)
82
+ raise AssertionError(f"run still {r['status']}: {r}")
83
+
84
+
85
+ class WorkerThread:
86
+ def __init__(self, tmp_path, hq, name="gpu", token=TOKEN, agents=None):
87
+ cfg = tmp_path / f"{name}.json"
88
+ cfg.write_text(json.dumps({"agents": agents or [{"name": "builder", "skills": ["python"]}]}))
89
+ self.bus = build(cfg, tmp_path / name / "artifacts", str(tmp_path / name / "logs" / "e.jsonl"), mock=True,
90
+ departments="none")
91
+ self.client = HQClient(f"http://127.0.0.1:{hq.wport}", name, token)
92
+ self.logs = []
93
+ self.worker = None
94
+ self.error = None
95
+ self.thread = threading.Thread(target=self._go, daemon=True)
96
+
97
+ def _go(self):
98
+ async def main():
99
+ self.worker = Worker(self.bus, self.client, jobs=2, poll_wait=1, log=self.logs.append)
100
+ self.loop = asyncio.get_running_loop()
101
+ await self.worker.ping()
102
+ await self.worker.run()
103
+ try:
104
+ asyncio.run(main())
105
+ except Exception as e:
106
+ self.error = e
107
+
108
+ def __enter__(self):
109
+ self.thread.start()
110
+ return self
111
+
112
+ def __exit__(self, *exc):
113
+ if self.worker:
114
+ self.loop.call_soon_threadsafe(self.worker.stop)
115
+ self.thread.join(15)
116
+
117
+
118
+ def remote_step_flow():
119
+ return {"nodes": [node("s", "start", inputs=[{"name": "what", "default": "a parser"}]),
120
+ node("local", "agent", prompt="plan {{inputs.what}}"),
121
+ node("far", "remote", labels=["gpu"], agent="builder", prompt="build {{inputs.what}} after:\n{{local.result}}"),
122
+ node("e", "end", output="REMOTE {{far.result}} via {{far.worker}}")],
123
+ "edges": [edge("s", "local"), edge("local", "far"), edge("far", "e")]}
124
+
125
+
126
+ def test_remote_step_runs_on_the_worker_with_its_own_agents(tmp_path, monkeypatch):
127
+ with HQ(tmp_path, monkeypatch) as hq, WorkerThread(tmp_path, hq) as w:
128
+ hq.api("PUT", "/api/flows/build", remote_step_flow())
129
+ rid = hq.api("POST", "/api/flows/build/run", {"inputs": {"what": "a lexer"}})["id"]
130
+ r = hq.wait_run(rid)
131
+ assert r["status"] == "done", r
132
+ far = r["nodes"]["far"]
133
+ assert far["worker"] == "gpu" and far["job_id"]
134
+ task = w.bus.tasks[far["output"]["task_id"]] # the step ran as a task on the worker
135
+ assert task.assignee == "builder" and "a lexer" in task.prompt
136
+ assert r["result"].startswith("REMOTE ")
137
+ assert r["nodes"]["local"]["task_id"] in hq.bus.tasks # the local step stayed on the HQ
138
+ st = hq.api("GET", "/api/flows/workers")
139
+ assert st["workers"][0]["online"] and st["workers"][0]["labels"] == ["gpu", "linux"]
140
+
141
+
142
+ def test_whole_flow_runs_on_a_worker_and_reports_nodes(tmp_path, monkeypatch):
143
+ flow = {"nodes": [node("s", "start"), node("a", "agent", prompt="one"), node("b", "agent", agent="builder", prompt="two {{a.status}}"),
144
+ node("e", "end", output="W {{b.status}}")],
145
+ "edges": [edge("s", "a"), edge("a", "b"), edge("b", "e")]}
146
+ with HQ(tmp_path, monkeypatch) as hq, WorkerThread(tmp_path, hq) as w:
147
+ hq.api("PUT", "/api/flows/whole", flow)
148
+ rid = hq.api("POST", "/api/flows/whole/run", {"labels": ["linux"]})["id"]
149
+ r = hq.wait_run(rid)
150
+ assert r["status"] == "done" and r["result"] == "W done" and r["where"] == "worker:gpu"
151
+ assert r["nodes"]["b"]["status"] == "done" and r["nodes"]["b"]["task_id"] in w.bus.tasks
152
+ assert not any(t.assignee == "planner2" for t in hq.bus.tasks.values()) # nothing ran on the HQ
153
+
154
+
155
+ def approval_flow():
156
+ return {"nodes": [node("s", "start"), node("a", "agent", agent="builder", prompt="draft"),
157
+ node("ok", "approval", question="ship {{a.status}}?"),
158
+ node("b", "agent", agent="builder", prompt="ship"), node("e", "end", output="SHIPPED {{b.status}}"),
159
+ node("no", "end", output="REJECTED")],
160
+ "edges": [edge("s", "a"), edge("a", "ok"), edge("ok", "b", "approve"), edge("b", "e"),
161
+ edge("ok", "no", "reject")]}
162
+
163
+
164
+ def wait_status(hq, rid, status, timeout=30):
165
+ t0 = time.time()
166
+ while time.time() - t0 < timeout:
167
+ r = hq.api("GET", f"/api/flows/runs/{rid}")
168
+ if r["status"] == status:
169
+ return r
170
+ time.sleep(0.1)
171
+ raise AssertionError(f"run is {r['status']}, not {status}: {r}")
172
+
173
+
174
+ def test_whole_flow_with_an_approval_asks_on_the_hq(tmp_path, monkeypatch):
175
+ with HQ(tmp_path, monkeypatch) as hq, WorkerThread(tmp_path, hq) as w:
176
+ hq.api("PUT", "/api/flows/ap", approval_flow())
177
+ rid = hq.api("POST", "/api/flows/ap/run", {"remote": True})["id"]
178
+ r = wait_status(hq, rid, "waiting")
179
+ assert r["nodes"]["ok"]["status"] == "waiting" and r["nodes"]["ok"]["question"] == "ship done?"
180
+ pend = hq.api("GET", "/api/flows/approvals")
181
+ assert [(p["run_id"], p["node"]) for p in pend] == [(rid, "ok")]
182
+ hq.api("POST", f"/api/flows/runs/{rid}/approve", {"node": "ok", "approve": True})
183
+ r = hq.wait_run(rid)
184
+ assert r["status"] == "done" and r["result"] == "SHIPPED done", r
185
+ assert r["nodes"]["ok"]["answer"] == "approve" and r["nodes"]["no"]["status"] == "skipped"
186
+ assert r["where"] == "worker:gpu" and r["nodes"]["b"]["task_id"] in w.bus.tasks
187
+ assert hq.api("GET", "/api/flows/approvals") == []
188
+
189
+
190
+ def test_whole_flow_approval_times_out_on_the_worker(tmp_path, monkeypatch):
191
+ flow = approval_flow()
192
+ flow["nodes"][2]["data"].update(timeout=0.5, default="reject")
193
+ with HQ(tmp_path, monkeypatch) as hq, WorkerThread(tmp_path, hq):
194
+ hq.api("PUT", "/api/flows/ap", flow)
195
+ rid = hq.api("POST", "/api/flows/ap/run", {"remote": True})["id"]
196
+ r = hq.wait_run(rid)
197
+ assert r["status"] == "done" and r["result"] == "REJECTED", r
198
+ assert r["nodes"]["ok"]["answered_by"] == "timeout"
199
+
200
+
201
+ def test_whole_flow_run_resumes_on_a_worker_keeping_done_steps(tmp_path, monkeypatch):
202
+ with HQ(tmp_path, monkeypatch) as hq, WorkerThread(tmp_path, hq) as w:
203
+ hq.api("PUT", "/api/flows/ap", approval_flow())
204
+ rid = hq.api("POST", "/api/flows/ap/run", {"labels": ["gpu"]})["id"]
205
+ wait_status(hq, rid, "waiting")
206
+ first = hq.api("GET", f"/api/flows/runs/{rid}")["nodes"]["a"]["task_id"]
207
+ r = hq.api("POST", f"/api/flows/runs/{rid}/cancel")
208
+ r = hq.wait_run(rid)
209
+ assert r["status"] == "cancelled" and r["resumable"]
210
+ r = hq.api("POST", f"/api/flows/runs/{rid}/resume")
211
+ assert r["status"] == "running" and r["resumed"] == 1 and not r["resumable"]
212
+ wait_status(hq, rid, "waiting")
213
+ hq.api("POST", f"/api/flows/runs/{rid}/approve", {"node": "ok", "approve": True})
214
+ r = hq.wait_run(rid)
215
+ assert r["status"] == "done" and r["result"] == "SHIPPED done", r
216
+ assert r["nodes"]["a"]["task_id"] == first # the done step did not run again
217
+ assert sum(1 for t in w.bus.tasks.values() if t.prompt == "draft") == 1
218
+
219
+
220
+ def test_webhook_on_the_public_listener(tmp_path, monkeypatch):
221
+ import hashlib
222
+ import hmac as _hmac
223
+ monkeypatch.setenv("HOOK_SECRET", "hk")
224
+ flow = {"nodes": [node("s", "start", inputs=[{"name": "msg", "default": ""}]),
225
+ node("a", "agent", prompt="handle {{inputs.msg}}"), node("e", "end", output="{{inputs.msg}}")],
226
+ "edges": [edge("s", "a"), edge("a", "e")],
227
+ "triggers": [{"id": "gh", "type": "webhook", "secret_env": "HOOK_SECRET",
228
+ "inputs": {"msg": "{{body.action}}"}}]}
229
+ with HQ(tmp_path, monkeypatch) as hq:
230
+ hq.api("PUT", "/api/flows/hooked", flow)
231
+ body = b'{"action": "opened"}'
232
+ sig = "sha256=" + _hmac.new(b"hk", body, hashlib.sha256).hexdigest()
233
+ url = f"http://127.0.0.1:{hq.wport}/flows/v1/hooks/hooked/gh"
234
+ req = urllib.request.Request(url, data=body, method="POST", headers={"X-Hub-Signature-256": sig})
235
+ with urllib.request.urlopen(req, timeout=10) as resp:
236
+ assert resp.status == 202
237
+ rid = json.loads(resp.read())["run_id"]
238
+ r = hq.wait_run(rid)
239
+ assert r["status"] == "done" and "opened" in r["result"] and "<untrusted_webhook_data>" in r["result"]
240
+ assert r["trigger"] == {"id": "gh", "type": "webhook"}
241
+ bad = urllib.request.Request(url, data=body, method="POST", headers={"X-Hub-Signature-256": "sha256=00"})
242
+ with pytest.raises(urllib.error.HTTPError) as e:
243
+ urllib.request.urlopen(bad, timeout=10)
244
+ assert e.value.code == 401
245
+
246
+
247
+ def test_labels_no_worker_has_fail_at_once(tmp_path, monkeypatch):
248
+ flow = remote_step_flow()
249
+ flow["nodes"][2]["data"]["labels"] = ["tpu"]
250
+ with HQ(tmp_path, monkeypatch) as hq:
251
+ saved = hq.api("PUT", "/api/flows/f", flow)
252
+ assert "no worker" in saved["warnings"][0]
253
+ with pytest.raises(urllib.error.HTTPError):
254
+ hq.api("POST", "/api/flows/f/run", {})
255
+
256
+
257
+ def test_wrong_token_and_unknown_worker_are_refused(tmp_path, monkeypatch):
258
+ with HQ(tmp_path, monkeypatch) as hq:
259
+ for name, token, code in (("gpu", "wrong", 401), ("nobody", TOKEN, 401)):
260
+ with pytest.raises(HQError) as e:
261
+ HQClient(f"http://127.0.0.1:{hq.wport}", name, token).call("GET", "/flows/v1/ping")
262
+ assert e.value.status == code
263
+ assert HQClient(f"http://127.0.0.1:{hq.wport}", "gpu", TOKEN).call("GET", "/flows/v1/ping")["labels"] == ["gpu", "linux"]
264
+
265
+
266
+ def test_cancel_on_the_hq_cancels_the_task_on_the_worker(tmp_path, monkeypatch):
267
+ with HQ(tmp_path, monkeypatch, lease=0.6) as hq, WorkerThread(tmp_path, hq) as w:
268
+ async def slow(task):
269
+ await asyncio.sleep(60)
270
+ w.bus.agents["builder"].handle = slow
271
+ flow = remote_step_flow()
272
+ flow["nodes"][1]["data"]["prompt"] = "x"
273
+ hq.api("PUT", "/api/flows/slow", flow)
274
+ rid = hq.api("POST", "/api/flows/slow/run", {})["id"]
275
+ t0 = time.time()
276
+ while hq.api("GET", f"/api/flows/runs/{rid}")["nodes"]["far"].get("status") != "running" or \
277
+ not any(t.assignee == "builder" for t in w.bus.tasks.values()):
278
+ assert time.time() - t0 < 20
279
+ time.sleep(0.1)
280
+ assert hq.api("POST", f"/api/flows/runs/{rid}/cancel")["status"] == "cancelled"
281
+ t0 = time.time()
282
+ while not any(t.status == "cancelled" for t in w.bus.tasks.values() if t.assignee == "builder"):
283
+ assert time.time() - t0 < 20, w.logs
284
+ time.sleep(0.1)
285
+ job = hq.api("GET", "/api/flows/workers")["jobs"][0]
286
+ t0 = time.time()
287
+ while job["status"] == "claimed":
288
+ assert time.time() - t0 < 20
289
+ time.sleep(0.1)
290
+ job = hq.api("GET", "/api/flows/workers")["jobs"][0]
291
+ assert job["status"] == "cancelled"
292
+
293
+
294
+ def test_a_lost_worker_gives_the_job_back_and_another_takes_it(tmp_path, monkeypatch):
295
+ with HQ(tmp_path, monkeypatch, lease=0.5) as hq:
296
+ hq.api("PUT", "/api/flows/build", remote_step_flow())
297
+ rid = hq.api("POST", "/api/flows/build/run", {})["id"]
298
+ c = HQClient(f"http://127.0.0.1:{hq.wport}", "gpu", TOKEN)
299
+ job = None
300
+ t0 = time.time()
301
+ while not job: # a worker takes the job and then disappears (no heartbeat, no result)
302
+ job = c.call("POST", "/flows/v1/next", {"wait": 1})["job"]
303
+ assert time.time() - t0 < 20
304
+ with WorkerThread(tmp_path, hq) as w:
305
+ r = hq.wait_run(rid)
306
+ assert r["status"] == "done", r
307
+ jobs = hq.api("GET", "/api/flows/workers")["jobs"]
308
+ assert jobs[0]["attempts"] == 2
309
+
310
+
311
+ def test_worker_settings():
312
+ import os
313
+ os.environ["T_TOK"] = "x"
314
+ s = settings({"flows_worker": {"hq": "http://h:8200", "name": "w1", "token_env": "T_TOK", "jobs": 3}})
315
+ assert s["jobs"] == 3 and s["token"] == "x"
316
+ with pytest.raises(ValueError, match="plaintext"):
317
+ settings({"flows_worker": {"hq": "h", "name": "n", "token": "abc"}})
318
+ with pytest.raises(ValueError, match="--hq"):
319
+ settings({})
320
+ with pytest.raises(ValueError, match="set NOPE_TOK"):
321
+ settings({"flows_worker": {"hq": "h", "name": "n", "token_env": "NOPE_TOK"}})
322
+
323
+
324
+ def test_worker_command_is_registered():
325
+ import subprocess
326
+ import sys
327
+ out = subprocess.run([sys.executable, "-m", "xqo", "worker", "--help"], capture_output=True, text=True)
328
+ assert out.returncode == 0 and "--hq" in out.stdout