zerochat 10.0.0__tar.gz → 10.2.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.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.0.0
3
+ Version: 10.2.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "zerochat"
7
- version = "10.0.0"
7
+ version = "10.2.0"
8
8
  description = "Private local web client for AI models, tools and MCP services"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.0.0
3
+ Version: 10.2.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -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.0.0"
56
+ SOURCE_BACKEND_VERSION = "10.2.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."""
@@ -3433,6 +3433,8 @@ MAX_PROFILE_NAME_LENGTH = 128
3433
3433
  MAX_PROFILE_DESCRIPTION_LENGTH = 2048
3434
3434
  MAX_CONVERSATION_ID_LENGTH = 128
3435
3435
  MAX_CONVERSATION_TITLE_LENGTH = 256
3436
+ MAX_BLOB_SIZE = 50 * 1024 * 1024
3437
+ MAX_BLOB_HTTP_BYTES = 72 * 1024 * 1024
3436
3438
 
3437
3439
  STORAGE_MIGRATIONS = [
3438
3440
  (1, "001_create_profiles_table", """
@@ -3469,6 +3471,19 @@ STORAGE_MIGRATIONS = [
3469
3471
  FOREIGN KEY(conversation_id) REFERENCES conversations(id) ON DELETE CASCADE,
3470
3472
  PRIMARY KEY (conversation_id, position)
3471
3473
  );
3474
+ """),
3475
+ (3, "003_create_blobs_table", """
3476
+ CREATE TABLE IF NOT EXISTS blobs (
3477
+ id TEXT PRIMARY KEY,
3478
+ mime_type TEXT NOT NULL,
3479
+ size INTEGER NOT NULL,
3480
+ data BLOB NOT NULL,
3481
+ created_at INTEGER NOT NULL
3482
+ );
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 '{}';
3472
3487
  """)
3473
3488
  ]
3474
3489
 
@@ -3712,13 +3727,20 @@ def _validate_conversation_title(title, allow_empty: bool = False) -> str:
3712
3727
 
3713
3728
  def _row_to_conversation_header(row: sqlite3.Row) -> dict:
3714
3729
  """Transforma una fila SQLite en la cabecera de una conversación."""
