xqo-flows-runner 3.2.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.
- xqo_flows_runner/__init__.py +120 -0
- xqo_flows_runner/worker.py +260 -0
- xqo_flows_runner-3.2.0.dist-info/METADATA +83 -0
- xqo_flows_runner-3.2.0.dist-info/RECORD +8 -0
- xqo_flows_runner-3.2.0.dist-info/WHEEL +5 -0
- xqo_flows_runner-3.2.0.dist-info/entry_points.txt +2 -0
- xqo_flows_runner-3.2.0.dist-info/licenses/LICENSE +21 -0
- xqo_flows_runner-3.2.0.dist-info/top_level.txt +1 -0
|
@@ -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,8 @@
|
|
|
1
|
+
xqo_flows_runner/__init__.py,sha256=lgMazX9YasmknJCdbQ_2s4_b3i7NSlHEEAdTwSFJBoc,5073
|
|
2
|
+
xqo_flows_runner/worker.py,sha256=vpPiiWrb97FbL79fz0B6EnLwm9gKkB1G9EAajelOSc8,12515
|
|
3
|
+
xqo_flows_runner-3.2.0.dist-info/licenses/LICENSE,sha256=PHtf4TI2P6oulwhOKBF8SgeOkDLp9YnLdq46mw6506s,1067
|
|
4
|
+
xqo_flows_runner-3.2.0.dist-info/METADATA,sha256=KjGG-5yZIk-wES31Bj_cVtwBGka528n_YiBoqIvXKk8,4143
|
|
5
|
+
xqo_flows_runner-3.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
xqo_flows_runner-3.2.0.dist-info/entry_points.txt,sha256=IA0nugTzqwEOiLRehhBh4Z7CU_pDJRtGOikdZJsBUns,59
|
|
7
|
+
xqo_flows_runner-3.2.0.dist-info/top_level.txt,sha256=0KS7lAQh6XSId-wA2LelT_by1mRul4BWhU9vgDZyh94,17
|
|
8
|
+
xqo_flows_runner-3.2.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
xqo_flows_runner
|