zerochat 10.7.0__tar.gz → 10.9.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {zerochat-10.7.0/zerochat.egg-info → zerochat-10.9.0}/PKG-INFO +1 -1
- {zerochat-10.7.0 → zerochat-10.9.0}/pyproject.toml +1 -1
- {zerochat-10.7.0 → zerochat-10.9.0/zerochat.egg-info}/PKG-INFO +1 -1
- {zerochat-10.7.0 → zerochat-10.9.0}/zerochat.py +127 -17
- {zerochat-10.7.0 → zerochat-10.9.0}/LICENSE +0 -0
- {zerochat-10.7.0 → zerochat-10.9.0}/README.md +0 -0
- {zerochat-10.7.0 → zerochat-10.9.0}/setup.cfg +0 -0
- {zerochat-10.7.0 → zerochat-10.9.0}/zerochat.egg-info/SOURCES.txt +0 -0
- {zerochat-10.7.0 → zerochat-10.9.0}/zerochat.egg-info/dependency_links.txt +0 -0
- {zerochat-10.7.0 → zerochat-10.9.0}/zerochat.egg-info/entry_points.txt +0 -0
- {zerochat-10.7.0 → zerochat-10.9.0}/zerochat.egg-info/top_level.txt +0 -0
|
@@ -54,7 +54,7 @@ import zlib
|
|
|
54
54
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
55
55
|
from pathlib import Path
|
|
56
56
|
|
|
57
|
-
SOURCE_BACKEND_VERSION = "10.
|
|
57
|
+
SOURCE_BACKEND_VERSION = "10.9.0"
|
|
58
58
|
|
|
59
59
|
def _read_source_version(filename: str) -> str | None:
|
|
60
60
|
"""Lee la versión de un archivo del repositorio cuando se ejecuta desde fuentes."""
|
|
@@ -6909,8 +6909,8 @@ def start_server_run(params: dict) -> dict:
|
|
|
6909
6909
|
if tool_security is not None and not isinstance(tool_security, dict):
|
|
6910
6910
|
raise ValueError("tool_security debe ser un objeto o null.")
|
|
6911
6911
|
|
|
6912
|
-
if not
|
|
6913
|
-
raise ValueError("
|
|
6912
|
+
if not find_node_executable():
|
|
6913
|
+
raise ValueError("Node.js 18+ es necesario para ejecutar tareas en segundo plano en el servidor (instala Node.js 18+).")
|
|
6914
6914
|
|
|
6915
6915
|
run_id = secrets.token_urlsafe(24)
|
|
6916
6916
|
cmd = [sys.executable, str(Path(__file__).resolve()), "--conversation", clean_conv_id, "--profile", profile_name]
|
|
@@ -7148,14 +7148,15 @@ def dispatch_run(method: str, params: dict) -> tuple[dict | None, dict | None, s
|
|
|
7148
7148
|
return None, {"code": -32601, "message": f"Método '{method}' no soportado."}, ""
|
|
7149
7149
|
|
|
7150
7150
|
|
|
7151
|
-
def run_supervisor(server: ThreadingHTTPServer, session: RunSession, browser_proc: subprocess.Popen | None = None):
|
|
7152
|
-
"""Detiene el servidor al recibir el resultado, si termina el
|
|
7151
|
+
def run_supervisor(server: ThreadingHTTPServer, session: RunSession, runner_proc: subprocess.Popen | None = None, browser_proc: subprocess.Popen | None = None):
|
|
7152
|
+
"""Detiene el servidor al recibir el resultado, si termina el runner propio o al agotar los plazos."""
|
|
7153
|
+
proc = runner_proc if runner_proc is not None else browser_proc
|
|
7153
7154
|
deadline = time.monotonic() + RUN_TOTAL_TIMEOUT
|
|
7154
7155
|
while not session.finished.wait(RUN_POLL_SECONDS):
|
|
7155
7156
|
# El latido o una señal ya detienen el servidor: el resultado queda vacío.
|
|
7156
7157
|
if _SERVER_SHUTTING_DOWN.is_set():
|
|
7157
7158
|
return
|
|
7158
|
-
if
|
|
7159
|
+
if proc is not None and proc.poll() is not None and not session.finished.wait(0.2):
|
|
7159
7160
|
break
|
|
7160
7161
|
if time.monotonic() >= deadline:
|
|
7161
7162
|
session.stop_reason = f"Plazo total agotado ({RUN_TOTAL_TIMEOUT:.0f}s)."
|
|
@@ -7166,7 +7167,7 @@ def run_supervisor(server: ThreadingHTTPServer, session: RunSession, browser_pro
|
|
|
7166
7167
|
if session.result is None and session.conversation_id:
|
|
7167
7168
|
with session.lock:
|
|
7168
7169
|
session.status = "error"
|
|
7169
|
-
session.error = session.stop_reason or "El
|
|
7170
|
+
session.error = session.stop_reason or ("El runner se cerró sin resultado." if proc else "La ejecución se interrumpió sin resultado.")
|
|
7170
7171
|
write_run_state(session)
|
|
7171
7172
|
stop_zerochat_server(server)
|
|
7172
7173
|
|
|
@@ -7190,7 +7191,7 @@ def run_outcome(session: RunSession) -> tuple[int, str | None]:
|
|
|
7190
7191
|
if session.export_path and not session.exported:
|
|
7191
7192
|
run_error(session.export_error or f"La interfaz no envió la conversación para {session.export_path}.")
|
|
7192
7193
|
if session.result is None:
|
|
7193
|
-
run_error(session.stop_reason or "El
|
|
7194
|
+
run_error(session.stop_reason or session.error or "El runner se cerró o la ejecución se interrumpió sin resultado.")
|
|
7194
7195
|
return RUN_EXIT_TIMEOUT, None
|
|
7195
7196
|
if "error" in session.result:
|
|
7196
7197
|
run_error(f"Error de generación: {session.result['error']}")
|
|
@@ -7213,6 +7214,116 @@ def fall_back_when_headless_exits(proc: subprocess.Popen, url: str):
|
|
|
7213
7214
|
if not HEARTBEAT_INITIALIZED and not _SERVER_SHUTTING_DOWN.is_set():
|
|
7214
7215
|
log_event("El navegador sin ventana terminó sin abrir la interfaz (¿ya estaba abierto?); se abre una pestaña de la forma normal.")
|
|
7215
7216
|
launch_browser(url)
|
|
7217
|
+
|
|
7218
|
+
|
|
7219
|
+
NODE_MINIMUM_MAJOR = 18
|
|
7220
|
+
|
|
7221
|
+
|
|
7222
|
+
def find_node_executable(min_major: int = NODE_MINIMUM_MAJOR) -> str | None:
|
|
7223
|
+
"""Localiza un ejecutable de Node.js en PATH y comprueba su versión mínima."""
|
|
7224
|
+
executable = shutil.which("node")
|
|
7225
|
+
if not executable:
|
|
7226
|
+
return None
|
|
7227
|
+
try:
|
|
7228
|
+
res = subprocess.run([executable, "--version"], capture_output=True, text=True, timeout=5)
|
|
7229
|
+
if res.returncode != 0:
|
|
7230
|
+
return None
|
|
7231
|
+
match = re.search(r"v?(\d+)\.", res.stdout.strip())
|
|
7232
|
+
if not match or int(match.group(1)) < min_major:
|
|
7233
|
+
return None
|
|
7234
|
+
return executable
|
|
7235
|
+
except (OSError, subprocess.SubprocessError):
|
|
7236
|
+
return None
|
|
7237
|
+
|
|
7238
|
+
|
|
7239
|
+
def ensure_runner_script() -> Path:
|
|
7240
|
+
"""
|
|
7241
|
+
Obtiene la ruta al runner de Node.js: en entorno de desarrollo local usa js/run-node.js o runner.js;
|
|
7242
|
+
en producción lo descarga o actualiza desde GitHub Pages con comprobación condicional ETag/304
|
|
7243
|
+
en ~/zerochat/cache/runner.js.
|
|
7244
|
+
"""
|
|
7245
|
+
dev_root = get_dev_root()
|
|
7246
|
+
if dev_root is not None:
|
|
7247
|
+
local_run_node = dev_root / "js" / "run-node.js"
|
|
7248
|
+
if local_run_node.is_file():
|
|
7249
|
+
return local_run_node
|
|
7250
|
+
local_runner = dev_root / "runner.js"
|
|
7251
|
+
if local_runner.is_file():
|
|
7252
|
+
return local_runner
|
|
7253
|
+
|
|
7254
|
+
cache_dir = get_data_dir() / "cache"
|
|
7255
|
+
cache_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
7256
|
+
if os.name != "nt":
|
|
7257
|
+
try:
|
|
7258
|
+
cache_dir.chmod(0o700)
|
|
7259
|
+
except OSError:
|
|
7260
|
+
pass
|
|
7261
|
+
runner_path = cache_dir / "runner.js"
|
|
7262
|
+
etag_path = cache_dir / "runner.etag"
|
|
7263
|
+
|
|
7264
|
+
runner_url = DEFAULT_UI_URL.rsplit("/", 1)[0] + "/runner.js"
|
|
7265
|
+
|
|
7266
|
+
try:
|
|
7267
|
+
req = urllib.request.Request(runner_url, headers={"User-Agent": f"ZeroChat/{VERSION}"})
|
|
7268
|
+
if runner_path.is_file() and etag_path.is_file():
|
|
7269
|
+
try:
|
|
7270
|
+
current_etag = etag_path.read_text(encoding="utf-8").strip()
|
|
7271
|
+
if current_etag:
|
|
7272
|
+
req.add_header("If-None-Match", current_etag)
|
|
7273
|
+
except OSError:
|
|
7274
|
+
pass
|
|
7275
|
+
|
|
7276
|
+
with urllib.request.urlopen(req, timeout=5) as resp:
|
|
7277
|
+
content = resp.read()
|
|
7278
|
+
etag = resp.headers.get("ETag")
|
|
7279
|
+
_write_private_text(runner_path, content.decode("utf-8"))
|
|
7280
|
+
if os.name != "nt":
|
|
7281
|
+
try:
|
|
7282
|
+
runner_path.chmod(0o755)
|
|
7283
|
+
except OSError:
|
|
7284
|
+
pass
|
|
7285
|
+
if etag:
|
|
7286
|
+
_write_private_text(etag_path, etag)
|
|
7287
|
+
except urllib.error.HTTPError as err:
|
|
7288
|
+
if err.code == 304 and runner_path.is_file():
|
|
7289
|
+
pass
|
|
7290
|
+
elif runner_path.is_file():
|
|
7291
|
+
log_event(f"No se pudo comprobar actualización de runner.js ({err}); usando versión en caché.")
|
|
7292
|
+
else:
|
|
7293
|
+
raise RuntimeError(f"Error descargando runner.js desde {runner_url}: {err}") from err
|
|
7294
|
+
except (urllib.error.URLError, TimeoutError, OSError) as err:
|
|
7295
|
+
if runner_path.is_file():
|
|
7296
|
+
log_event(f"No se pudo comprobar actualización de runner.js ({err}); usando versión en caché.")
|
|
7297
|
+
else:
|
|
7298
|
+
raise RuntimeError(f"No se pudo descargar runner.js ({err}) y no hay copia en caché.") from err
|
|
7299
|
+
|
|
7300
|
+
return runner_path
|
|
7301
|
+
|
|
7302
|
+
|
|
7303
|
+
def launch_node_runner(url: str) -> subprocess.Popen | None:
|
|
7304
|
+
"""Abre el runner de Node.js sin ventana en segundo plano."""
|
|
7305
|
+
node = find_node_executable()
|
|
7306
|
+
if not node:
|
|
7307
|
+
run_error("Node.js 18+ es necesario para la ejecución desatendida. Instala Node.js o usa --browser.")
|
|
7308
|
+
return None
|
|
7309
|
+
try:
|
|
7310
|
+
runner_path = ensure_runner_script()
|
|
7311
|
+
except Exception as exc:
|
|
7312
|
+
run_error(f"No se pudo preparar el runner de Node.js: {exc}")
|
|
7313
|
+
return None
|
|
7314
|
+
log_event(f"Iniciando runner de Node.js ({runner_path.name})...")
|
|
7315
|
+
try:
|
|
7316
|
+
return subprocess.Popen(
|
|
7317
|
+
[node, str(runner_path), url],
|
|
7318
|
+
stdin=subprocess.DEVNULL,
|
|
7319
|
+
stdout=subprocess.DEVNULL,
|
|
7320
|
+
stderr=subprocess.DEVNULL,
|
|
7321
|
+
start_new_session=True,
|
|
7322
|
+
)
|
|
7323
|
+
except OSError as error:
|
|
7324
|
+
run_error(f"No se pudo iniciar el proceso de Node.js ({error}).")
|
|
7325
|
+
return None
|
|
7326
|
+
|
|
7216
7327
|
# ==============================================================================
|
|
7217
7328
|
# Punto de Entrada Principal (CLI)
|
|
7218
7329
|
# ==============================================================================
|
|
@@ -7264,7 +7375,7 @@ def build_parser() -> ZeroChatArgumentParser:
|
|
|
7264
7375
|
parser.add_argument("--profile", default=None, help=f"Con --prompt o --conversation, perfil (nombre o id) que se usa solo en esta ejecución, sin cambiar el activo (por defecto: {DEFAULT_RUN_PROFILE} del servidor)")
|
|
7265
7376
|
parser.add_argument("--log", choices=("on", "off"), default=None, help="Mostrar la cabecera y el registro del servidor (default: on; off con --prompt o --conversation)")
|
|
7266
7377
|
parser.add_argument("--export", default=None, metavar="FICHERO", help=f"Con --prompt o --conversation, guardar la conversación en FICHERO; el formato sale de la extensión ({', '.join(RUN_EXPORT_FORMATS)})")
|
|
7267
|
-
parser.add_argument("--browser", action="store_true", help="Con --prompt o --conversation, abrir el navegador predeterminado del usuario en lugar del
|
|
7378
|
+
parser.add_argument("--browser", action="store_true", help="Con --prompt o --conversation, abrir el navegador predeterminado del usuario en lugar del proceso Node.js sin ventana")
|
|
7268
7379
|
parser.add_argument("--keep-page", action="store_true", help="Página: con --browser, no cerrar la página al terminar para ver la conversación (no se combina con --headless)")
|
|
7269
7380
|
parser.add_argument("--allow-dangerous-tools", action="store_true", help="Con --prompt o --conversation, aprobar también las herramientas que escriben o ejecutan (write_file, edit_file, run_command); las demás se aprueban siempre para la sesión")
|
|
7270
7381
|
parser.add_argument("--headless", action="store_true", help="Con --browser, abrir el navegador predeterminado sin ventana (si ya está abierto puede verse la pestaña)")
|
|
@@ -7302,11 +7413,11 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
|
|
|
7302
7413
|
if not has_user_or_tool:
|
|
7303
7414
|
parser.error(f"la conversación '{conversation_id}' no tiene turnos para continuar")
|
|
7304
7415
|
if args.no_browser:
|
|
7305
|
-
parser.error("--prompt y --conversation
|
|
7416
|
+
parser.error("--prompt y --conversation ejecutan la interfaz de forma autónoma: no se combina con --no-browser")
|
|
7306
7417
|
if args.keep_server:
|
|
7307
7418
|
parser.error("--prompt y --conversation terminan al devolver el resultado: no se combina con --keep-server (para no cerrar la página, --keep-page)")
|
|
7308
7419
|
if args.headless and not args.browser:
|
|
7309
|
-
parser.error("--headless solo se usa con --browser (--prompt y --conversation ya se ejecutan sin ventana con
|
|
7420
|
+
parser.error("--headless solo se usa con --browser (--prompt y --conversation ya se ejecutan sin ventana con Node.js)")
|
|
7310
7421
|
if args.keep_page and (not args.browser or args.headless):
|
|
7311
7422
|
parser.error("--keep-page necesita la ventana del navegador del usuario (--browser sin --headless)")
|
|
7312
7423
|
profile_data = None
|
|
@@ -7479,14 +7590,13 @@ def start_interface(args, parser, server: ThreadingHTTPServer, ui_url: str, resu
|
|
|
7479
7590
|
return None
|
|
7480
7591
|
target_url = launch_url(ui_url)
|
|
7481
7592
|
if not args.browser:
|
|
7482
|
-
|
|
7483
|
-
if
|
|
7484
|
-
run_error("No se pudo abrir el Chromium de Playwright (instálalo desde Ajustes › Navegador o usa --browser).")
|
|
7593
|
+
runner_proc = launch_node_runner(target_url)
|
|
7594
|
+
if runner_proc is None:
|
|
7485
7595
|
server.server_close()
|
|
7486
7596
|
sys.stdout = result_out
|
|
7487
7597
|
sys.exit(RUN_EXIT_SETUP)
|
|
7488
|
-
threading.Thread(target=run_supervisor, args=(server, RUN_SESSION,
|
|
7489
|
-
return
|
|
7598
|
+
threading.Thread(target=run_supervisor, args=(server, RUN_SESSION, runner_proc), daemon=True).start()
|
|
7599
|
+
return runner_proc
|
|
7490
7600
|
headless_browser = launch_headless_browser(target_url) if args.headless else None
|
|
7491
7601
|
if headless_browser is None and not launch_browser(target_url):
|
|
7492
7602
|
run_error("No se pudo abrir el navegador.")
|
|
@@ -7495,7 +7605,7 @@ def start_interface(args, parser, server: ThreadingHTTPServer, ui_url: str, resu
|
|
|
7495
7605
|
sys.exit(RUN_EXIT_SETUP)
|
|
7496
7606
|
if headless_browser is not None:
|
|
7497
7607
|
threading.Thread(target=fall_back_when_headless_exits, args=(headless_browser, target_url), daemon=True).start()
|
|
7498
|
-
threading.Thread(target=run_supervisor, args=(server, RUN_SESSION), daemon=True).start()
|
|
7608
|
+
threading.Thread(target=run_supervisor, args=(server, RUN_SESSION, None, headless_browser), daemon=True).start()
|
|
7499
7609
|
return headless_browser
|
|
7500
7610
|
|
|
7501
7611
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|