3715
- return {
3730
+ header = {
3716
3731
  "id": row["id"],
3717
3732
  "title": row["title"],
3718
3733
  "createdAt": row["created_at"],
3719
3734
  "updatedAt": row["updated_at"],
3720
3735
  "messageCount": row["message_count"]
3721
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
+ return header
3722
3744
 
3723
3745
 
3724
3746
  def _row_to_message(row: sqlite3.Row) -> dict:
@@ -3771,15 +3793,27 @@ def save_conversation(session_meta: dict, messages: list[dict] | None = None) ->
3771
3793
  created_at = int(session_meta.get("createdAt") or now)
3772
3794
  updated_at = int(session_meta.get("updatedAt") or now)
3773
3795
 
3796
+ extra = session_meta.get("extra")
3797
+ if not isinstance(extra, dict):
3798
+ extra = {}
3799
+ else:
3800
+ extra = dict(extra)
3801
+ profile_id = session_meta.get("profileId")
3802
+ if profile_id and isinstance(profile_id, str) and profile_id.strip():
3803
+ extra["profile_id"] = profile_id.strip()
3804
+
3805
+ extra_json = json.dumps(extra, ensure_ascii=False) if extra else "{}"
3806
+
3774
3807
  with open_storage() as conn:
3775
3808
  conn.execute("""
3776
- INSERT INTO conversations (id, title, created_at, updated_at, message_count)
3777
- VALUES (?, ?, ?, ?, ?)
3809
+ INSERT INTO conversations (id, title, created_at, updated_at, message_count, extra_json)
3810
+ VALUES (?, ?, ?, ?, ?, ?)
3778
3811
  ON CONFLICT(id) DO UPDATE SET
3779
3812
  title = excluded.title,
3780
3813
  updated_at = excluded.updated_at,
3781
- message_count = excluded.message_count;
3782
- """, (session_id, title, created_at, updated_at, len(messages)))
3814
+ message_count = excluded.message_count,
3815
+ extra_json = excluded.extra_json;
3816
+ """, (session_id, title, created_at, updated_at, len(messages), extra_json))
3783
3817
 
3784
3818
  conn.execute("DELETE FROM messages WHERE conversation_id = ?;", (session_id,))
3785
3819
 
@@ -3831,6 +3865,82 @@ def delete_all_conversations() -> int:
3831
3865
  cursor = conn.execute("DELETE FROM conversations;")
3832
3866
  conn.commit()
3833
3867
  return cursor.rowcount
3868
+
3869
+
3870
+ def _validate_blob_id(blob_id: str) -> str:
3871
+ """Valida que el identificador del blob sea un hash SHA-256 en hexadecimal (64 caracteres)."""
3872
+ if not isinstance(blob_id, str) or not re.match(r"^[0-9a-f]{64}$", blob_id.strip().lower()):
3873
+ raise ValueError(f"ID de blob inválido (debe ser un hash SHA-256 hexadecimal de 64 caracteres): {blob_id}")
3874
+ return blob_id.strip().lower()
3875
+
3876
+
3877
+ def put_blob(data_bytes: bytes, mime_type: str = "application/octet-stream", blob_id: str | None = None) -> dict:
3878
+ """Almacena un blob binario indexado por su hash SHA-256."""
3879
+ if not isinstance(data_bytes, (bytes, bytearray)):
3880
+ raise ValueError("Los datos del blob deben ser bytes")
3881
+ if len(data_bytes) == 0:
3882
+ raise ValueError("El blob no puede estar vacío")
3883
+ if len(data_bytes) > MAX_BLOB_SIZE:
3884
+ raise ValueError(f"El tamaño del blob ({len(data_bytes)} bytes) excede el máximo permitido ({MAX_BLOB_SIZE} bytes)")
3885
+
3886
+ calc_id = hashlib.sha256(data_bytes).hexdigest()
3887
+ if blob_id is not None:
3888
+ clean_id = _validate_blob_id(blob_id)
3889
+ if clean_id != calc_id:
3890
+ raise ValueError(f"El ID del blob ({clean_id}) no coincide con el hash SHA-256 de los datos ({calc_id})")
3891
+ else:
3892
+ clean_id = calc_id
3893
+
3894
+ mime = (mime_type or "application/octet-stream").strip()
3895
+ now = int(time.time() * 1000)
3896
+ with open_storage() as conn:
3897
+ conn.execute("""
3898
+ INSERT INTO blobs (id, mime_type, size, data, created_at)
3899
+ VALUES (?, ?, ?, ?, ?)
3900
+ ON CONFLICT(id) DO UPDATE SET
3901
+ mime_type = excluded.mime_type,
3902
+ size = excluded.size,
3903
+ data = excluded.data;
3904
+ """, (clean_id, mime, len(data_bytes), sqlite3.Binary(data_bytes), now))
3905
+ conn.commit()
3906
+ return {"id": clean_id, "mime_type": mime, "size": len(data_bytes), "created_at": now}
3907
+
3908
+
3909
+ def get_blob(blob_id: str) -> dict | None:
3910
+ """Recupera un blob por su hash SHA-256."""
3911
+ clean_id = _validate_blob_id(blob_id)
3912
+ with open_storage() as conn:
3913
+ row = conn.execute("SELECT id, mime_type, size, data, created_at FROM blobs WHERE id = ?;", (clean_id,)).fetchone()
3914
+ if not row:
3915
+ return None
3916
+ return {
3917
+ "id": row["id"],
3918
+ "mime_type": row["mime_type"],
3919
+ "size": row["size"],
3920
+ "data": bytes(row["data"]),
3921
+ "created_at": row["created_at"],
3922
+ }
3923
+
3924
+
3925
+ def has_blobs(blob_ids: list[str]) -> dict:
3926
+ """Comprueba la existencia de una lista de IDs de blobs, devolviendo los existentes y los faltantes."""
3927
+ if not isinstance(blob_ids, list):
3928
+ raise ValueError("La lista de IDs de blobs debe ser una lista")
3929
+ if len(blob_ids) > 1000:
3930
+ raise ValueError("No se pueden consultar más de 1000 IDs de blobs a la vez")
3931
+ clean_ids = [_validate_blob_id(bid) for bid in blob_ids]
3932
+ if not clean_ids:
3933
+ return {"existing": [], "missing": []}
3934
+ unique_ids = list(dict.fromkeys(clean_ids))
3935
+ with open_storage() as conn:
3936
+ placeholders = ",".join("?" for _ in unique_ids)
3937
+ rows = conn.execute(f"SELECT id FROM blobs WHERE id IN ({placeholders});", unique_ids).fetchall()
3938
+ existing_set = {row["id"] for row in rows}
3939
+ return {
3940
+ "existing": [bid for bid in unique_ids if bid in existing_set],
3941
+ "missing": [bid for bid in unique_ids if bid not in existing_set],
3942
+ }
3943
+
3834
3944
  DEFAULT_HEARTBEAT_TIMEOUT = float(os.environ.get("ZEROCHAT_HEARTBEAT_TIMEOUT", "60.0"))
3835
3945
  DEFAULT_HEARTBEAT_GRACE = float(os.environ.get("ZEROCHAT_HEARTBEAT_GRACE", "45.0"))
3836
3946
  DEFAULT_HEARTBEAT_POLL = float(os.environ.get("ZEROCHAT_HEARTBEAT_POLL", "5.0"))
@@ -4162,7 +4272,7 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
4162
4272
  return
4163
4273
  self.send_header("Access-Control-Allow-Origin", origin if origin else "*")
4164
4274
  self.send_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
4165
- self.send_header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-ZeroChat-Token, X-ZeroChat-Client, X-ZeroChat-Proxy, X-ZeroChat-Tool-Session, X-ZeroChat-Tool-Expires, X-ZeroChat-Tool-Nonce, X-ZeroChat-Tool-Signature")
4275
+ self.send_header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-ZeroChat-Token, X-ZeroChat-Client, X-ZeroChat-Proxy, X-ZeroChat-Tool-Session, X-ZeroChat-Tool-Expires, X-ZeroChat-Tool-Nonce, X-ZeroChat-Tool-Signature, X-ZeroChat-Blob")
4166
4276
  self.send_header("Access-Control-Allow-Private-Network", "true")
4167
4277
 
4168
4278
  def verify_token(self) -> bool:
@@ -4287,7 +4397,11 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
4287
4397
  self._log_req("POST", safe_path)
4288
4398
  self._reject(400, {"error": "Invalid Content-Length"}, safe_path, t0, "Content-Length negativo")
4289
4399
  return None
4290
- body_limit = http_body_limit()
4400
+ is_blob_upload = (
4401
+ self.headers.get("X-ZeroChat-Blob") == "1"
4402
+ or safe_path in ("/zerochat/blobs", "/zerochat/blobs/put")
4403
+ )
4404
+ body_limit = MAX_BLOB_HTTP_BYTES if is_blob_upload else http_body_limit()
4291
4405
  if content_len > body_limit:
4292
4406
  self._log_req("POST", safe_path)
4293
4407
  if content_len <= body_limit * 2:
@@ -4307,8 +4421,10 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
4307
4421
  self._reject(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": f"Parse error: {err}"}},
4308
4422
  safe_path, t0, f"Error parseando JSON: {err}")
4309
4423
  return None
4310
- # El tope ampliado de http_body_limit es solo para la exportación de --prompt --export.
4311
- if content_len > MAX_HTTP_BODY_BYTES and not (isinstance(req, dict) and req.get("method") == "zerochat/run/export"):
4424
+ # El tope ampliado de http_body_limit es solo para la exportación de --prompt --export y la subida de blobs.
4425
+ if content_len > MAX_HTTP_BODY_BYTES and not (
4426
+ isinstance(req, dict) and req.get("method") in ("zerochat/run/export", "zerochat/blobs/put")
4427
+ ):
4312
4428
  self._log_req("POST", safe_path)
4313
4429
  self._reject(413, {"error": "Request body too large"}, safe_path, t0, "Cuerpo HTTP excede el límite")
4314
4430
  return None
@@ -4467,6 +4583,8 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
4467
4583
  return self._dispatch_profiles(method, params)
4468
4584
  if method.startswith("zerochat/conversations/"):
4469
4585
  return self._dispatch_conversations(method, params)
4586
+ if method.startswith("zerochat/blobs/"):
4587
+ return self._dispatch_blobs(method, params)
4470
4588
  return None, {"code": -32601, "message": f"Método '{method}' no soportado."}, ""
4471
4589
 
4472
4590
  @staticmethod
@@ -4525,6 +4643,51 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
4525
4643
  return None, {"code": -32603, "message": f"Error en gestión de conversaciones: {exc}"}, str(exc)
4526
4644
  return None, {"code": -32601, "message": f"Método '{method}' no soportado."}, ""
4527
4645
 
4646
+ @staticmethod
4647
+ def _dispatch_blobs(method: str, params: dict) -> tuple[dict | None, dict | None, str]:
4648
+ """Gestión de blobs desacoplados de mensajes (imágenes y adjuntos) en SQLite."""
4649
+ params = params if isinstance(params, dict) else {}
4650
+ try:
4651
+ if method == "zerochat/blobs/has":
4652
+ ids = params.get("ids")
4653
+ if ids is None:
4654
+ ids = []
4655
+ return has_blobs(ids), None, ""
4656
+ if method == "zerochat/blobs/put":
4657
+ raw_data = params.get("data")
4658
+ if not raw_data or not isinstance(raw_data, str):
4659
+ raise ValueError("El parámetro 'data' debe ser una cadena en base64 no vacía")
4660
+ mime_type = params.get("mimeType") or "application/octet-stream"
4661
+ if raw_data.startswith("data:") and ";base64," in raw_data:
4662
+ header, b64_part = raw_data.split(";base64,", 1)
4663
+ if not params.get("mimeType"):
4664
+ mime_type = header[5:]
4665
+ raw_data = b64_part
4666
+ try:
4667
+ data_bytes = base64.b64decode(raw_data)
4668
+ except Exception as decode_err:
4669
+ raise ValueError(f"Error decodificando base64: {decode_err}")
4670
+ saved = put_blob(data_bytes, mime_type=mime_type, blob_id=params.get("id"))
4671
+ return {"id": saved["id"], "mimeType": saved["mime_type"], "size": saved["size"]}, None, ""
4672
+ if method == "zerochat/blobs/get":
4673
+ blob = get_blob(params.get("id"))
4674
+ if not blob:
4675
+ return {"blob": None}, None, ""
4676
+ return {
4677
+ "blob": {
4678
+ "id": blob["id"],
4679
+ "mimeType": blob["mime_type"],
4680
+ "size": blob["size"],
4681
+ "data": base64.b64encode(blob["data"]).decode("ascii"),
4682
+ "createdAt": blob["created_at"],
4683
+ }
4684
+ }, None, ""
4685
+ except ValueError as exc:
4686
+ return None, {"code": -32602, "message": str(exc)}, ""
4687
+ except Exception as exc:
4688
+ return None, {"code": -32603, "message": f"Error en gestión de blobs: {exc}"}, str(exc)
4689
+ return None, {"code": -32601, "message": f"Método '{method}' no soportado."}, ""
4690
+
4528
4691
  @staticmethod
4529
4692
  def _login(params: dict) -> tuple[dict | None, dict | None, str]:
4530
4693
  try:
@@ -4913,7 +5076,12 @@ def launch_headless_browser(url: str) -> subprocess.Popen | None:
4913
5076
  log_event(f"Abriendo {Path(executable).name} sin ventana en la interfaz configurada...")
4914
5077
  try:
4915
5078
  return subprocess.Popen(
4916
- [executable, "--headless", url],
5079
+ [
5080
+ executable,
5081
+ "--headless",
5082
+ "--disable-features=LocalNetworkAccessChecks,BlockInsecurePrivateNetworkRequests",
5083
+ url,
5084
+ ],
4917
5085
  stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
4918
5086
  start_new_session=True,
4919
5087
  )
@@ -4965,7 +5133,12 @@ def launch_playwright_chromium(url: str) -> subprocess.Popen | None:
4965
5133
  log_event(f"Abriendo {Path(executable).name} de Playwright sin ventana en la interfaz configurada...")
4966
5134
  try:
4967
5135
  return subprocess.Popen(
4968
- [executable, "--headless", url],
5136
+ [
5137
+ executable,
5138
+ "--headless",
5139
+ "--disable-features=LocalNetworkAccessChecks,BlockInsecurePrivateNetworkRequests",
5140
+ url,
5141
+ ],
4969
5142
  stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
4970
5143
  start_new_session=True,
4971
5144
  )
@@ -5163,12 +5336,17 @@ def start_server_run(params: dict) -> dict:
5163
5336
  if not isinstance(conv_id, str) or not conv_id.strip():
5164
5337
  raise ValueError("conversation_id requerido.")
5165
5338
  clean_conv_id = _validate_conversation_id(conv_id)
5166
- if get_conversation(clean_conv_id) is None:
5339
+ conv = get_conversation(clean_conv_id)
5340
+ if conv is None:
5167
5341
  raise ValueError(f"Conversación '{clean_conv_id}' no encontrada.")
5168
5342
 
5169
5343
  profile = params.get("profile")
5170
5344
  if not isinstance(profile, str) or not profile.strip():
5171
- raise ValueError("profile requerido.")
5345
+ conv_profile = conv.get("profileId")
5346
+ if isinstance(conv_profile, str) and conv_profile.strip():
5347
+ profile = conv_profile.strip()
5348
+ else:
5349
+ raise ValueError("profile requerido.")
5172
5350
  profile_entry = get_general_profile(profile) or get_general_profile_by_name(profile)
5173
5351
  if not profile_entry:
5174
5352
  raise ValueError(f"Perfil general '{profile}' no encontrado.")
@@ -5562,6 +5740,7 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
5562
5740
  if not prompt:
5563
5741
  parser.error("el prompt está vacío")
5564
5742
  conversation_id = None
5743
+ conv = None
5565
5744
  if args.conversation is not None:
5566
5745
  raw_conv = args.conversation.strip()
5567
5746
  if not raw_conv:
@@ -5592,6 +5771,18 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
5592
5771
  parser.error("--profile no puede estar vacío")
5593
5772
  general_match = get_general_profile_by_name(clean_profile) or get_general_profile(clean_profile)
5594
5773
  profile_name = general_match["name"] if general_match else clean_profile
5774
+ elif conversation_id:
5775
+ conv_profile = conv.get("profileId") if conv else None
5776
+ if conv_profile:
5777
+ match = get_general_profile_by_name(conv_profile) or get_general_profile(conv_profile)
5778
+ if not match:
5779
+ parser.error(f"no existe el perfil general '{conv_profile}' de la conversación; créalo o indica uno con --profile")
5780
+ profile_name = match["name"]
5781
+ else:
5782
+ default_match = get_general_profile_by_name(DEFAULT_RUN_PROFILE)
5783
+ if default_match is None:
5784
+ parser.error(f"no existe el perfil general por defecto '{DEFAULT_RUN_PROFILE}'; créalo o indica uno con --profile")
5785
+ profile_name = default_match["name"]
5595
5786
  else:
5596
5787
  default_match = get_general_profile_by_name(DEFAULT_RUN_PROFILE)
5597
5788
  if default_match is None:
File without changes
File without changes
File without changes