|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Diff-first PATCH of agent adapterConfig + desiredSkills + heartbeat from manifest. |
| 3 | +
|
| 4 | +Called by `agents/deploy.sh` after the markdown PUT pass. Reads `.paperclip.yaml` |
| 5 | +and per-agent `AGENTS.md` frontmatter, compares with prod via Paperclip API, |
| 6 | +PATCHes only agents whose config actually drifted. |
| 7 | +
|
| 8 | +Env: PAPERCLIP_URL, PAPERCLIP_API_KEY, COMPANY_ID, SCRIPT_DIR, DRY_RUN. |
| 9 | +""" |
| 10 | + |
| 11 | +import json |
| 12 | +import os |
| 13 | +import re |
| 14 | +import sys |
| 15 | +import urllib.error |
| 16 | +import urllib.request |
| 17 | + |
| 18 | +import yaml |
| 19 | + |
| 20 | +URL = os.environ["PAPERCLIP_URL"] |
| 21 | +KEY = os.environ["PAPERCLIP_API_KEY"] |
| 22 | +COMPANY = os.environ["COMPANY_ID"] |
| 23 | +SCRIPT_DIR = os.environ["SCRIPT_DIR"] |
| 24 | +DRY = os.environ.get("DRY_RUN", "0") == "1" |
| 25 | + |
| 26 | +# Skills published under paperclipai/paperclip/ — preserve when present, don't expect them in frontmatter. |
| 27 | +PAPERCLIP_NS_SKILLS = { |
| 28 | + "paperclip", |
| 29 | + "paperclip-create-agent", |
| 30 | + "paperclip-create-plugin", |
| 31 | + "para-memory-files", |
| 32 | +} |
| 33 | + |
| 34 | + |
| 35 | +def api(method: str, path: str, body=None): |
| 36 | + req = urllib.request.Request(URL + path, method=method) |
| 37 | + req.add_header("Authorization", f"Bearer {KEY}") |
| 38 | + req.add_header("Content-Type", "application/json") |
| 39 | + # Cloudflare in front of org.ffmemes.com blocks default Python-urllib UA (error 1010). |
| 40 | + req.add_header("User-Agent", "ffmemes-deploy.sh/1.0") |
| 41 | + data = json.dumps(body).encode() if body is not None else None |
| 42 | + try: |
| 43 | + with urllib.request.urlopen(req, data=data) as resp: |
| 44 | + return json.loads(resp.read()) |
| 45 | + except urllib.error.HTTPError as e: |
| 46 | + print(f" HTTP {e.code} on {method} {path}: {e.read().decode()[:300]}", file=sys.stderr) |
| 47 | + raise |
| 48 | + |
| 49 | + |
| 50 | +def skill_to_path(slug: str) -> str: |
| 51 | + if slug in PAPERCLIP_NS_SKILLS: |
| 52 | + return f"paperclipai/paperclip/{slug}" |
| 53 | + return f"garrytan/gstack/{slug}" |
| 54 | + |
| 55 | + |
| 56 | +def read_frontmatter_skills(agents_md_path: str) -> list[str]: |
| 57 | + if not os.path.exists(agents_md_path): |
| 58 | + return [] |
| 59 | + with open(agents_md_path) as f: |
| 60 | + text = f.read() |
| 61 | + m = re.match(r"^---\n(.*?)\n---", text, re.DOTALL) |
| 62 | + if not m: |
| 63 | + return [] |
| 64 | + fm = yaml.safe_load(m.group(1)) or {} |
| 65 | + return list(fm.get("skills") or []) |
| 66 | + |
| 67 | + |
| 68 | +def main() -> int: |
| 69 | + with open(f"{SCRIPT_DIR}/.paperclip.yaml") as f: |
| 70 | + manifest = yaml.safe_load(f) |
| 71 | + |
| 72 | + agents_list = api("GET", f"/api/companies/{COMPANY}/agents") |
| 73 | + by_slug = {a["urlKey"]: a for a in agents_list} |
| 74 | + |
| 75 | + patched = 0 |
| 76 | + skipped = 0 |
| 77 | + failed = 0 |
| 78 | + would_patch = 0 |
| 79 | + for slug, mblock in (manifest.get("agents") or {}).items(): |
| 80 | + if slug not in by_slug: |
| 81 | + print(f" SKIP {slug} — not in prod") |
| 82 | + continue |
| 83 | + cur = by_slug[slug] |
| 84 | + |
| 85 | + # Targets from manifest |
| 86 | + ad_cfg = (mblock.get("adapter") or {}).get("config") or {} |
| 87 | + target_model = ad_cfg.get("model") |
| 88 | + target_max_turns = ad_cfg.get("maxTurnsPerRun") |
| 89 | + target_heartbeat = (mblock.get("runtime") or {}).get("heartbeat") or {} |
| 90 | + target_perms = mblock.get("permissions") or {} |
| 91 | + |
| 92 | + # Frontmatter → desiredSkills (preserve any paperclipai/* currently attached) |
| 93 | + fm_skills = read_frontmatter_skills(f"{SCRIPT_DIR}/{slug}/AGENTS.md") |
| 94 | + cur_ac = cur.get("adapterConfig") or {} |
| 95 | + cur_skills = ((cur_ac.get("paperclipSkillSync") or {}).get("desiredSkills")) or [] |
| 96 | + preserved = [s for s in cur_skills if s.startswith("paperclipai/")] |
| 97 | + target_skills = sorted(set(preserved + [skill_to_path(s) for s in fm_skills])) |
| 98 | + cur_skills_sorted = sorted(cur_skills) |
| 99 | + |
| 100 | + # Diff |
| 101 | + changes: list[str] = [] |
| 102 | + if target_model and cur_ac.get("model") != target_model: |
| 103 | + changes.append(f"model: {cur_ac.get('model')} → {target_model}") |
| 104 | + if target_max_turns and cur_ac.get("maxTurnsPerRun") != target_max_turns: |
| 105 | + changes.append( |
| 106 | + f"maxTurnsPerRun: {cur_ac.get('maxTurnsPerRun')} → {target_max_turns}" |
| 107 | + ) |
| 108 | + if target_skills != cur_skills_sorted: |
| 109 | + added = sorted(set(target_skills) - set(cur_skills_sorted)) |
| 110 | + removed = sorted(set(cur_skills_sorted) - set(target_skills)) |
| 111 | + if added: |
| 112 | + changes.append(f"+skills: {added}") |
| 113 | + if removed: |
| 114 | + changes.append(f"-skills: {removed}") |
| 115 | + |
| 116 | + cur_rt = cur.get("runtimeConfig") or {} |
| 117 | + cur_hb = cur_rt.get("heartbeat") or {} |
| 118 | + for k, v in target_heartbeat.items(): |
| 119 | + if cur_hb.get(k) != v: |
| 120 | + changes.append(f"heartbeat.{k}: {cur_hb.get(k)} → {v}") |
| 121 | + |
| 122 | + cur_perms = cur.get("permissions") or {} |
| 123 | + perm_changes: list[tuple[str, object]] = [] |
| 124 | + for k, v in target_perms.items(): |
| 125 | + if cur_perms.get(k) != v: |
| 126 | + perm_changes.append((k, v)) |
| 127 | + changes.append(f"permissions.{k}: {cur_perms.get(k)} → {v}") |
| 128 | + |
| 129 | + if not changes: |
| 130 | + print(f" skip {slug} (no config drift)") |
| 131 | + skipped += 1 |
| 132 | + continue |
| 133 | + |
| 134 | + if DRY: |
| 135 | + print(f" WOULD PATCH {slug}: {'; '.join(changes)}") |
| 136 | + would_patch += 1 |
| 137 | + continue |
| 138 | + |
| 139 | + # Build merged payload — preserve everything else (instructionsFilePath, env, etc.) |
| 140 | + new_ac = dict(cur_ac) |
| 141 | + if target_model: |
| 142 | + new_ac["model"] = target_model |
| 143 | + if target_max_turns: |
| 144 | + new_ac["maxTurnsPerRun"] = target_max_turns |
| 145 | + new_skill_sync = dict(new_ac.get("paperclipSkillSync") or {}) |
| 146 | + new_skill_sync["desiredSkills"] = target_skills |
| 147 | + new_ac["paperclipSkillSync"] = new_skill_sync |
| 148 | + |
| 149 | + new_rt = dict(cur_rt) |
| 150 | + new_hb = dict(cur_hb) |
| 151 | + new_hb.update(target_heartbeat) |
| 152 | + new_rt["heartbeat"] = new_hb |
| 153 | + |
| 154 | + # Permissions go through a separate endpoint (PATCH /api/agents/:id rejects them). |
| 155 | + body = { |
| 156 | + "adapterConfig": new_ac, |
| 157 | + "runtimeConfig": new_rt, |
| 158 | + } |
| 159 | + try: |
| 160 | + api("PATCH", f"/api/agents/{cur['id']}", body) |
| 161 | + print(f" PATCHED {slug}: {'; '.join(changes)}") |
| 162 | + patched += 1 |
| 163 | + if perm_changes: |
| 164 | + # Best-effort permissions update via dedicated endpoint. |
| 165 | + new_perms = dict(cur_perms) |
| 166 | + new_perms.update(target_perms) |
| 167 | + try: |
| 168 | + api("PATCH", f"/api/agents/{cur['id']}/permissions", new_perms) |
| 169 | + print(f" + permissions updated: {dict(perm_changes)}") |
| 170 | + except Exception as pe: |
| 171 | + print(f" WARN permissions sync failed for {slug}: {pe}", file=sys.stderr) |
| 172 | + except Exception as e: |
| 173 | + print(f" ERROR PATCH {slug}: {e}", file=sys.stderr) |
| 174 | + failed += 1 |
| 175 | + |
| 176 | + if DRY: |
| 177 | + print(f"\nConfig sync (dry-run): would patch {would_patch}, skip {skipped} (no drift).") |
| 178 | + else: |
| 179 | + print(f"\nConfig sync: patched={patched}, skipped={skipped}, failed={failed}.") |
| 180 | + return 1 if failed > 0 else 0 |
| 181 | + |
| 182 | + |
| 183 | +if __name__ == "__main__": |
| 184 | + sys.exit(main()) |
0 commit comments