06-sep: [fix] opencode_bot sin verbose, texto final + tiempo, sin duplicados entre turnos

This commit is contained in:
juanjo
2026-09-06 20:09:51 +02:00
parent 09e8f1d9c3
commit f6116d1af2

View File

@@ -400,40 +400,30 @@ def procesar_texto(chat, texto):
enviar(chat, f"❌ Error al lanzar OpenCode: {resp}") enviar(chat, f"❌ Error al lanzar OpenCode: {resp}")
return return
vistos_texto = set() # Respuesta SIN verbose: no se envian los comandos/tools intermedios ni
vistos_tool = set() # fragmentos de streaming. Solo se recoge el texto del assistant generado
# en este turno (filtrado por t0 para no repetir mensajes de turnos
# anteriores) y se entrega al terminar junto con el tiempo empleado.
trozos = {} # pid -> (start, texto)
comienzo = time.time() comienzo = time.time()
terminado = False terminado = False
while time.time() - comienzo < 900: while time.time() - comienzo < 900:
time.sleep(3) time.sleep(2)
code, hist = oc_get(f"/session/{sid}/message?limit=4") code, hist = oc_get(f"/session/{sid}/message?limit=10")
if code == 200 and isinstance(hist, list): if code == 200 and isinstance(hist, list):
for item in reversed(hist[-4:]): for item in reversed(hist[-10:]):
info = item.get("info") or {} info = item.get("info") or {}
if info.get("role") != "assistant": if info.get("role") != "assistant":
continue continue
for p in item.get("parts") or []: for p in item.get("parts") or []:
t = p.get("type") if p.get("type") != "text" or not p.get("text"):
pid = p.get("id") or "" continue
if t == "text" and p.get("text") and pid not in vistos_texto: inicio = (p.get("time") or {}).get("start") or 0
vistos_texto.add(pid) if inicio and inicio < t0:
enviar(chat, formatear_html(p["text"])) continue # parte de un turno anterior: ignorar
elif t == "tool" and pid not in vistos_tool: pid = p.get("id") or f"{inicio}-{len(p['text'])}"
vistos_tool.add(pid) if pid not in trozos:
comando = ((p.get("state") or {}).get("input") trozos[pid] = (inicio, p["text"])
or {}).get("command")
if comando:
corto = comando.strip().replace("\n", " ")[:90]
try:
import requests as _rq
_rq.post(f"{API}/sendMessage",
data={"chat_id": chat, "text":
f"⚙️ <i>{html.escape(corto)}</i>",
"parse_mode": "HTML"},
timeout=10)
except Exception:
pass
# fin del turno: la sesion deja de estar busy (tras un margen inicial)
code2, sts = oc_get("/session/status", timeout=10) code2, sts = oc_get("/session/status", timeout=10)
transcurrido = time.time() - comienzo transcurrido = time.time() - comienzo
if (code2 == 200 and isinstance(sts, dict) if (code2 == 200 and isinstance(sts, dict)
@@ -448,6 +438,14 @@ def procesar_texto(chat, texto):
"para cortarla y empezar de nuevo.") "para cortarla y empezar de nuevo.")
return return
# Texto consolidado del turno, ordenado por tiempo de inicio.
texto_final = "\n".join(t for _, t in
sorted(trozos.values(), key=lambda x: x[0]))
if texto_final.strip():
seg = time.time() - comienzo
enviar(chat, formatear_html(texto_final.strip()))
enviar(chat, f"⏱️ Hecho en <b>{seg:.1f}s</b>")
# ficheros tocados en el turno # ficheros tocados en el turno
adjuntos = [] adjuntos = []
try: try: