zerochat 10.2.0__tar.gz → 10.4.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.
Potentially problematic release.
This version of zerochat might be problematic. Click here for more details.
- {zerochat-10.2.0/zerochat.egg-info → zerochat-10.4.0}/PKG-INFO +1 -1
- {zerochat-10.2.0 → zerochat-10.4.0}/pyproject.toml +1 -1
- {zerochat-10.2.0 → zerochat-10.4.0/zerochat.egg-info}/PKG-INFO +1 -1
- {zerochat-10.2.0 → zerochat-10.4.0}/zerochat.py +97 -19
- {zerochat-10.2.0 → zerochat-10.4.0}/LICENSE +0 -0
- {zerochat-10.2.0 → zerochat-10.4.0}/README.md +0 -0
- {zerochat-10.2.0 → zerochat-10.4.0}/setup.cfg +0 -0
- {zerochat-10.2.0 → zerochat-10.4.0}/zerochat.egg-info/SOURCES.txt +0 -0
- {zerochat-10.2.0 → zerochat-10.4.0}/zerochat.egg-info/dependency_links.txt +0 -0
- {zerochat-10.2.0 → zerochat-10.4.0}/zerochat.egg-info/entry_points.txt +0 -0
- {zerochat-10.2.0 → zerochat-10.4.0}/zerochat.egg-info/top_level.txt +0 -0
|
@@ -30,6 +30,7 @@ import json
|
|
|
30
30
|
import math
|
|
31
31
|
import os
|
|
32
32
|
import queue
|
|
33
|
+
import random
|
|
33
34
|
import re
|
|
34
35
|
import secrets
|
|
35
36
|
import shutil
|
|
@@ -53,7 +54,7 @@ import zlib
|
|
|
53
54
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
54
55
|
from pathlib import Path
|
|
55
56
|
|
|
56
|
-
SOURCE_BACKEND_VERSION = "10.
|
|
57
|
+
SOURCE_BACKEND_VERSION = "10.4.0"
|
|
57
58
|
|
|
58
59
|
def _read_source_version(filename: str) -> str | None:
|
|
59
60
|
"""Lee la versión de un archivo del repositorio cuando se ejecuta desde fuentes."""
|
|
@@ -3597,7 +3598,7 @@ def validate_profile_payload(record: dict) -> tuple[str, str, str, dict, str | N
|
|
|
3597
3598
|
|
|
3598
3599
|
|
|
3599
3600
|
def _row_to_profile(row: sqlite3.Row) -> dict:
|
|
3600
|
-
"""Transforma una fila SQLite en el objeto de perfil
|
|
3601
|
+
"""Transforma una fila SQLite en el objeto de perfil del servidor."""
|
|
3601
3602
|
try:
|
|
3602
3603
|
settings = json.loads(row["settings_json"])
|
|
3603
3604
|
except (json.JSONDecodeError, TypeError):
|
|
@@ -3618,14 +3619,14 @@ def _row_to_profile(row: sqlite3.Row) -> dict:
|
|
|
3618
3619
|
|
|
3619
3620
|
|
|
3620
3621
|
def list_general_profiles() -> list[dict]:
|
|
3621
|
-
"""Lista todos los perfiles de conexión
|
|
3622
|
+
"""Lista todos los perfiles de conexión del servidor almacenados en SQLite."""
|
|
3622
3623
|
with open_storage() as conn:
|
|
3623
3624
|
rows = conn.execute("SELECT * FROM profiles ORDER BY name COLLATE NOCASE ASC;").fetchall()
|
|
3624
3625
|
return [_row_to_profile(row) for row in rows]
|
|
3625
3626
|
|
|
3626
3627
|
|
|
3627
3628
|
def get_general_profile(profile_id: str) -> dict | None:
|
|
3628
|
-
"""Recupera un perfil
|
|
3629
|
+
"""Recupera un perfil de servidor por su identificador único."""
|
|
3629
3630
|
if not profile_id or not isinstance(profile_id, str) or not profile_id.strip():
|
|
3630
3631
|
return None
|
|
3631
3632
|
clean_id = normalize_profile_id("", profile_id)
|
|
@@ -3635,7 +3636,7 @@ def get_general_profile(profile_id: str) -> dict | None:
|
|
|
3635
3636
|
|
|
3636
3637
|
|
|
3637
3638
|
def get_general_profile_by_name(name: str) -> dict | None:
|
|
3638
|
-
"""Recupera un perfil
|
|
3639
|
+
"""Recupera un perfil de servidor por su nombre."""
|
|
3639
3640
|
if not name or not isinstance(name, str) or not name.strip():
|
|
3640
3641
|
return None
|
|
3641
3642
|
clean = name.strip()
|
|
@@ -3650,7 +3651,7 @@ def get_general_profile_by_name(name: str) -> dict | None:
|
|
|
3650
3651
|
|
|
3651
3652
|
|
|
3652
3653
|
def save_general_profile(record: dict) -> dict:
|
|
3653
|
-
"""Guarda (crea o actualiza) un perfil de conexión
|
|
3654
|
+
"""Guarda (crea o actualiza) un perfil de conexión del servidor en SQLite."""
|
|
3654
3655
|
profile_id, name, description, settings, api_key = validate_profile_payload(record)
|
|
3655
3656
|
now = int(time.time() * 1000)
|
|
3656
3657
|
|
|
@@ -3669,7 +3670,7 @@ def save_general_profile(record: dict) -> dict:
|
|
|
3669
3670
|
(name, profile_id)
|
|
3670
3671
|
).fetchone()
|
|
3671
3672
|
if same_name:
|
|
3672
|
-
raise ValueError(f"Ya existe un perfil
|
|
3673
|
+
raise ValueError(f"Ya existe un perfil con el nombre '{name}' en el servidor")
|
|
3673
3674
|
|
|
3674
3675
|
if existing:
|
|
3675
3676
|
version = existing["version"] + 1
|
|
@@ -3740,6 +3741,8 @@ def _row_to_conversation_header(row: sqlite3.Row) -> dict:
|
|
|
3740
3741
|
header["extra"] = extra
|
|
3741
3742
|
if "profile_id" in extra:
|
|
3742
3743
|
header["profileId"] = extra["profile_id"]
|
|
3744
|
+
if "server_run" in extra:
|
|
3745
|
+
header["serverRun"] = bool(extra["server_run"])
|
|
3743
3746
|
return header
|
|
3744
3747
|
|
|
3745
3748
|
|
|
@@ -3801,6 +3804,8 @@ def save_conversation(session_meta: dict, messages: list[dict] | None = None) ->
|
|
|
3801
3804
|
profile_id = session_meta.get("profileId")
|
|
3802
3805
|
if profile_id and isinstance(profile_id, str) and profile_id.strip():
|
|
3803
3806
|
extra["profile_id"] = profile_id.strip()
|
|
3807
|
+
if session_meta.get("serverRun") is not None:
|
|
3808
|
+
extra["server_run"] = bool(session_meta.get("serverRun"))
|
|
3804
3809
|
|
|
3805
3810
|
extra_json = json.dumps(extra, ensure_ascii=False) if extra else "{}"
|
|
3806
3811
|
|
|
@@ -3836,6 +3841,28 @@ def save_conversation(session_meta: dict, messages: list[dict] | None = None) ->
|
|
|
3836
3841
|
return _row_to_conversation_header(row)
|
|
3837
3842
|
|
|
3838
3843
|
|
|
3844
|
+
def mark_conversation_server_run(session_id: str, profile_name: str | None = None) -> bool:
|
|
3845
|
+
"""Marca la conversación en SQLite como ejecutada en servidor asociándole el perfil."""
|
|
3846
|
+
try:
|
|
3847
|
+
clean_id = _validate_conversation_id(session_id)
|
|
3848
|
+
except (ValueError, TypeError):
|
|
3849
|
+
return False
|
|
3850
|
+
try:
|
|
3851
|
+
with open_storage() as conn:
|
|
3852
|
+
row = conn.execute("SELECT extra_json FROM conversations WHERE id = ?;", (clean_id,)).fetchone()
|
|
3853
|
+
if not row:
|
|
3854
|
+
return False
|
|
3855
|
+
cur_extra = json.loads(row["extra_json"]) if row["extra_json"] else {}
|
|
3856
|
+
cur_extra["server_run"] = True
|
|
3857
|
+
if profile_name:
|
|
3858
|
+
cur_extra["profile_id"] = str(profile_name).strip()
|
|
3859
|
+
conn.execute("UPDATE conversations SET extra_json = ? WHERE id = ?;", (json.dumps(cur_extra, ensure_ascii=False), clean_id))
|
|
3860
|
+
conn.commit()
|
|
3861
|
+
return True
|
|
3862
|
+
except (sqlite3.Error, OSError, json.JSONDecodeError):
|
|
3863
|
+
return False
|
|
3864
|
+
|
|
3865
|
+
|
|
3839
3866
|
def rename_conversation(session_id: str, new_title: str) -> bool:
|
|
3840
3867
|
"""Renombra una conversación existente en SQLite."""
|
|
3841
3868
|
clean_id = _validate_conversation_id(session_id)
|
|
@@ -4057,6 +4084,13 @@ WEB_FETCH_READ_CHUNK = 64 * 1024
|
|
|
4057
4084
|
TEXT_CONTENT_TYPE_RE = re.compile(
|
|
4058
4085
|
r"^(text/|application/(json|xml|xhtml\+xml|javascript|x-javascript|ecmascript)$|[a-z]+/[^;]*\+(json|xml)$)"
|
|
4059
4086
|
)
|
|
4087
|
+
# Control de cadencia entre peticiones consecutivas al mismo host (mitigación de retos anti-bot).
|
|
4088
|
+
_WEB_FETCH_LOCK = threading.Lock()
|
|
4089
|
+
_LAST_WEB_FETCH_AT: dict[str, float] = {}
|
|
4090
|
+
WEB_FETCH_HOST_PACING_DOMAINS = ("duckduckgo.com",)
|
|
4091
|
+
WEB_FETCH_MIN_DELAY_S = 0.6
|
|
4092
|
+
WEB_FETCH_MAX_DELAY_S = 1.2
|
|
4093
|
+
|
|
4060
4094
|
|
|
4061
4095
|
|
|
4062
4096
|
def _is_public_ip(address: str) -> bool:
|
|
@@ -4137,15 +4171,40 @@ def fetch_web_resource(params: dict) -> dict:
|
|
|
4137
4171
|
raise ValueError("URL no válida o ausente.")
|
|
4138
4172
|
url = _validate_web_url(url.strip())
|
|
4139
4173
|
|
|
4174
|
+
parsed = urllib.parse.urlsplit(url)
|
|
4175
|
+
hostname = (parsed.hostname or "").lower()
|
|
4176
|
+
|
|
4177
|
+
# Si se repite una consulta a un host sensible (ej. DuckDuckGo), aplicar un retardo mínimo aleatorio.
|
|
4178
|
+
if any(hostname == domain or hostname.endswith("." + domain) for domain in WEB_FETCH_HOST_PACING_DOMAINS):
|
|
4179
|
+
with _WEB_FETCH_LOCK:
|
|
4180
|
+
now = time.monotonic()
|
|
4181
|
+
last_call = _LAST_WEB_FETCH_AT.get(hostname, 0.0)
|
|
4182
|
+
required_gap = random.uniform(WEB_FETCH_MIN_DELAY_S, WEB_FETCH_MAX_DELAY_S)
|
|
4183
|
+
sleep_needed = max(0.0, (last_call + required_gap) - now)
|
|
4184
|
+
_LAST_WEB_FETCH_AT[hostname] = now + sleep_needed
|
|
4185
|
+
if sleep_needed > 0:
|
|
4186
|
+
time.sleep(sleep_needed)
|
|
4187
|
+
|
|
4140
4188
|
timeout_s = max(0.5, min(float(params.get("timeout_s", 10.0)), 30.0))
|
|
4141
4189
|
max_bytes = max(1024, min(int(params.get("max_bytes", 2 * 1024 * 1024)), WEB_FETCH_MAX_BYTES))
|
|
4142
4190
|
as_binary = bool(params.get("binary", False))
|
|
4143
4191
|
accept = params.get("accept")
|
|
4144
4192
|
req_headers = {
|
|
4145
4193
|
"User-Agent": DEFAULT_USER_AGENT,
|
|
4146
|
-
"Accept": accept if isinstance(accept, str) and accept else "
|
|
4194
|
+
"Accept": accept if isinstance(accept, str) and accept else "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
|
4195
|
+
"Accept-Language": "es-ES,es;q=0.9,en;q=0.8",
|
|
4147
4196
|
"Accept-Encoding": "gzip, deflate",
|
|
4197
|
+
"Sec-Ch-Ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
|
|
4198
|
+
"Sec-Ch-Ua-Mobile": "?0",
|
|
4199
|
+
"Sec-Ch-Ua-Platform": '"Windows"',
|
|
4200
|
+
"Sec-Fetch-Dest": "document",
|
|
4201
|
+
"Sec-Fetch-Mode": "navigate",
|
|
4202
|
+
"Sec-Fetch-Site": "none",
|
|
4203
|
+
"Sec-Fetch-User": "?1",
|
|
4204
|
+
"Upgrade-Insecure-Requests": "1",
|
|
4148
4205
|
}
|
|
4206
|
+
if hostname.endswith("duckduckgo.com"):
|
|
4207
|
+
req_headers["Referer"] = f"{parsed.scheme}://{parsed.netloc}/"
|
|
4149
4208
|
|
|
4150
4209
|
req = urllib.request.Request(url, headers=req_headers)
|
|
4151
4210
|
try:
|
|
@@ -4154,6 +4213,14 @@ def fetch_web_resource(params: dict) -> dict:
|
|
|
4154
4213
|
raw_data, truncated = _read_limited_body(resp, resp.headers.get("Content-Encoding", ""), max_bytes)
|
|
4155
4214
|
# Las cabeceras de transporte ya no describen el cuerpo descomprimido.
|
|
4156
4215
|
resp_headers = {k: v for k, v in resp.getheaders() if k.lower() not in ("content-encoding", "content-length")}
|
|
4216
|
+
# Respuestas 202 u otros retos anti-bot se marcan como error no exitoso.
|
|
4217
|
+
if resp.status == 202:
|
|
4218
|
+
return {
|
|
4219
|
+
"ok": False,
|
|
4220
|
+
"status": resp.status,
|
|
4221
|
+
"error": "HTTP 202: Reto anti-bot o verificación de anomalía detectada por el servidor remoto.",
|
|
4222
|
+
"text": raw_data.decode("utf-8", errors="replace")
|
|
4223
|
+
}
|
|
4157
4224
|
result = {
|
|
4158
4225
|
"ok": True,
|
|
4159
4226
|
"status": resp.status,
|
|
@@ -5164,8 +5231,8 @@ RUN_EXIT_TIMEOUT = 2
|
|
|
5164
5231
|
RUN_EXIT_SETUP = 3
|
|
5165
5232
|
# Argumentos no válidos, en cualquier modo: argparse usaría 2, que con --prompt es plazo agotado.
|
|
5166
5233
|
RUN_EXIT_ARGS = 4
|
|
5167
|
-
# Perfil
|
|
5168
|
-
DEFAULT_RUN_PROFILE = "
|
|
5234
|
+
# Perfil por defecto de --prompt cuando no se indica --profile.
|
|
5235
|
+
DEFAULT_RUN_PROFILE = "local"
|
|
5169
5236
|
# Formato de --export según la extensión del fichero; la interfaz genera el contenido con ChatExport.
|
|
5170
5237
|
RUN_EXPORT_FORMATS = {".md": "markdown", ".json": "json", ".html": "html"}
|
|
5171
5238
|
# Cuerpo HTTP admitido mientras se espera la exportación: el JSON y el HTML llevan las imágenes incrustadas.
|
|
@@ -5349,7 +5416,7 @@ def start_server_run(params: dict) -> dict:
|
|
|
5349
5416
|
raise ValueError("profile requerido.")
|
|
5350
5417
|
profile_entry = get_general_profile(profile) or get_general_profile_by_name(profile)
|
|
5351
5418
|
if not profile_entry:
|
|
5352
|
-
raise ValueError(f"Perfil
|
|
5419
|
+
raise ValueError(f"Perfil del servidor '{profile}' no encontrado.")
|
|
5353
5420
|
profile_name = profile_entry.get("name", profile.strip())
|
|
5354
5421
|
|
|
5355
5422
|
state_path = get_run_state_path(clean_conv_id)
|
|
@@ -5383,6 +5450,8 @@ def start_server_run(params: dict) -> dict:
|
|
|
5383
5450
|
env["ZEROCHAT_RUN_SECURITY"] = json.dumps(tool_security, ensure_ascii=False)
|
|
5384
5451
|
|
|
5385
5452
|
now = int(time.time() * 1000)
|
|
5453
|
+
mark_conversation_server_run(clean_conv_id, profile_name)
|
|
5454
|
+
|
|
5386
5455
|
proc = subprocess.Popen(
|
|
5387
5456
|
cmd,
|
|
5388
5457
|
stdin=subprocess.DEVNULL,
|
|
@@ -5432,13 +5501,14 @@ class RunSession:
|
|
|
5432
5501
|
"""Estado de la ejecución: prompt, opciones, último progreso, exportación, resultado y motivo de un final sin él."""
|
|
5433
5502
|
def __init__(self, prompt: str | None = None, profile: str | None = None, export_path: Path | None = None, keep_page: bool = False,
|
|
5434
5503
|
allow_dangerous_tools: bool = False, conversation_id: str | None = None, run_id: str | None = None,
|
|
5435
|
-
tool_security: dict | None = None):
|
|
5504
|
+
tool_security: dict | None = None, profile_data: dict | None = None):
|
|
5436
5505
|
env_run_id = os.environ.get("ZEROCHAT_RUN_ID", "").strip()
|
|
5437
5506
|
self.run_id = run_id.strip() if (run_id and isinstance(run_id, str) and run_id.strip()) else (env_run_id or secrets.token_urlsafe(24))
|
|
5438
5507
|
self.conversation_id = conversation_id
|
|
5439
5508
|
self.prompt = prompt
|
|
5440
|
-
# Perfil (nombre o id) que la interfaz usa solo en esta ejecución; por defecto,
|
|
5509
|
+
# Perfil (nombre o id) que la interfaz usa solo en esta ejecución; por defecto, local del servidor.
|
|
5441
5510
|
self.profile = profile
|
|
5511
|
+
self.profile_data = profile_data
|
|
5442
5512
|
# Fichero donde se escribe la conversación exportada (formato por su extensión); None, sin exportar.
|
|
5443
5513
|
self.export_path = export_path
|
|
5444
5514
|
self.exported = False
|
|
@@ -5533,6 +5603,7 @@ def dispatch_run(method: str, params: dict) -> tuple[dict | None, dict | None, s
|
|
|
5533
5603
|
session.touch()
|
|
5534
5604
|
export_format = RUN_EXPORT_FORMATS[session.export_path.suffix.lower()] if session.export_path else None
|
|
5535
5605
|
return {"prompt": session.prompt, "conversation_id": session.conversation_id, "profile": session.profile,
|
|
5606
|
+
"profile_data": session.profile_data,
|
|
5536
5607
|
"export": export_format, "keep_page": session.keep_page,
|
|
5537
5608
|
"allow_dangerous_tools": session.allow_dangerous_tools, "tool_security": session.tool_security}, None, ""
|
|
5538
5609
|
if method == "zerochat/run/progress":
|
|
@@ -5765,29 +5836,34 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
|
|
|
5765
5836
|
parser.error("--headless solo se usa con --browser (--prompt y --conversation ya se ejecutan sin ventana con el Chromium de Playwright)")
|
|
5766
5837
|
if args.keep_page and (not args.browser or args.headless):
|
|
5767
5838
|
parser.error("--keep-page necesita la ventana del navegador del usuario (--browser sin --headless)")
|
|
5839
|
+
profile_data = None
|
|
5768
5840
|
if args.profile is not None:
|
|
5769
5841
|
clean_profile = args.profile.strip()
|
|
5770
5842
|
if not clean_profile:
|
|
5771
5843
|
parser.error("--profile no puede estar vacío")
|
|
5772
5844
|
general_match = get_general_profile_by_name(clean_profile) or get_general_profile(clean_profile)
|
|
5773
5845
|
profile_name = general_match["name"] if general_match else clean_profile
|
|
5846
|
+
profile_data = general_match
|
|
5774
5847
|
elif conversation_id:
|
|
5775
5848
|
conv_profile = conv.get("profileId") if conv else None
|
|
5776
5849
|
if conv_profile:
|
|
5777
5850
|
match = get_general_profile_by_name(conv_profile) or get_general_profile(conv_profile)
|
|
5778
5851
|
if not match:
|
|
5779
|
-
parser.error(f"no existe el perfil
|
|
5852
|
+
parser.error(f"no existe el perfil '{conv_profile}' en el servidor; créalo o indica uno con --profile")
|
|
5780
5853
|
profile_name = match["name"]
|
|
5854
|
+
profile_data = match
|
|
5781
5855
|
else:
|
|
5782
5856
|
default_match = get_general_profile_by_name(DEFAULT_RUN_PROFILE)
|
|
5783
5857
|
if default_match is None:
|
|
5784
|
-
parser.error(f"no existe el perfil
|
|
5858
|
+
parser.error(f"no existe el perfil por defecto '{DEFAULT_RUN_PROFILE}' en el servidor; créalo o indica uno con --profile")
|
|
5785
5859
|
profile_name = default_match["name"]
|
|
5860
|
+
profile_data = default_match
|
|
5786
5861
|
else:
|
|
5787
5862
|
default_match = get_general_profile_by_name(DEFAULT_RUN_PROFILE)
|
|
5788
5863
|
if default_match is None:
|
|
5789
|
-
parser.error(f"no existe el perfil
|
|
5864
|
+
parser.error(f"no existe el perfil por defecto '{DEFAULT_RUN_PROFILE}' en el servidor; créalo o indica uno con --profile")
|
|
5790
5865
|
profile_name = default_match["name"]
|
|
5866
|
+
profile_data = default_match
|
|
5791
5867
|
export_path = None
|
|
5792
5868
|
if args.export is not None:
|
|
5793
5869
|
export_path = Path(args.export).expanduser().absolute()
|
|
@@ -5795,7 +5871,9 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
|
|
|
5795
5871
|
parser.error(f"--export necesita una de estas extensiones: {', '.join(RUN_EXPORT_FORMATS)}")
|
|
5796
5872
|
if not export_path.parent.is_dir():
|
|
5797
5873
|
parser.error(f"--export: no existe el directorio {export_path.parent}")
|
|
5798
|
-
|
|
5874
|
+
if conversation_id:
|
|
5875
|
+
mark_conversation_server_run(conversation_id, profile_name)
|
|
5876
|
+
return RunSession(prompt, profile_name, export_path, args.keep_page, args.allow_dangerous_tools, conversation_id=conversation_id, profile_data=profile_data)
|
|
5799
5877
|
|
|
5800
5878
|
|
|
5801
5879
|
def redirect_log(args):
|
|
@@ -6008,9 +6086,9 @@ def main():
|
|
|
6008
6086
|
if getattr(args, "list_profiles", False):
|
|
6009
6087
|
profiles = list_general_profiles()
|
|
6010
6088
|
if not profiles:
|
|
6011
|
-
print("No hay perfiles de conexión
|
|
6089
|
+
print("No hay perfiles de conexión almacenados en el servidor local.")
|
|
6012
6090
|
else:
|
|
6013
|
-
print("Perfiles de conexión
|
|
6091
|
+
print("Perfiles de conexión del servidor local:")
|
|
6014
6092
|
for p in profiles:
|
|
6015
6093
|
settings = p.get("settings", {})
|
|
6016
6094
|
model = settings.get("model") or "sin modelo"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|