185 lines
8.3 KiB
Python
185 lines
8.3 KiB
Python
"""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 = "<p><strong>🤖 BROUILLON IA — à relire, ne pas envoyer tel quel</strong></p>"
|
||
|
|
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"<p>{html.escape(p.strip()).replace(chr(10), '<br>')}</p>"
|
||
|
|
for p in texte.split("\n\n") if p.strip())
|
||
|
|
|
||
|
|
|
||
|
|
def note(r, execution: str) -> str:
|
||
|
|
"""La note privée (spec §8, version de départ ; le format est à valider avec l'équipe support)."""
|
||
|
|
titre = "Proposition de réponse au client :" if r.statut == "fait" else "Pas de proposition :"
|
||
|
|
figures = (f"<p><em>Figures préparées (non jointes) : {html.escape(', '.join(p.name for p in r.pieces))}</em></p>"
|
||
|
|
if r.pieces else "")
|
||
|
|
return (f"{ENTETE}<p><em>{titre}</em></p>{_paragraphes(r.texte)}{figures}"
|
||
|
|
f"<hr><p><small>Exécution {html.escape(execution)} · modèle {MODELE} · coût {r.cout:.2f} $</small></p>")
|
||
|
|
|
||
|
|
|
||
|
|
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}<p>Diagnostic en échec : {html.escape(type(e).__name__)}."
|
||
|
|
f"</p><hr><p><small>Exécution {html.escape(execution)}</small></p>"),
|
||
|
|
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())
|