#!/usr/bin/env python3 """Example orch `cmd` adapter for Gitea (source + sink). See docs/cmd-protocol.md. Env: ORCH_GITEA_HOST (git.example.com), ORCH_GITEA_REPO (owner/name), ORCH_GITEA_CLONE (local clone path). Issues labeled `orch` are tasks. Labels orch-running / orch-done / orch-failed track state; create them first. """ import base64, json, os, subprocess, sys, urllib.error, urllib.request HOST, REPO, CLONE = (os.environ[k] for k in ("ORCH_GITEA_HOST", "ORCH_GITEA_REPO", "ORCH_GITEA_CLONE")) def auth(): out = subprocess.run(["git", "credential", "fill"], input=f"protocol=https\nhost={HOST}\n\n", capture_output=True, text=True, check=True).stdout c = dict(l.split("=", 1) for l in out.splitlines() if "=" in l) return "Basic " + base64.b64encode(f"{c['username']}:{c['password']}".encode()).decode() def api(method, path, body=None): r = urllib.request.Request(f"https://{HOST}/api/v1/repos/{REPO}/{path}", method=method, data=None if body is None else json.dumps(body).encode(), headers={"Authorization": auth(), "Content-Type": "application/json", "User-Agent": "curl/8.5.0"}) # Cloudflare blocks the python UA raw = urllib.request.urlopen(r).read() return json.loads(raw) if raw.strip() else {} def label_ids(): return {l["name"]: l["id"] for l in api("GET", "labels?limit=100")} def set_label(num, remove, add): ids = label_ids() try: api("DELETE", f"issues/{num}/labels/{ids[remove]}") except urllib.error.HTTPError: pass # label not on the issue api("POST", f"issues/{num}/labels", {"labels": [ids[add]]}) def task(i): return {"id": f"issue-{i['number']}", "title": i["title"], "body": f"{i['title']}\n\n{i['body']}", "repo": CLONE, "number": i["number"]} def main(op): data = json.load(sys.stdin) if op == "list": issues = api("GET", "issues?state=open&type=issues&labels=orch&limit=50") return {"tasks": [task(i) for i in issues]} t = data["task"] if op == "claim": cur = api("GET", f"issues/{t['number']}") if any(l["name"] == "orch-running" for l in cur["labels"]): return {"claimed": False} set_label(t["number"], "orch", "orch-running") # ponytail: not atomic; a lock arrives with O4 return {"claimed": True} run = data["run"] if op == "report": ok = run["status"] == "done" set_label(t["number"], "orch-running", "orch-done" if ok else "orch-failed") api("POST", f"issues/{t['number']}/comments", {"body": f"orch run `{run['id']}`: **{run['status']}**" + (f" ({run['reason']})" if run["reason"] else "") + f", {run['attempts']} attempt(s), {run['input_tokens'] + run['output_tokens']} tokens."}) return {} if op == "publish": subprocess.run(["git", "push", "-q", "origin", run["branch"]], cwd=run["repo"], check=True) pr = api("POST", "pulls", {"head": run["branch"], "base": "main", "title": t["title"], "body": f"Closes #{t['number']}\n\nAutomated by orch run `{run['id']}`."}) return {"url": pr.get("html_url")} raise SystemExit(f"unknown op {op}") if __name__ == "__main__": print(json.dumps(main(sys.argv[1])))