zerochat 10.1.0__tar.gz → 10.3.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.1.0/zerochat.egg-info → zerochat-10.3.0}/PKG-INFO +1 -1
- {zerochat-10.1.0 → zerochat-10.3.0}/pyproject.toml +1 -1
- {zerochat-10.1.0 → zerochat-10.3.0/zerochat.egg-info}/PKG-INFO +1 -1
- {zerochat-10.1.0 → zerochat-10.3.0}/zerochat.py +100 -23
- {zerochat-10.1.0 → zerochat-10.3.0}/LICENSE +0 -0
- {zerochat-10.1.0 → zerochat-10.3.0}/README.md +0 -0
- {zerochat-10.1.0 → zerochat-10.3.0}/setup.cfg +0 -0
- {zerochat-10.1.0 → zerochat-10.3.0}/zerochat.egg-info/SOURCES.txt +0 -0
- {zerochat-10.1.0 → zerochat-10.3.0}/zerochat.egg-info/dependency_links.txt +0 -0
- {zerochat-10.1.0 → zerochat-10.3.0}/zerochat.egg-info/entry_points.txt +0 -0
- {zerochat-10.1.0 → zerochat-10.3.0}/zerochat.egg-info/top_level.txt +0 -0
|
@@ -53,7 +53,7 @@ import zlib
|
|
|
53
53
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
54
54
|
from pathlib import Path
|
|
55
55
|
|
|
56
|
-
SOURCE_BACKEND_VERSION = "10.
|
|
56
|
+
SOURCE_BACKEND_VERSION = "10.3.0"
|
|
57
57
|
|
|
58
58
|
def _read_source_version(filename: str) -> str | None:
|
|
59
59
|
"""Lee la versión de un archivo del repositorio cuando se ejecuta desde fuentes."""
|
|
@@ -3481,6 +3481,9 @@ STORAGE_MIGRATIONS = [
|
|
|
3481
3481
|
created_at INTEGER NOT NULL
|
|
3482
3482
|
);
|
|
3483
3483
|
CREATE INDEX IF NOT EXISTS idx_blobs_created_at ON blobs(created_at);
|
|
3484
|
+
"""),
|
|
3485
|
+
(4, "004_add_extra_json_to_conversations", """
|
|
3486
|
+
ALTER TABLE conversations ADD COLUMN extra_json TEXT DEFAULT '{}';
|
|
3484
3487
|
""")
|
|
3485
3488
|
]
|
|
3486
3489
|
|
|
@@ -3594,7 +3597,7 @@ def validate_profile_payload(record: dict) -> tuple[str, str, str, dict, str | N
|
|
|
3594
3597
|
|
|
3595
3598
|
|
|
3596
3599
|
def _row_to_profile(row: sqlite3.Row) -> dict:
|
|
3597
|
-
"""Transforma una fila SQLite en el objeto de perfil
|
|
3600
|
+
"""Transforma una fila SQLite en el objeto de perfil del servidor."""
|
|
3598
3601
|
try:
|
|
3599
3602
|
settings = json.loads(row["settings_json"])
|
|
3600
3603
|
except (json.JSONDecodeError, TypeError):
|
|
@@ -3615,14 +3618,14 @@ def _row_to_profile(row: sqlite3.Row) -> dict:
|
|
|
3615
3618
|
|
|
3616
3619
|
|
|
3617
3620
|
def list_general_profiles() -> list[dict]:
|
|
3618
|
-
"""Lista todos los perfiles de conexión
|
|
3621
|
+
"""Lista todos los perfiles de conexión del servidor almacenados en SQLite."""
|
|
3619
3622
|
with open_storage() as conn:
|
|
3620
3623
|
rows = conn.execute("SELECT * FROM profiles ORDER BY name COLLATE NOCASE ASC;").fetchall()
|
|
3621
3624
|
return [_row_to_profile(row) for row in rows]
|
|
3622
3625
|
|
|
3623
3626
|
|
|
3624
3627
|
def get_general_profile(profile_id: str) -> dict | None:
|
|
3625
|
-
"""Recupera un perfil
|
|
3628
|
+
"""Recupera un perfil de servidor por su identificador único."""
|
|
3626
3629
|
if not profile_id or not isinstance(profile_id, str) or not profile_id.strip():
|
|
3627
3630
|
return None
|
|
3628
3631
|
clean_id = normalize_profile_id("", profile_id)
|
|
@@ -3632,7 +3635,7 @@ def get_general_profile(profile_id: str) -> dict | None:
|
|
|
3632
3635
|
|
|
3633
3636
|
|
|
3634
3637
|
def get_general_profile_by_name(name: str) -> dict | None:
|
|
3635
|
-
"""Recupera un perfil
|
|
3638
|
+
"""Recupera un perfil de servidor por su nombre."""
|
|
3636
3639
|
if not name or not isinstance(name, str) or not name.strip():
|
|
3637
3640
|
return None
|
|
3638
3641
|
clean = name.strip()
|
|
@@ -3647,7 +3650,7 @@ def get_general_profile_by_name(name: str) -> dict | None:
|
|
|
3647
3650
|
|
|
3648
3651
|
|
|
3649
3652
|
def save_general_profile(record: dict) -> dict:
|
|
3650
|
-
"""Guarda (crea o actualiza) un perfil de conexión
|
|
3653
|
+
"""Guarda (crea o actualiza) un perfil de conexión del servidor en SQLite."""
|
|
3651
3654
|
profile_id, name, description, settings, api_key = validate_profile_payload(record)
|
|
3652
3655
|
now = int(time.time() * 1000)
|
|
3653
3656
|
|
|
@@ -3666,7 +3669,7 @@ def save_general_profile(record: dict) -> dict:
|
|
|
3666
3669
|
(name, profile_id)
|
|
3667
3670
|
).fetchone()
|
|
3668
3671
|
if same_name:
|
|
3669
|
-
raise ValueError(f"Ya existe un perfil
|
|
3672
|
+
raise ValueError(f"Ya existe un perfil con el nombre '{name}' en el servidor")
|
|
3670
3673
|
|
|
3671
3674
|
if existing:
|
|
3672
3675
|
version = existing["version"] + 1
|
|
@@ -3724,13 +3727,22 @@ def _validate_conversation_title(title, allow_empty: bool = False) -> str:
|
|
|
3724
3727
|
|
|
3725
3728
|
def _row_to_conversation_header(row: sqlite3.Row) -> dict:
|
|
3726
3729
|
"""Transforma una fila SQLite en la cabecera de una conversación."""
|
|
3727
|
-
|
|
3730
|
+
header = {
|
|
3728
3731
|
"id": row["id"],
|
|
3729
3732
|
"title": row["title"],
|
|
3730
3733
|
"createdAt": row["created_at"],
|
|
3731
3734
|
"updatedAt": row["updated_at"],
|
|
3732
3735
|
"messageCount": row["message_count"]
|
|
3733
3736
|
}
|
|
3737
|
+
raw_extra = row["extra_json"]
|
|
3738
|
+
extra = json.loads(raw_extra) if raw_extra else {}
|
|
3739
|
+
if extra:
|
|
3740
|
+
header["extra"] = extra
|
|
3741
|
+
if "profile_id" in extra:
|
|
3742
|
+
header["profileId"] = extra["profile_id"]
|
|
3743
|
+
if "server_run" in extra:
|
|
3744
|
+
header["serverRun"] = bool(extra["server_run"])
|
|
3745
|
+
return header
|
|
3734
3746
|
|
|
3735
3747
|
|
|
3736
3748
|
def _row_to_message(row: sqlite3.Row) -> dict:
|
|
@@ -3783,15 +3795,29 @@ def save_conversation(session_meta: dict, messages: list[dict] | None = None) ->
|
|
|
3783
3795
|
created_at = int(session_meta.get("createdAt") or now)
|
|
3784
3796
|
updated_at = int(session_meta.get("updatedAt") or now)
|
|
3785
3797
|
|
|
3798
|
+
extra = session_meta.get("extra")
|
|
3799
|
+
if not isinstance(extra, dict):
|
|
3800
|
+
extra = {}
|
|
3801
|
+
else:
|
|
3802
|
+
extra = dict(extra)
|
|
3803
|
+
profile_id = session_meta.get("profileId")
|
|
3804
|
+
if profile_id and isinstance(profile_id, str) and profile_id.strip():
|
|
3805
|
+
extra["profile_id"] = profile_id.strip()
|
|
3806
|
+
if session_meta.get("serverRun") is not None:
|
|
3807
|
+
extra["server_run"] = bool(session_meta.get("serverRun"))
|
|
3808
|
+
|
|
3809
|
+
extra_json = json.dumps(extra, ensure_ascii=False) if extra else "{}"
|
|
3810
|
+
|
|
3786
3811
|
with open_storage() as conn:
|
|
3787
3812
|
conn.execute("""
|
|
3788
|
-
INSERT INTO conversations (id, title, created_at, updated_at, message_count)
|
|
3789
|
-
VALUES (?, ?, ?, ?, ?)
|
|
3813
|
+
INSERT INTO conversations (id, title, created_at, updated_at, message_count, extra_json)
|
|
3814
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
3790
3815
|
ON CONFLICT(id) DO UPDATE SET
|
|
3791
3816
|
title = excluded.title,
|
|
3792
3817
|
updated_at = excluded.updated_at,
|
|
3793
|
-
message_count = excluded.message_count
|
|
3794
|
-
|
|
3818
|
+
message_count = excluded.message_count,
|
|
3819
|
+
extra_json = excluded.extra_json;
|
|
3820
|
+
""", (session_id, title, created_at, updated_at, len(messages), extra_json))
|
|
3795
3821
|
|
|
3796
3822
|
conn.execute("DELETE FROM messages WHERE conversation_id = ?;", (session_id,))
|
|
3797
3823
|
|
|
@@ -3814,6 +3840,28 @@ def save_conversation(session_meta: dict, messages: list[dict] | None = None) ->
|
|
|
3814
3840
|
return _row_to_conversation_header(row)
|
|
3815
3841
|
|
|
3816
3842
|
|
|
3843
|
+
def mark_conversation_server_run(session_id: str, profile_name: str | None = None) -> bool:
|
|
3844
|
+
"""Marca la conversación en SQLite como ejecutada en servidor asociándole el perfil."""
|
|
3845
|
+
try:
|
|
3846
|
+
clean_id = _validate_conversation_id(session_id)
|
|
3847
|
+
except (ValueError, TypeError):
|
|
3848
|
+
return False
|
|
3849
|
+
try:
|
|
3850
|
+
with open_storage() as conn:
|
|
3851
|
+
row = conn.execute("SELECT extra_json FROM conversations WHERE id = ?;", (clean_id,)).fetchone()
|
|
3852
|
+
if not row:
|
|
3853
|
+
return False
|
|
3854
|
+
cur_extra = json.loads(row["extra_json"]) if row["extra_json"] else {}
|
|
3855
|
+
cur_extra["server_run"] = True
|
|
3856
|
+
if profile_name:
|
|
3857
|
+
cur_extra["profile_id"] = str(profile_name).strip()
|
|
3858
|
+
conn.execute("UPDATE conversations SET extra_json = ? WHERE id = ?;", (json.dumps(cur_extra, ensure_ascii=False), clean_id))
|
|
3859
|
+
conn.commit()
|
|
3860
|
+
return True
|
|
3861
|
+
except (sqlite3.Error, OSError, json.JSONDecodeError):
|
|
3862
|
+
return False
|
|
3863
|
+
|
|
3864
|
+
|
|
3817
3865
|
def rename_conversation(session_id: str, new_title: str) -> bool:
|
|
3818
3866
|
"""Renombra una conversación existente en SQLite."""
|
|
3819
3867
|
clean_id = _validate_conversation_id(session_id)
|
|
@@ -5142,8 +5190,8 @@ RUN_EXIT_TIMEOUT = 2
|
|
|
5142
5190
|
RUN_EXIT_SETUP = 3
|
|
5143
5191
|
# Argumentos no válidos, en cualquier modo: argparse usaría 2, que con --prompt es plazo agotado.
|
|
5144
5192
|
RUN_EXIT_ARGS = 4
|
|
5145
|
-
# Perfil
|
|
5146
|
-
DEFAULT_RUN_PROFILE = "
|
|
5193
|
+
# Perfil por defecto de --prompt cuando no se indica --profile.
|
|
5194
|
+
DEFAULT_RUN_PROFILE = "local"
|
|
5147
5195
|
# Formato de --export según la extensión del fichero; la interfaz genera el contenido con ChatExport.
|
|
5148
5196
|
RUN_EXPORT_FORMATS = {".md": "markdown", ".json": "json", ".html": "html"}
|
|
5149
5197
|
# Cuerpo HTTP admitido mientras se espera la exportación: el JSON y el HTML llevan las imágenes incrustadas.
|
|
@@ -5314,15 +5362,20 @@ def start_server_run(params: dict) -> dict:
|
|
|
5314
5362
|
if not isinstance(conv_id, str) or not conv_id.strip():
|
|
5315
5363
|
raise ValueError("conversation_id requerido.")
|
|
5316
5364
|
clean_conv_id = _validate_conversation_id(conv_id)
|
|
5317
|
-
|
|
5365
|
+
conv = get_conversation(clean_conv_id)
|
|
5366
|
+
if conv is None:
|
|
5318
5367
|
raise ValueError(f"Conversación '{clean_conv_id}' no encontrada.")
|
|
5319
5368
|
|
|
5320
5369
|
profile = params.get("profile")
|
|
5321
5370
|
if not isinstance(profile, str) or not profile.strip():
|
|
5322
|
-
|
|
5371
|
+
conv_profile = conv.get("profileId")
|
|
5372
|
+
if isinstance(conv_profile, str) and conv_profile.strip():
|
|
5373
|
+
profile = conv_profile.strip()
|
|
5374
|
+
else:
|
|
5375
|
+
raise ValueError("profile requerido.")
|
|
5323
5376
|
profile_entry = get_general_profile(profile) or get_general_profile_by_name(profile)
|
|
5324
5377
|
if not profile_entry:
|
|
5325
|
-
raise ValueError(f"Perfil
|
|
5378
|
+
raise ValueError(f"Perfil del servidor '{profile}' no encontrado.")
|
|
5326
5379
|
profile_name = profile_entry.get("name", profile.strip())
|
|
5327
5380
|
|
|
5328
5381
|
state_path = get_run_state_path(clean_conv_id)
|
|
@@ -5356,6 +5409,8 @@ def start_server_run(params: dict) -> dict:
|
|
|
5356
5409
|
env["ZEROCHAT_RUN_SECURITY"] = json.dumps(tool_security, ensure_ascii=False)
|
|
5357
5410
|
|
|
5358
5411
|
now = int(time.time() * 1000)
|
|
5412
|
+
mark_conversation_server_run(clean_conv_id, profile_name)
|
|
5413
|
+
|
|
5359
5414
|
proc = subprocess.Popen(
|
|
5360
5415
|
cmd,
|
|
5361
5416
|
stdin=subprocess.DEVNULL,
|
|
@@ -5405,13 +5460,14 @@ class RunSession:
|
|
|
5405
5460
|
"""Estado de la ejecución: prompt, opciones, último progreso, exportación, resultado y motivo de un final sin él."""
|
|
5406
5461
|
def __init__(self, prompt: str | None = None, profile: str | None = None, export_path: Path | None = None, keep_page: bool = False,
|
|
5407
5462
|
allow_dangerous_tools: bool = False, conversation_id: str | None = None, run_id: str | None = None,
|
|
5408
|
-
tool_security: dict | None = None):
|
|
5463
|
+
tool_security: dict | None = None, profile_data: dict | None = None):
|
|
5409
5464
|
env_run_id = os.environ.get("ZEROCHAT_RUN_ID", "").strip()
|
|
5410
5465
|
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))
|
|
5411
5466
|
self.conversation_id = conversation_id
|
|
5412
5467
|
self.prompt = prompt
|
|
5413
|
-
# Perfil (nombre o id) que la interfaz usa solo en esta ejecución; por defecto,
|
|
5468
|
+
# Perfil (nombre o id) que la interfaz usa solo en esta ejecución; por defecto, local del servidor.
|
|
5414
5469
|
self.profile = profile
|
|
5470
|
+
self.profile_data = profile_data
|
|
5415
5471
|
# Fichero donde se escribe la conversación exportada (formato por su extensión); None, sin exportar.
|
|
5416
5472
|
self.export_path = export_path
|
|
5417
5473
|
self.exported = False
|
|
@@ -5506,6 +5562,7 @@ def dispatch_run(method: str, params: dict) -> tuple[dict | None, dict | None, s
|
|
|
5506
5562
|
session.touch()
|
|
5507
5563
|
export_format = RUN_EXPORT_FORMATS[session.export_path.suffix.lower()] if session.export_path else None
|
|
5508
5564
|
return {"prompt": session.prompt, "conversation_id": session.conversation_id, "profile": session.profile,
|
|
5565
|
+
"profile_data": session.profile_data,
|
|
5509
5566
|
"export": export_format, "keep_page": session.keep_page,
|
|
5510
5567
|
"allow_dangerous_tools": session.allow_dangerous_tools, "tool_security": session.tool_security}, None, ""
|
|
5511
5568
|
if method == "zerochat/run/progress":
|
|
@@ -5713,6 +5770,7 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
|
|
|
5713
5770
|
if not prompt:
|
|
5714
5771
|
parser.error("el prompt está vacío")
|
|
5715
5772
|
conversation_id = None
|
|
5773
|
+
conv = None
|
|
5716
5774
|
if args.conversation is not None:
|
|
5717
5775
|
raw_conv = args.conversation.strip()
|
|
5718
5776
|
if not raw_conv:
|
|
@@ -5737,17 +5795,34 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
|
|
|
5737
5795
|
parser.error("--headless solo se usa con --browser (--prompt y --conversation ya se ejecutan sin ventana con el Chromium de Playwright)")
|
|
5738
5796
|
if args.keep_page and (not args.browser or args.headless):
|
|
5739
5797
|
parser.error("--keep-page necesita la ventana del navegador del usuario (--browser sin --headless)")
|
|
5798
|
+
profile_data = None
|
|
5740
5799
|
if args.profile is not None:
|
|
5741
5800
|
clean_profile = args.profile.strip()
|
|
5742
5801
|
if not clean_profile:
|
|
5743
5802
|
parser.error("--profile no puede estar vacío")
|
|
5744
5803
|
general_match = get_general_profile_by_name(clean_profile) or get_general_profile(clean_profile)
|
|
5745
5804
|
profile_name = general_match["name"] if general_match else clean_profile
|
|
5805
|
+
profile_data = general_match
|
|
5806
|
+
elif conversation_id:
|
|
5807
|
+
conv_profile = conv.get("profileId") if conv else None
|
|
5808
|
+
if conv_profile:
|
|
5809
|
+
match = get_general_profile_by_name(conv_profile) or get_general_profile(conv_profile)
|
|
5810
|
+
if not match:
|
|
5811
|
+
parser.error(f"no existe el perfil '{conv_profile}' en el servidor; créalo o indica uno con --profile")
|
|
5812
|
+
profile_name = match["name"]
|
|
5813
|
+
profile_data = match
|
|
5814
|
+
else:
|
|
5815
|
+
default_match = get_general_profile_by_name(DEFAULT_RUN_PROFILE)
|
|
5816
|
+
if default_match is None:
|
|
5817
|
+
parser.error(f"no existe el perfil por defecto '{DEFAULT_RUN_PROFILE}' en el servidor; créalo o indica uno con --profile")
|
|
5818
|
+
profile_name = default_match["name"]
|
|
5819
|
+
profile_data = default_match
|
|
5746
5820
|
else:
|
|
5747
5821
|
default_match = get_general_profile_by_name(DEFAULT_RUN_PROFILE)
|
|
5748
5822
|
if default_match is None:
|
|
5749
|
-
parser.error(f"no existe el perfil
|
|
5823
|
+
parser.error(f"no existe el perfil por defecto '{DEFAULT_RUN_PROFILE}' en el servidor; créalo o indica uno con --profile")
|
|
5750
5824
|
profile_name = default_match["name"]
|
|
5825
|
+
profile_data = default_match
|
|
5751
5826
|
export_path = None
|
|
5752
5827
|
if args.export is not None:
|
|
5753
5828
|
export_path = Path(args.export).expanduser().absolute()
|
|
@@ -5755,7 +5830,9 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
|
|
|
5755
5830
|
parser.error(f"--export necesita una de estas extensiones: {', '.join(RUN_EXPORT_FORMATS)}")
|
|
5756
5831
|
if not export_path.parent.is_dir():
|
|
5757
5832
|
parser.error(f"--export: no existe el directorio {export_path.parent}")
|
|
5758
|
-
|
|
5833
|
+
if conversation_id:
|
|
5834
|
+
mark_conversation_server_run(conversation_id, profile_name)
|
|
5835
|
+
return RunSession(prompt, profile_name, export_path, args.keep_page, args.allow_dangerous_tools, conversation_id=conversation_id, profile_data=profile_data)
|
|
5759
5836
|
|
|
5760
5837
|
|
|
5761
5838
|
def redirect_log(args):
|
|
@@ -5968,9 +6045,9 @@ def main():
|
|
|
5968
6045
|
if getattr(args, "list_profiles", False):
|
|
5969
6046
|
profiles = list_general_profiles()
|
|
5970
6047
|
if not profiles:
|
|
5971
|
-
print("No hay perfiles de conexión
|
|
6048
|
+
print("No hay perfiles de conexión almacenados en el servidor local.")
|
|
5972
6049
|
else:
|
|
5973
|
-
print("Perfiles de conexión
|
|
6050
|
+
print("Perfiles de conexión del servidor local:")
|
|
5974
6051
|
for p in profiles:
|
|
5975
6052
|
settings = p.get("settings", {})
|
|
5976
6053
|
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
|