diff --git a/support_diagnostic/run.py b/support_diagnostic/run.py new file mode 100644 index 0000000..795a2be --- /dev/null +++ b/support_diagnostic/run.py @@ -0,0 +1,185 @@ +"""Une exécution : les conversations étiquetées tri:diagnostic, les agents, une note privée, les étiquettes d'état. + +python -m support_diagnostic.run — configuration par l'environnement (spec §7, §9.2). Seul ce code déterministe écrit +dans LibreDesk, par le client restreint ; les agents rendent du texte. +""" +import email.header +import html +import os +import sys +import tempfile +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Mapping + +from .libredesk import Garde, LibreDesk + +TRI, EN_COURS, RELANCER = "tri:diagnostic", "diag:en-cours", "diag:relancer" +ENTETE = "
🤖 BROUILLON IA — à relire, ne pas envoyer tel quel
" +TYPES_IMAGE = {"image/png", "image/jpeg", "image/gif", "image/webp"} +TAILLE_MIN = 10_000 # ponytail: octets, écarte les logos des signatures (comme Support-Agent) +MODELE = "claude-opus-5-5" # celui de agents/support/agent.py + + +@dataclass +class Config: + url: str + cle: str + secret: str + ecrire: bool + autorisees: set[str] | None # None : toutes (« * ») + plafond: int + conversation: str # "" : toutes les éligibles + donnees: Path + cases: Path + + @staticmethod + def depuis_env(env: Mapping[str, str]) -> "Config | None": + """None si KILL_SWITCH est actif. Écrire exige DRY_RUN=false et une liste blanche (des uuid, ou *).""" + if env.get("KILL_SWITCH", "").strip() not in ("", "false", "0"): + return None + ecrire = env.get("DRY_RUN", "true").strip() == "false" + liste = env.get("ALLOWED_CONVERSATION_IDS", "").strip() + if ecrire and not liste: + raise ValueError("DRY_RUN=false exige ALLOWED_CONVERSATION_IDS (des uuid séparés par des virgules, ou *)") + autorisees = None if liste == "*" else {u.strip() for u in liste.split(",") if u.strip()} or None + return Config(env["LIBREDESK_URL"], env["LIBREDESK_API_KEY"], env["LIBREDESK_API_SECRET"], ecrire, autorisees, + int(env.get("MAX_CONVERSATIONS_PER_RUN") or 3), env.get("CONVERSATION", "").strip(), + Path(env.get("AIMSIGHT_DATA") or "data"), + Path(env.get("AIMSIGHT_CASES") or tempfile.mkdtemp(prefix="cases-"))) + + +def eligible(etiquettes: list[str]) -> bool: + diag = [t for t in etiquettes if t.startswith("diag:")] + return TRI in etiquettes and (not diag or RELANCER in diag) + + +def _objet(s: str | None) -> str: + try: + return str(email.header.make_header(email.header.decode_header(s or ""))) + except (LookupError, ValueError, UnicodeDecodeError): + return s or "" + + +def fil(messages: list[dict], moi: int) -> tuple[str, str]: + """(le mail, le contexte). Le mail : le fil avec le client, le plus récent en tête, comme un mail collé (repris de + Support-Agent/app/serveur/libredesk.py). Le contexte : les notes privées des humains ; jamais les nôtres.""" + blocs, notes = [], [] + for m in sorted(messages, key=lambda m: m["created_at"], reverse=True): + texte = (m.get("text_content") or m.get("content") or "").strip() + if m.get("private"): + if m.get("sender_id") != moi and texte: + notes.append(texte) + continue + if m.get("type") not in ("incoming", "outgoing") or not texte: + continue + a, meta = m.get("author") or {}, m.get("meta") or {} + qui = " ".join(filter(None, [a.get("first_name"), a.get("last_name")])) or ", ".join(meta.get("from") or []) + tete = [f"De: {qui}" + (f" <{a['email']}>" if a.get("email") else ""), f"Date: {m['created_at']}"] + if meta.get("subject"): + tete.append(f"Objet: {_objet(meta['subject'])}") + blocs.append("\n".join(tete) + "\n\n" + texte) + return "\n\n---\n\n".join(blocs), "\n\n".join(reversed(notes)) + + +def _paragraphes(texte: str) -> str: + return "".join(f"{html.escape(p.strip()).replace(chr(10), '
')}
Figures préparées (non jointes) : {html.escape(', '.join(p.name for p in r.pieces))}
" + if r.pieces else "") + return (f"{ENTETE}{titre}
{_paragraphes(r.texte)}{figures}" + f"Exécution {html.escape(execution)} · modèle {MODELE} · coût {r.cout:.2f} $
") + + +def _execution() -> str: + e = os.environ + ou = (f"{e['GITHUB_SERVER_URL']}/{e['GITHUB_REPOSITORY']}/actions/runs/{e['GITHUB_RUN_ID']}" + if all(e.get(k) for k in ("GITHUB_SERVER_URL", "GITHUB_REPOSITORY", "GITHUB_RUN_ID")) else "local") + return f"{ou} · commit {e.get('GITHUB_SHA', '')[:7] or '?'}" + + +def _images(ld, messages: list[dict]) -> list[tuple[str, bytes]]: + return [(p["content_type"], ld.piece(p["url"])) for m in messages + if m.get("type") == "incoming" and not m.get("private") + for p in m.get("attachments") or [] + if p.get("content_type") in TYPES_IMAGE and (p.get("size") or 0) >= TAILLE_MIN and p.get("url")] + + +def _une(ld, cfg: Config, uuid: str, diag, execution: str): + from .diagnostic import Resultat + # ponytail: verrou orphelin non détecté (runner tué) : un humain retire diag:en-cours ; date de l'étiquette si ça arrive + ld.etiqueter(uuid, [EN_COURS]) + messages = ld.messages(uuid) + mail, contexte = fil(messages, ld.moi()) + if not "".join(m.get("text_content") or "" for m in messages if m.get("type") == "incoming").strip(): + r = Resultat("ignore", "Le mail du client ne contient pas de texte.", [], 0.0, None) + else: + r = diag(mail, _images(ld, messages), contexte, cfg.donnees, cfg.cases) + ld.note_privee(uuid, note(r, execution)) + ld.etiqueter(uuid, ["diag:" + r.statut], [EN_COURS, RELANCER]) + return r + + +def traiter(ld, cfg: Config, diag=None) -> dict[str, str]: + if diag is None: + from .diagnostic import diagnostiquer as diag + debut, execution, statuts, couts = time.monotonic(), _execution(), {}, {} + if cfg.conversation: + candidates = [cfg.conversation] + else: + candidates = [c["uuid"] for c in ld.conversations(ld.ids_etiquettes()[TRI])] + for uuid in candidates: + if len(statuts) >= cfg.plafond: + break + if (cfg.autorisees is not None and uuid not in cfg.autorisees) or not eligible(ld.etiquettes(uuid)): + continue + print(f"--- {uuid}", flush=True) + try: + r = _une(ld, cfg, uuid, diag, execution) + statuts[uuid], couts[uuid] = r.statut, r.cout + except Garde: + try: + ld.etiqueter(uuid, ["diag:erreur"], [EN_COURS]) + finally: + raise + except Exception as e: # noqa: BLE001 — une conversation en échec n'arrête pas les autres + print(f"[erreur] {uuid} : {type(e).__name__}: {e}", flush=True) + statuts[uuid], couts[uuid] = "erreur", 0.0 + for essai in (lambda: ld.note_privee(uuid, f"{ENTETE}Diagnostic en échec : {html.escape(type(e).__name__)}." + f"
Exécution {html.escape(execution)}
"), + lambda: ld.etiqueter(uuid, ["diag:erreur"], [EN_COURS])): + try: + essai() + except Garde: + raise + except Exception as e2: # noqa: BLE001 + print(f"[erreur] {uuid} : {type(e2).__name__}: {e2}", flush=True) + for uuid, s in statuts.items(): + print(f"{uuid} {s} {couts[uuid]:.2f} $") + print(f"{len(statuts)} conversation(s), {sum(couts.values()):.2f} $, {time.monotonic() - debut:.0f} s" + + ("" if cfg.ecrire else " (simulation : rien n'a été écrit)")) + return statuts + + +def main() -> int: + cfg = Config.depuis_env(os.environ) + if cfg is None: + print("KILL_SWITCH actif : rien n'est lu ni écrit.") + return 0 + ld = LibreDesk(cfg.url, cfg.cle, cfg.secret, cfg.ecrire) + try: + traiter(ld, cfg) + except Garde as e: + print(f"[garde-fou] arrêt de toute l'exécution : {e}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_run.py b/tests/test_run.py new file mode 100644 index 0000000..0e00ab1 --- /dev/null +++ b/tests/test_run.py @@ -0,0 +1,179 @@ +import unittest +from pathlib import Path + +from support_diagnostic.diagnostic import Resultat +from support_diagnostic.libredesk import Garde +from support_diagnostic.run import Config, eligible, fil, note, traiter + +ENTETE = "🤖 BROUILLON IA — à relire, ne pas envoyer tel quel
" +MOI = 4 +ENV = {"LIBREDESK_URL": "http://ld", "LIBREDESK_API_KEY": "k", "LIBREDESK_API_SECRET": "s"} + + +def msg(type_, texte, private=False, sender=10, quand="2026-11-09T08:00:00Z", pieces=()): + return {"uuid": f"m-{texte[:8]}", "type": type_, "private": private, "sender_id": sender, "created_at": quand, + "author": {"first_name": "Client" if type_ == "incoming" else "Marc"}, "meta": {}, + "text_content": texte, "content": f"{texte}
", "attachments": list(pieces)} + + +class FauxLD: + """Le client LibreDesk en mémoire : mêmes méthodes, ecrire comme le vrai.""" + def __init__(self, conversations: dict[str, list[str]], ecrire=True, note_leve=None): + self.tags = {u: list(t) for u, t in conversations.items()} + self.msgs = {u: [msg("incoming", f"Mes courbes {u} ?")] for u in conversations} + self.ecrire, self.note_leve = ecrire, note_leve + self.notes: list[tuple[str, str]] = [] + self.lus: list[str] = [] + + def moi(self): + return MOI + + def ids_etiquettes(self): + return {"tri:diagnostic": 1} + + def conversations(self, avec): + return [{"uuid": u} for u, t in self.tags.items() if "tri:diagnostic" in t] + + def etiquettes(self, uuid): + return list(self.tags[uuid]) + + def messages(self, uuid): + self.lus.append(uuid) + return self.msgs[uuid] + + def piece(self, url): + return b"x" * 20_000 + + def etiqueter(self, uuid, ajouter=(), retirer=()): + if self.ecrire: + self.tags[uuid] = [t for t in self.tags[uuid] if t not in retirer] + [t for t in ajouter if t not in self.tags[uuid]] + + def note_privee(self, uuid, html): + if self.note_leve: + raise self.note_leve + if self.ecrire: + self.notes.append((uuid, html)) + + +def cfg(**plus): + return Config.depuis_env({**ENV, "DRY_RUN": "false", "ALLOWED_CONVERSATION_IDS": "*", **plus}) + + +def diag_fait(mail, images, contexte, donnees, cases): + return Resultat("fait", "Bonjour,\n\nTout va bien.", [], 1.5, Path("/tmp")) + + +class TestConfig(unittest.TestCase): + def test_dry_run_par_defaut(self): + self.assertFalse(Config.depuis_env(ENV).ecrire) + for v in ("False", "0", "no", "true", ""): + self.assertFalse(Config.depuis_env({**ENV, "DRY_RUN": v}).ecrire, v) + self.assertTrue(cfg().ecrire) + + def test_ecrire_exige_liste_blanche(self): + with self.assertRaises(ValueError): + Config.depuis_env({**ENV, "DRY_RUN": "false"}) + self.assertIsNone(cfg().autorisees) + self.assertEqual(cfg(ALLOWED_CONVERSATION_IDS="c1, c2").autorisees, {"c1", "c2"}) + + def test_kill_switch(self): + self.assertIsNone(Config.depuis_env({**ENV, "KILL_SWITCH": "1"})) + for v in ("false", "0", ""): + self.assertIsNotNone(Config.depuis_env({**ENV, "KILL_SWITCH": v}), v) + + def test_plafond_par_defaut(self): + self.assertEqual(Config.depuis_env(ENV).plafond, 3) + + +class TestCycle(unittest.TestCase): + def test_eligible(self): + self.assertTrue(eligible(["tri:diagnostic"])) + self.assertFalse(eligible(["tri:diagnostic", "diag:fait"])) + self.assertTrue(eligible(["tri:diagnostic", "diag:fait", "diag:relancer"])) + self.assertFalse(eligible([])) + self.assertFalse(eligible(["diag:relancer"])) + + def test_plafond_et_liste_blanche(self): + ld = FauxLD({f"c{i}": ["tri:diagnostic"] for i in range(1, 6)}) + self.assertEqual(len(traiter(ld, cfg(), diag_fait)), 3) + ld = FauxLD({f"c{i}": ["tri:diagnostic"] for i in range(1, 6)}) + self.assertEqual(traiter(ld, cfg(ALLOWED_CONVERSATION_IDS="c2"), diag_fait), {"c2": "fait"}) + + def test_conversation_unique(self): + ld = FauxLD({"c1": ["tri:diagnostic"], "c2": ["tri:diagnostic"]}) + self.assertEqual(traiter(ld, cfg(CONVERSATION="c2"), diag_fait), {"c2": "fait"}) + + def test_cycle_fait(self): + ld = FauxLD({"c1": ["tri:diagnostic", "urgent", "diag:fait", "diag:relancer"]}) + self.assertEqual(traiter(ld, cfg(), diag_fait), {"c1": "fait"}) + self.assertEqual(sorted(ld.tags["c1"]), ["diag:fait", "tri:diagnostic", "urgent"]) + (uuid, html), = ld.notes + self.assertTrue(html.startswith(ENTETE)) + self.assertIn("Tout va bien.", html) + + def test_simulation_n_ecrit_rien(self): + ld = FauxLD({"c1": ["tri:diagnostic"]}, ecrire=False) + traiter(ld, Config.depuis_env(ENV), diag_fait) + self.assertEqual((ld.notes, ld.tags["c1"]), ([], ["tri:diagnostic"])) + + def test_mail_vide_ignore(self): + ld = FauxLD({"c1": ["tri:diagnostic"]}) + ld.msgs["c1"] = [msg("incoming", " ")] + appels = [] + self.assertEqual(traiter(ld, cfg(), lambda *a: appels.append(a)), {"c1": "ignore"}) + self.assertEqual(appels, []) + self.assertIn("diag:ignore", ld.tags["c1"]) + self.assertIn("ne contient pas de texte", ld.notes[0][1]) + + def test_erreur_passe_a_la_suivante(self): + ld = FauxLD({"c1": ["tri:diagnostic"], "c2": ["tri:diagnostic"]}) + + def diag(mail, *a): + if "c1" in mail: + raise RuntimeError("agents en panne") + return diag_fait(mail, *a) + self.assertEqual(traiter(ld, cfg(), diag), {"c1": "erreur", "c2": "fait"}) + self.assertEqual(sorted(ld.tags["c1"]), ["diag:erreur", "tri:diagnostic"]) + self.assertIn("RuntimeError", ld.notes[0][1]) + + def test_garde_arrete_tout(self): + ld = FauxLD({"c1": ["tri:diagnostic"], "c2": ["tri:diagnostic"]}, note_leve=Garde("pas privée")) + with self.assertRaises(Garde): + traiter(ld, cfg(), diag_fait) + self.assertEqual(ld.lus, ["c1"]) + self.assertIn("diag:erreur", ld.tags["c1"]) + + def test_relance_ecarte_nos_notes(self): + mail, contexte = fil([ + msg("incoming", "Mes courbes ?", quand="2026-11-09T08:00:00Z"), + msg("outgoing", "BROUILLON IA ancien", private=True, sender=MOI, quand="2026-11-09T09:00:00Z"), + msg("outgoing", "C'est Crissier, station LENZSPITZE", private=True, sender=7, quand="2026-11-09T10:00:00Z"), + msg("activity", "Marc a posé diag:relancer", sender=7, quand="2026-11-09T10:01:00Z"), + ], MOI) + self.assertIn("Mes courbes ?", mail) + self.assertNotIn("BROUILLON", mail + contexte) + self.assertNotIn("LENZSPITZE", mail) + self.assertIn("LENZSPITZE", contexte) + self.assertNotIn("relancer", mail + contexte) + + def test_images_des_messages_entrants(self): + ld = FauxLD({"c1": ["tri:diagnostic"]}) + ld.msgs["c1"][0]["attachments"] = [ + {"content_type": "image/png", "size": 20_000, "url": "/u/1", "name": "capture.png"}, + {"content_type": "image/png", "size": 500, "url": "/u/2", "name": "logo.png"}, + {"content_type": "application/pdf", "size": 90_000, "url": "/u/3", "name": "a.pdf"}] + vus = [] + traiter(ld, cfg(), lambda mail, images, *a: vus.append(images) or diag_fait(mail, images, *a)) + self.assertEqual([t for t, _ in vus[0]], ["image/png"]) + + def test_note_echappe_le_html(self): + html = note(Resultat("fait", "", [Path("/d/figure-1.png")], 1.234, None), "local · abc1234") + self.assertIn("<script>", html) + self.assertNotIn("