zerochat 10.41.0__tar.gz → 10.42.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.41.0
3
+ Version: 10.42.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.41.0"
7
+ version = "10.42.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.41.0
3
+ Version: 10.42.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
@@ -514,7 +514,7 @@ class TokenGrant:
514
514
  if method == "zerochat/conversations/save":
515
515
  conv = params.get("conversation")
516
516
  return isinstance(conv, dict) and conv.get("id") == self.conversation_id
517
- if method == "zerochat/conversations/save_chunk":
517
+ if method in ("zerochat/conversations/save_chunk", "zerochat/conversations/cancel_upload"):
518
518
  return params.get("conversationId") == self.conversation_id
519
519
  return False
520
520
 
@@ -1133,7 +1133,7 @@ def parse_nonneg_int(value, label: str, default: int = 0) -> int:
1133
1133
 
1134
1134
 
1135
1135
 
1136
- SOURCE_BACKEND_VERSION = "10.41.0"
1136
+ SOURCE_BACKEND_VERSION = "10.42.0"
1137
1137
 
1138
1138
 
1139
1139
  def _read_source_version(filename: str) -> str | None:
@@ -2411,6 +2411,12 @@ MAX_PROFILE_NAME_LENGTH = 128
2411
2411
  MAX_PROFILE_DESCRIPTION_LENGTH = 2048
2412
2412
  MAX_CONVERSATION_ID_LENGTH = 128
2413
2413
  MAX_CONVERSATION_TITLE_LENGTH = 256
2414
+ # Identificador de agente de una conversación: <subconjunto>.<nombre>, dos niveles dentro de su proyecto.
2415
+ MAX_AGENT_ID_LENGTH = 64
2416
+ _AGENT_SEGMENT = r"[a-z0-9_-]+"
2417
+ _AGENT_ID_PATTERN = re.compile(rf"{_AGENT_SEGMENT}\.{_AGENT_SEGMENT}")
2418
+ # Patrón de watchAgents: todos los agentes del proyecto, los de un subconjunto o uno concreto.
2419
+ _AGENT_WATCH_PATTERN = re.compile(rf"\*|{_AGENT_SEGMENT}\.(?:\*|{_AGENT_SEGMENT})")
2414
2420
  MAX_BLOB_SIZE = 50 * 1024 * 1024
2415
2421
  MAX_BLOB_HTTP_BYTES = 72 * 1024 * 1024
2416
2422
  CONVERSATION_UPLOAD_TTL_SECONDS = 300
@@ -2652,6 +2658,19 @@ def open_storage():
2652
2658
  conn.close()
2653
2659
 
2654
2660
 
2661
+ @contextlib.contextmanager
2662
+ def _immediate_transaction(conn: sqlite3.Connection):
2663
+ """Transacción de escritura BEGIN IMMEDIATE sobre `conn`: COMMIT al salir y ROLLBACK si sale una excepción."""
2664
+ conn.isolation_level = None
2665
+ conn.execute("BEGIN IMMEDIATE;")
2666
+ try:
2667
+ yield conn
2668
+ except BaseException:
2669
+ conn.execute("ROLLBACK;")
2670
+ raise
2671
+ conn.execute("COMMIT;")
2672
+
2673
+
2655
2674
  def normalize_profile_id(name: str, given_id: str | None = None) -> str:
2656
2675
  """Genera o normaliza un identificador único para el perfil."""
2657
2676
  if given_id and isinstance(given_id, str) and given_id.strip():
@@ -2692,8 +2711,6 @@ def validate_profile_payload(record: dict) -> tuple[str, str, str, dict, str | N
2692
2711
  raise ValueError("Los ajustes del perfil deben ser un objeto")
2693
2712
 
2694
2713
  settings = dict(settings_source)
2695
- settings.pop("mcpServers", None)
2696
- settings.pop("playwrightBrowser", None)
2697
2714
  has_api_key = "apiKey" in settings or "apiKey" in record
2698
2715
  raw_key = settings.pop("apiKey", None)
2699
2716
  if raw_key is None:
@@ -2826,6 +2843,27 @@ def _validate_conversation_id(session_id) -> str:
2826
2843
  return clean
2827
2844
 
2828
2845
 
2846
+ def validate_agent_id(agent) -> str:
2847
+ """El identificador de agente <subconjunto>.<nombre> (minúsculas, cifras, _ y -), sin pasar de MAX_AGENT_ID_LENGTH."""
2848
+ if not isinstance(agent, str) or len(agent) > MAX_AGENT_ID_LENGTH or not _AGENT_ID_PATTERN.fullmatch(agent):
2849
+ raise ValueError(f"agent debe ser <subconjunto>.<nombre> con minúsculas, cifras, _ o - y hasta {MAX_AGENT_ID_LENGTH} caracteres")
2850
+ return agent
2851
+
2852
+
2853
+ def validate_agent_watch_pattern(pattern) -> str:
2854
+ """Un patrón de watchAgents: '*', '<subconjunto>.*' o '<subconjunto>.<nombre>', con el tope de un identificador."""
2855
+ if not isinstance(pattern, str) or len(pattern) > MAX_AGENT_ID_LENGTH or not _AGENT_WATCH_PATTERN.fullmatch(pattern):
2856
+ raise ValueError("watchAgents admite '*', '<subconjunto>.*' o '<subconjunto>.<nombre>'")
2857
+ return pattern
2858
+
2859
+
2860
+ def agent_matches(agent, patterns) -> bool:
2861
+ """Si el agente de una conversación lo cubre alguno de los patrones de watchAgents; una sin agente, nunca."""
2862
+ if not isinstance(agent, str) or not agent:
2863
+ return False
2864
+ return any(pattern in ("*", agent) or (pattern.endswith(".*") and agent.startswith(pattern[:-1])) for pattern in patterns)
2865
+
2866
+
2829
2867
  def _validate_conversation_title(title, allow_empty: bool = False) -> str:
2830
2868
  if not isinstance(title, str):
2831
2869
  raise ValueError("El título de la conversación debe ser un texto")
@@ -2853,6 +2891,8 @@ def _row_to_conversation_header(row: sqlite3.Row) -> dict:
2853
2891
  header["serverRun"] = bool(extra["server_run"])
2854
2892
  if extra.get("project"):
2855
2893
  header["project"] = extra["project"]
2894
+ if extra.get("agent"):
2895
+ header["agent"] = extra["agent"]
2856
2896
  return header
2857
2897
 
2858
2898
 
@@ -2932,7 +2972,7 @@ def _delete_orphan_blobs(conn: sqlite3.Connection, candidates: set[str]):
2932
2972
 
2933
2973
 
2934
2974
  def _conversation_extra(session_meta: dict) -> dict:
2935
- """Campos de extra_json que trae la petición: el perfil, el modo servidor y el proyecto."""
2975
+ """Campos de extra_json que trae la petición: el perfil, el modo servidor, el proyecto y el agente."""
2936
2976
  extra = {}
2937
2977
  profile_id = session_meta.get("profileId")
2938
2978
  if profile_id and isinstance(profile_id, str) and profile_id.strip():
@@ -2945,12 +2985,17 @@ def _conversation_extra(session_meta: dict) -> dict:
2945
2985
  raise ValueError("El proyecto de la conversación debe ser una ruta")
2946
2986
  if project.strip():
2947
2987
  extra["project"] = project.strip()
2988
+ if session_meta.get("agent") is not None:
2989
+ extra["agent"] = validate_agent_id(session_meta["agent"])
2990
+ if isinstance(session_meta.get("launch"), dict):
2991
+ extra["launch"] = session_meta["launch"]
2948
2992
  return extra
2949
2993
 
2950
2994
 
2951
2995
  def _merge_saved_header(existing, session_meta: dict, created_at: int, title: str, extra: dict) -> tuple[int, str, dict]:
2952
2996
  """Completa la cabecera con la guardada: su fecha de creación y su título si la petición no los trae, y su
2953
- extra_json debajo del nuevo. El proyecto se fija al crear la conversación y no cambia después."""
2997
+ extra_json debajo del nuevo. El proyecto y el agente se fijan al crear la conversación; cuando guarda la interfaz
2998
+ (sin `launch` en `session_meta`) una conversación de agente conserva también su `launch` y su `profile_id`."""
2954
2999
  if not session_meta.get("createdAt") and existing["created_at"]:
2955
3000
  created_at = int(existing["created_at"])
2956
3001
  if not title and existing["title"]:
@@ -2959,6 +3004,11 @@ def _merge_saved_header(existing, session_meta: dict, created_at: int, title: st
2959
3004
  extra = {**existing_extra, **extra}
2960
3005
  if existing_extra.get("project"):
2961
3006
  extra["project"] = existing_extra["project"]
3007
+ extra.pop("agent", None)
3008
+ if existing_extra.get("agent"):
3009
+ extra["agent"] = existing_extra["agent"]
3010
+ if "launch" not in session_meta and existing_extra.get("profile_id"):
3011
+ extra["profile_id"] = existing_extra["profile_id"]
2962
3012
  return created_at, title, extra
2963
3013
 
2964
3014
 
@@ -3009,7 +3059,7 @@ def save_conversation(session_meta: dict, messages: list[dict] | None = None) ->
3009
3059
  now = int(time.time() * 1000)
3010
3060
  created_at = int(session_meta.get("createdAt") or now)
3011
3061
  updated_at = int(session_meta.get("updatedAt") or now)
3012
- # extra_json guarda el perfil, el modo servidor y el proyecto; la cabecera los expone como campos propios.
3062
+ # extra_json guarda el perfil, el modo servidor, el proyecto y el agente; la cabecera los expone como campos propios.
3013
3063
  extra = _conversation_extra(session_meta)
3014
3064
 
3015
3065
  with open_storage() as conn:
@@ -3175,6 +3225,20 @@ def save_conversation_chunk(params: dict) -> dict:
3175
3225
  return {"ok": True, "uploadId": upload_id, "receivedChunks": entry["next_index"]}
3176
3226
 
3177
3227
 
3228
+ def cancel_conversation_upload(params: dict) -> dict:
3229
+ """Libera la subida por tramos pendiente de una conversación (un tramo falló y no se va a consolidar)."""
3230
+ if not isinstance(params, dict):
3231
+ raise ValueError("Los parámetros deben ser un objeto")
3232
+ upload_id = _validate_upload_id(params.get("uploadId"))
3233
+ conv_id = _validate_conversation_id(params.get("conversationId"))
3234
+ with _STORAGE_LOCK:
3235
+ entry = _PENDING_CONVERSATION_UPLOADS.get(upload_id)
3236
+ if not entry or entry["conversation_id"] != conv_id:
3237
+ return {"cancelled": False}
3238
+ del _PENDING_CONVERSATION_UPLOADS[upload_id]
3239
+ return {"cancelled": True}
3240
+
3241
+
3178
3242
  def commit_conversation_upload(session_meta: dict, upload_id: str) -> dict:
3179
3243
  """Consolida atómicamente en SQLite una conversación subida por tramos."""
3180
3244
  if not isinstance(session_meta, dict):
@@ -3194,8 +3258,8 @@ def commit_conversation_upload(session_meta: dict, upload_id: str) -> dict:
3194
3258
  return save_conversation(session_meta, messages)
3195
3259
 
3196
3260
 
3197
- def mark_conversation_server_run(session_id: str, profile_name: str | None = None) -> bool:
3198
- """Marca la conversación en SQLite como ejecutada en servidor asociándole el perfil."""
3261
+ def _patch_conversation_extra(session_id: str, patch: dict) -> bool:
3262
+ """Añade campos al extra_json de una conversación que existe; False si no existe o no se pudo guardar."""
3199
3263
  try:
3200
3264
  clean_id = _validate_conversation_id(session_id)
3201
3265
  except (ValueError, TypeError):
@@ -3206,9 +3270,7 @@ def mark_conversation_server_run(session_id: str, profile_name: str | None = Non
3206
3270
  if not row:
3207
3271
  return False
3208
3272
  cur_extra = json.loads(row["extra_json"]) if row["extra_json"] else {}
3209
- cur_extra["server_run"] = True
3210
- if profile_name:
3211
- cur_extra["profile_id"] = str(profile_name).strip()
3273
+ cur_extra.update(patch)
3212
3274
  conn.execute("UPDATE conversations SET extra_json = ? WHERE id = ?;", (json.dumps(cur_extra, ensure_ascii=False), clean_id))
3213
3275
  conn.commit()
3214
3276
  except (sqlite3.Error, OSError, json.JSONDecodeError):
@@ -3217,6 +3279,24 @@ def mark_conversation_server_run(session_id: str, profile_name: str | None = Non
3217
3279
  return True
3218
3280
 
3219
3281
 
3282
+ def mark_conversation_server_run(session_id: str, profile_name: str | None = None) -> bool:
3283
+ """Marca la conversación en SQLite como ejecutada en servidor asociándole el perfil."""
3284
+ patch: dict = {"server_run": True}
3285
+ if profile_name:
3286
+ patch["profile_id"] = str(profile_name).strip()
3287
+ return _patch_conversation_extra(session_id, patch)
3288
+
3289
+
3290
+ def get_conversation_launch(session_id: str) -> dict | None:
3291
+ """La petición de lanzamiento guardada de una conversación de agente, o None si no la tiene."""
3292
+ clean_id = _validate_conversation_id(session_id)
3293
+ with open_storage() as conn:
3294
+ row = conn.execute("SELECT extra_json FROM conversations WHERE id = ?;", (clean_id,)).fetchone()
3295
+ extra = json.loads(row["extra_json"]) if row and row["extra_json"] else {}
3296
+ launch = extra.get("launch")
3297
+ return launch if isinstance(launch, dict) else None
3298
+
3299
+
3220
3300
  def rename_conversation(session_id: str, new_title: str) -> bool:
3221
3301
  """Renombra una conversación existente en SQLite."""
3222
3302
  clean_id = _validate_conversation_id(session_id)
@@ -3234,34 +3314,34 @@ def rename_conversation(session_id: str, new_title: str) -> bool:
3234
3314
  return changed
3235
3315
 
3236
3316
 
3317
+ def _delete_conversations_in_transaction(conn: sqlite3.Connection, where: str, params: tuple) -> list[str]:
3318
+ """Borra, dentro de la transacción abierta de `conn`, las conversaciones que cumplen `where` y sus blobs huérfanos."""
3319
+ ids = [row["id"] for row in conn.execute(f"SELECT id FROM conversations WHERE {where};", params)] # noqa: S608
3320
+ if ids:
3321
+ marks = ",".join("?" for _ in ids)
3322
+ candidates = {
3323
+ row["blob_id"]
3324
+ for row in conn.execute(
3325
+ f"SELECT DISTINCT blob_id FROM conversation_blobs WHERE conversation_id IN ({marks});", # noqa: S608
3326
+ ids,
3327
+ )
3328
+ }
3329
+ conn.execute(f"DELETE FROM conversations WHERE id IN ({marks});", ids) # noqa: S608
3330
+ _delete_orphan_blobs(conn, candidates)
3331
+ return ids
3332
+
3333
+
3237
3334
  def _delete_conversations(conn: sqlite3.Connection, where: str, params: tuple) -> list[str]:
3238
3335
  """
3239
3336
  Borra en una transacción las conversaciones que cumplen `where`, con sus mensajes en cascada, y los
3240
3337
  blobs que solo ellas referenciaban. Solo se consideran los blobs de las conversaciones borradas: uno
3241
3338
  subido para una conversación que aún no se ha guardado no se toca.
3242
3339
  """
3243
- conn.isolation_level = None
3244
- conn.execute("BEGIN IMMEDIATE;")
3245
- try:
3246
- ids = [row["id"] for row in conn.execute(f"SELECT id FROM conversations WHERE {where};", params)] # noqa: S608
3247
- if ids:
3248
- marks = ",".join("?" for _ in ids)
3249
- candidates = {
3250
- row["blob_id"]
3251
- for row in conn.execute(
3252
- f"SELECT DISTINCT blob_id FROM conversation_blobs WHERE conversation_id IN ({marks});", # noqa: S608
3253
- ids,
3254
- )
3255
- }
3256
- conn.execute(f"DELETE FROM conversations WHERE id IN ({marks});", ids) # noqa: S608
3257
- _delete_orphan_blobs(conn, candidates)
3258
- conn.execute("COMMIT;")
3259
- if ids:
3260
- notify_live_change()
3261
- return ids
3262
- except Exception:
3263
- conn.execute("ROLLBACK;")
3264
- raise
3340
+ with _immediate_transaction(conn):
3341
+ ids = _delete_conversations_in_transaction(conn, where, params)
3342
+ if ids:
3343
+ notify_live_change()
3344
+ return ids
3265
3345
 
3266
3346
 
3267
3347
  def delete_conversation(session_id: str) -> bool:
@@ -3368,15 +3448,21 @@ def has_blobs(blob_ids: list[str]) -> dict:
3368
3448
 
3369
3449
 
3370
3450
  GLOBAL_SECURITY_POLICY_ID = "global"
3371
- PROJECT_SECURITY_POLICY_PREFIX = "project:"
3451
+ # Prefijo único de lo guardado por proyecto: la fila de políticas es `project:<key>` y cada secreto `project:<key>:<NOMBRE>`.
3452
+ PROJECT_KEY_PREFIX = "project:"
3372
3453
 
3373
3454
 
3374
- def project_security_policy_id(project_key: str) -> str:
3375
- """Clave de fila en `security_policies` para un proyecto concreto."""
3455
+ def clean_project_key(project_key) -> str:
3456
+ """Clave de proyecto sin espacios alrededor; vacía es un error."""
3376
3457
  clean_key = str(project_key or "").strip()
3377
3458
  if not clean_key:
3378
3459
  raise ValueError("project_key es obligatorio")
3379
- return f"{PROJECT_SECURITY_POLICY_PREFIX}{clean_key}"
3460
+ return clean_key
3461
+
3462
+
3463
+ def project_security_policy_id(project_key: str) -> str:
3464
+ """Clave de fila en `security_policies` para un proyecto concreto."""
3465
+ return f"{PROJECT_KEY_PREFIX}{clean_project_key(project_key)}"
3380
3466
 
3381
3467
 
3382
3468
  def _parse_security_policy_row(row) -> dict | None:
@@ -3404,8 +3490,8 @@ def _upsert_security_policy_row(conn: sqlite3.Connection, row_id: str, data: dic
3404
3490
 
3405
3491
  def _count_other_project_patterns(conn: sqlite3.Connection, excluded_id: str) -> int:
3406
3492
  rows = conn.execute(
3407
- "SELECT data_json FROM security_policies WHERE id LIKE 'project:%' AND id != ?;",
3408
- (excluded_id,),
3493
+ "SELECT data_json FROM security_policies WHERE substr(id, 1, ?) = ? AND id != ?;",
3494
+ (len(PROJECT_KEY_PREFIX), PROJECT_KEY_PREFIX, excluded_id),
3409
3495
  ).fetchall()
3410
3496
  total = 0
3411
3497
  for row in rows:
@@ -3431,9 +3517,7 @@ def update_security_policy_data(
3431
3517
  """Ejecuta una lectura-modificación-escritura atómica sobre la fila global y la del proyecto en BEGIN IMMEDIATE."""
3432
3518
  proj_id = project_security_policy_id(project_key)
3433
3519
  with open_storage() as conn:
3434
- conn.isolation_level = None
3435
- conn.execute("BEGIN IMMEDIATE;")
3436
- try:
3520
+ with _immediate_transaction(conn):
3437
3521
  global_row = conn.execute("SELECT data_json FROM security_policies WHERE id = ?;", (GLOBAL_SECURITY_POLICY_ID,)).fetchone()
3438
3522
  proj_row = conn.execute("SELECT data_json FROM security_policies WHERE id = ?;", (proj_id,)).fetchone()
3439
3523
  other_pattern_count = _count_other_project_patterns(conn, proj_id)
@@ -3448,11 +3532,7 @@ def update_security_policy_data(
3448
3532
  conn.execute("DELETE FROM security_policies WHERE id = ?;", (proj_id,))
3449
3533
  else:
3450
3534
  _upsert_security_policy_row(conn, proj_id, new_project, now)
3451
- conn.execute("COMMIT;")
3452
3535
  return new_global, new_project
3453
- except Exception:
3454
- conn.execute("ROLLBACK;")
3455
- raise
3456
3536
 
3457
3537
 
3458
3538
  def _write_secret_on_conn(conn: sqlite3.Connection, name: str, value: str, now: int):
@@ -3500,18 +3580,12 @@ def set_setting(key: str, value, *, secret_name: str | None = None, secret: str
3500
3580
  """Guarda un ajuste JSON en `settings`; con `secret_name`, guarda (o borra si va vacío) en la misma transacción su secreto ofuscado."""
3501
3581
  now = int(time.time() * 1000)
3502
3582
  with open_storage() as conn:
3503
- conn.isolation_level = None
3504
- conn.execute("BEGIN IMMEDIATE;")
3505
- try:
3583
+ with _immediate_transaction(conn):
3506
3584
  _write_setting_on_conn(conn, key, value, now)
3507
3585
  if secret_name and secret:
3508
3586
  _write_secret_on_conn(conn, secret_name, secret, now)
3509
3587
  elif secret_name:
3510
3588
  conn.execute("DELETE FROM secrets WHERE name = ?;", (secret_name,))
3511
- conn.execute("COMMIT;")
3512
- except Exception:
3513
- conn.execute("ROLLBACK;")
3514
- raise
3515
3589
 
3516
3590
 
3517
3591
  def _json_column(raw):
@@ -3670,7 +3744,8 @@ def _clean_project_tool_id(raw, label: str) -> str:
3670
3744
  return clean
3671
3745
 
3672
3746
 
3673
- def _validate_project_prompt(prompt) -> str | None:
3747
+ def validate_project_prompt(prompt) -> str | None:
3748
+ """systemDataPrompt de un proyecto (o de --run-file): texto acotado sin espacios alrededor, o None."""
3674
3749
  if prompt is None:
3675
3750
  return None
3676
3751
  if not isinstance(prompt, str):
@@ -3711,7 +3786,7 @@ def _validate_project_browser(browser) -> str:
3711
3786
 
3712
3787
 
3713
3788
  _PROJECT_ENV_VALIDATORS = {
3714
- "systemDataPrompt": _validate_project_prompt,
3789
+ "systemDataPrompt": validate_project_prompt,
3715
3790
  "enabledTools": _validate_enabled_tools,
3716
3791
  "mcpServers": lambda raw: _validate_project_id_list(raw, "mcpServers", MAX_PROJECT_MCP_SERVERS),
3717
3792
  "browser": _validate_project_browser,
@@ -3743,9 +3818,7 @@ def _row_to_project_environment(row) -> dict:
3743
3818
 
3744
3819
  def get_project_environment(project_key: str) -> dict:
3745
3820
  """Devuelve el entorno guardado del proyecto (`general` usa get_no_project_dir()), o los valores base."""
3746
- clean_key = str(project_key or "").strip()
3747
- if not clean_key:
3748
- raise ValueError("project_key es obligatorio")
3821
+ clean_key = clean_project_key(project_key)
3749
3822
  with open_storage() as conn:
3750
3823
  row = conn.execute(
3751
3824
  "SELECT config_json, updated_at FROM project_environments WHERE project_key = ?;",
@@ -3756,15 +3829,11 @@ def get_project_environment(project_key: str) -> dict:
3756
3829
 
3757
3830
  def save_project_environment(project_key: str, raw_patch: dict) -> dict:
3758
3831
  """Actualiza atómicamente en SQLite el entorno de ejecución guardado del proyecto."""
3759
- clean_key = str(project_key or "").strip()
3760
- if not clean_key:
3761
- raise ValueError("project_key es obligatorio")
3832
+ clean_key = clean_project_key(project_key)
3762
3833
  patch = validate_project_environment_patch(raw_patch)
3763
3834
  now = int(time.time() * 1000)
3764
3835
  with open_storage() as conn:
3765
- conn.isolation_level = None
3766
- conn.execute("BEGIN IMMEDIATE;")
3767
- try:
3836
+ with _immediate_transaction(conn):
3768
3837
  row = conn.execute(
3769
3838
  "SELECT config_json, updated_at FROM project_environments WHERE project_key = ?;",
3770
3839
  (clean_key,),
@@ -3778,11 +3847,7 @@ def save_project_environment(project_key: str, raw_patch: dict) -> dict:
3778
3847
  config_json = excluded.config_json,
3779
3848
  updated_at = excluded.updated_at;
3780
3849
  """, (clean_key, json.dumps(stored, ensure_ascii=False), now))
3781
- conn.execute("COMMIT;")
3782
3850
  return {**stored, "saved": True, "updatedAt": now}
3783
- except Exception:
3784
- conn.execute("ROLLBACK;")
3785
- raise
3786
3851
 
3787
3852
 
3788
3853
  MAX_PROJECT_SECRETS = 50
@@ -3790,10 +3855,7 @@ PROJECT_SECRET_NAME_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9_]{0,63}$")
3790
3855
 
3791
3856
 
3792
3857
  def project_secret_prefix(project_key: str) -> str:
3793
- clean_key = str(project_key or "").strip()
3794
- if not clean_key:
3795
- raise ValueError("project_key es obligatorio")
3796
- return f"project:{clean_key}:"
3858
+ return f"{project_security_policy_id(project_key)}:"
3797
3859
 
3798
3860
 
3799
3861
  def validate_project_secret_name(name) -> str:
@@ -3826,9 +3888,7 @@ def save_project_secret(project_key: str, name: str, value: str) -> list[str]:
3826
3888
  full_key = f"{prefix}{clean_name}"
3827
3889
  now = int(time.time() * 1000)
3828
3890
  with open_storage() as conn:
3829
- conn.isolation_level = None
3830
- conn.execute("BEGIN IMMEDIATE;")
3831
- try:
3891
+ with _immediate_transaction(conn):
3832
3892
  rows = conn.execute(
3833
3893
  "SELECT name FROM secrets WHERE substr(name, 1, ?) = ?;",
3834
3894
  (len(prefix), prefix),
@@ -3837,11 +3897,7 @@ def save_project_secret(project_key: str, name: str, value: str) -> list[str]:
3837
3897
  if full_key not in existing and len(existing) >= MAX_PROJECT_SECRETS:
3838
3898
  raise ValueError(f"Un proyecto no puede tener más de {MAX_PROJECT_SECRETS} secretos")
3839
3899
  _write_secret_on_conn(conn, full_key, clean_val, now)
3840
- conn.execute("COMMIT;")
3841
3900
  existing.add(full_key)
3842
- except Exception:
3843
- conn.execute("ROLLBACK;")
3844
- raise
3845
3901
  return sorted(key[len(prefix):] for key in existing)
3846
3902
 
3847
3903
 
@@ -3856,17 +3912,32 @@ def get_project_secret(project_key: str, name: str) -> str | None:
3856
3912
 
3857
3913
 
3858
3914
  def delete_project_storage(project_key: str) -> list[str]:
3859
- """Elimina entorno guardado, políticas de seguridad, secretos y conversaciones de un proyecto en SQLite."""
3860
- clean_key = str(project_key or "").strip()
3861
- if not clean_key:
3862
- raise ValueError("project_key es obligatorio")
3863
- deleted_ids = delete_project_conversations(clean_key)
3915
+ """
3916
+ Elimina en una sola transacción las conversaciones del proyecto (con sus blobs huérfanos y sus filas de
3917
+ `runs`), su entorno guardado, sus políticas de seguridad y sus secretos. Las filas de `runs` no guardan
3918
+ el proyecto: se cruzan por `conversation_id` con el proyecto de la conversación. Si alguna de esas
3919
+ ejecuciones sigue en marcha, no borra nada.
3920
+ """
3921
+ clean_key = clean_project_key(project_key)
3864
3922
  prefix = project_secret_prefix(clean_key)
3923
+ project_where = "json_extract(extra_json, '$.project') = ?"
3865
3924
  with open_storage() as conn:
3866
- conn.execute("DELETE FROM project_environments WHERE project_key = ?;", (clean_key,))
3867
- conn.execute("DELETE FROM security_policies WHERE id = ?;", (project_security_policy_id(clean_key),))
3868
- conn.execute("DELETE FROM secrets WHERE substr(name, 1, ?) = ?;", (len(prefix), prefix))
3869
- conn.commit()
3925
+ with _immediate_transaction(conn):
3926
+ running = conn.execute(
3927
+ f"SELECT 1 FROM runs WHERE status = 'running' AND conversation_id IN (SELECT id FROM conversations WHERE {project_where}) LIMIT 1;", # noqa: S608
3928
+ (clean_key,),
3929
+ ).fetchone()
3930
+ if running:
3931
+ raise ValueError("Detén los comandos y ejecuciones activas del proyecto antes de borrarlo.")
3932
+ conn.execute(
3933
+ f"DELETE FROM runs WHERE conversation_id IN (SELECT id FROM conversations WHERE {project_where});", # noqa: S608
3934
+ (clean_key,),
3935
+ )
3936
+ deleted_ids = _delete_conversations_in_transaction(conn, project_where, (clean_key,))
3937
+ conn.execute("DELETE FROM project_environments WHERE project_key = ?;", (clean_key,))
3938
+ conn.execute("DELETE FROM security_policies WHERE id = ?;", (project_security_policy_id(clean_key),))
3939
+ conn.execute("DELETE FROM secrets WHERE substr(name, 1, ?) = ?;", (len(prefix), prefix))
3940
+ notify_live_change()
3870
3941
  return deleted_ids
3871
3942
 
3872
3943
 
@@ -3880,9 +3951,7 @@ def has_nested_project_data(project_key: str) -> bool:
3880
3951
  if not clean_key:
3881
3952
  return False
3882
3953
  p_slash, p_back = f"{clean_key}/", f"{clean_key}\\"
3883
- pol_slash = f"{PROJECT_SECURITY_POLICY_PREFIX}{p_slash}"
3884
- pol_back = f"{PROJECT_SECURITY_POLICY_PREFIX}{p_back}"
3885
- sec_slash, sec_back = f"project:{p_slash}", f"project:{p_back}"
3954
+ prefixed_slash, prefixed_back = f"{PROJECT_KEY_PREFIX}{p_slash}", f"{PROJECT_KEY_PREFIX}{p_back}"
3886
3955
  with open_storage() as conn:
3887
3956
  if _has_prefix_match(
3888
3957
  conn,
@@ -3894,15 +3963,15 @@ def has_nested_project_data(project_key: str) -> bool:
3894
3963
  if _has_prefix_match(
3895
3964
  conn,
3896
3965
  "SELECT 1 FROM security_policies WHERE substr(id, 1, ?) = ? OR substr(id, 1, ?) = ? LIMIT 1;",
3897
- pol_slash,
3898
- pol_back,
3966
+ prefixed_slash,
3967
+ prefixed_back,
3899
3968
  ):
3900
3969
  return True
3901
3970
  if _has_prefix_match(
3902
3971
  conn,
3903
3972
  "SELECT 1 FROM secrets WHERE substr(name, 1, ?) = ? OR substr(name, 1, ?) = ? LIMIT 1;",
3904
- sec_slash,
3905
- sec_back,
3973
+ prefixed_slash,
3974
+ prefixed_back,
3906
3975
  ):
3907
3976
  return True
3908
3977
  if _has_prefix_match(
@@ -3927,7 +3996,7 @@ def has_nested_project_data(project_key: str) -> bool:
3927
3996
  # Modo del usuario: su Chrome, Edge o Chromium mediante la extensión de Playwright (--extension).
3928
3997
  BROWSER_MODES = ("own", "user")
3929
3998
  OWN_BROWSER_ENGINES = ("chromium", "firefox", "webkit")
3930
- OWN_SYSTEM_ENGINES = ("chrome", "msedge")
3999
+ OWN_SYSTEM_ENGINES = ("chrome", "msedge", "system-chromium")
3931
4000
  ALL_OWN_ENGINES = (*OWN_BROWSER_ENGINES, *OWN_SYSTEM_ENGINES)
3932
4001
  USER_BROWSERS = ("chrome", "msedge", "chromium")
3933
4002
  USER_AGENT_MODES = ("auto", "rotate", "custom")
@@ -3961,6 +4030,8 @@ MODERN_USER_AGENTS = (
3961
4030
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",
3962
4031
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0",
3963
4032
  )
4033
+ # User-Agent por defecto de las salidas web y de los motores propios hasta que el frontend fija el suyo.
4034
+ DEFAULT_USER_AGENT = MODERN_USER_AGENTS[0]
3964
4035
 
3965
4036
 
3966
4037
  def own_browser_profile_dir(engine: str) -> Path:
@@ -4034,6 +4105,13 @@ def chromium_install() -> tuple[str, Path] | None:
4034
4105
  return (executable, data_dir) if executable and os.path.isfile(executable) else None
4035
4106
 
4036
4107
 
4108
+ def _require_chromium_install() -> tuple[str, Path]:
4109
+ install = chromium_install()
4110
+ if not install:
4111
+ raise RuntimeError("No se encuentra Chromium en el sistema: elige otro navegador en Ajustes › Navegador.")
4112
+ return install
4113
+
4114
+
4037
4115
  def playwright_launch_args(config: dict, user_agent: str | None = None) -> list[str]:
4038
4116
  """Argumentos de Playwright MCP para la configuración del navegador."""
4039
4117
  if config["mode"] == "user":
@@ -4042,12 +4120,13 @@ def playwright_launch_args(config: dict, user_agent: str | None = None) -> list[
4042
4120
  return ["--extension", f"--browser={config['userBrowser']}"]
4043
4121
  # Chromium no es un canal de Playwright: se da su ejecutable y su perfil, con el canal chrome
4044
4122
  # para que no lo lance sin sandbox si no está abierto.
4045
- install = chromium_install()
4046
- if not install:
4047
- raise RuntimeError("No se encuentra Chromium en el sistema: elige otro navegador en Ajustes › Navegador.")
4048
- executable, data_dir = install
4123
+ executable, data_dir = _require_chromium_install()
4049
4124
  return ["--extension", "--browser=chrome", f"--executable-path={executable}", f"--user-data-dir={data_dir}"]
4050
- args = [f"--browser={config['engine']}", "--isolated"]
4125
+ if config["engine"] == "system-chromium":
4126
+ executable, _ = _require_chromium_install()
4127
+ args = ["--browser=chrome", "--isolated", f"--executable-path={executable}"]
4128
+ else:
4129
+ args = [f"--browser={config['engine']}", "--isolated"]
4051
4130
  # El motor propio usa el User-Agent de ZeroChat; en modo user lo pone el navegador del usuario.
4052
4131
  if user_agent:
4053
4132
  args.append(f"--user-agent={user_agent}")
@@ -4072,7 +4151,7 @@ def _playwright_launch(service_user_agent: str | None = None) -> tuple[list[str]
4072
4151
 
4073
4152
  # User-Agent que usan los motores propios de Playwright; lo fija el servidor con el User-Agent
4074
4153
  # activo de las salidas web (web/fetch) para que ambos compartan el mismo fingerprint.
4075
- SERVICE_USER_AGENT: str | None = None
4154
+ SERVICE_USER_AGENT: str | None = DEFAULT_USER_AGENT
4076
4155
  _FRONTEND_USER_AGENT_CAPTURED: bool = False
4077
4156
 
4078
4157
 
@@ -4088,12 +4167,10 @@ def load_last_frontend_user_agent() -> str | None:
4088
4167
  stored = get_setting(LAST_FRONTEND_USER_AGENT_KEY)
4089
4168
  except (OSError, ValueError, TypeError, sqlite3.Error):
4090
4169
  return None
4091
- if not isinstance(stored, str):
4092
- return None
4093
- cleaned = stored.strip()
4094
- if not cleaned or len(cleaned) > USER_AGENT_MAX_LEN or any(ch in cleaned for ch in ("\r", "\n", "\x00")):
4170
+ try:
4171
+ return _validate_user_agent(stored) or None
4172
+ except ValueError:
4095
4173
  return None
4096
- return cleaned
4097
4174
 
4098
4175
 
4099
4176
  def save_last_frontend_user_agent(user_agent: str) -> None:
@@ -5124,10 +5201,14 @@ RUN_EXPORT_FORMATS = {".md": "markdown", ".json": "json", ".html": "html"}
5124
5201
  RUN_EXPORT_MAX_BODY_BYTES = 64 * 1024 * 1024
5125
5202
  # Petición de --run-file: lo que quien lanza la ejecución fija en ella. Nunca lleva permisos, herramientas ni servicios
5126
5203
  # MCP, que salen siempre del entorno guardado del proyecto, así que no puede ampliarlos.
5127
- RUN_FILE_TEXT_KEYS = ("conversation_id", "prompt", "profile")
5204
+ RUN_FILE_TEXT_KEYS = ("conversation_id", "prompt", "profile", "agent")
5128
5205
  # Límites opcionales de la ejecución: llamadas al modelo y segundos desde el arranque del proceso, con su máximo.
5129
5206
  RUN_FILE_LIMIT_KEYS = {"maxSteps": 1000, "timeout": 24 * 60 * 60}
5130
- RUN_FILE_KEYS = frozenset(RUN_FILE_TEXT_KEYS + ("systemDataPrompt",) + tuple(RUN_FILE_LIMIT_KEYS))
5207
+ RUN_FILE_KEYS = frozenset(RUN_FILE_TEXT_KEYS + ("systemDataPrompt", "projectMode", "watchAgents") + tuple(RUN_FILE_LIMIT_KEYS))
5208
+ # Lo que una conversación de agente guarda de su lanzamiento (además del perfil) y repite al continuarla.
5209
+ RUN_LAUNCH_KEYS = ("systemDataPrompt", "projectMode", "watchAgents") + tuple(RUN_FILE_LIMIT_KEYS)
5210
+ # Patrones de watchAgents que admite una ejecución (agentes que vigila con check_agents).
5211
+ MAX_WATCH_AGENTS = 32
5131
5212
  # El prompt acaba en la conversación, que se guarda por HTTP: no cabe uno mayor que el cuerpo admitido.
5132
5213
  RUN_FILE_MAX_BYTES = MAX_HTTP_BODY_BYTES
5133
5214
 
@@ -5155,6 +5236,20 @@ def _run_request_object(raw: bytes) -> dict:
5155
5236
  return data
5156
5237
 
5157
5238
 
5239
+ def _agent_options(data: dict) -> dict:
5240
+ """projectMode (sin él, --run-file no inyecta AGENTS.md ni .zerochat/state.md: el agente sigue su propio manual) y
5241
+ watchAgents (los agentes del mismo proyecto que la ejecución puede consultar con check_agents)."""
5242
+ if "projectMode" in data and not isinstance(data["projectMode"], bool):
5243
+ raise ValueError("projectMode debe ser true o false")
5244
+ options = {"projectMode": data.get("projectMode", False)}
5245
+ if "watchAgents" in data:
5246
+ patterns = data["watchAgents"]
5247
+ if not isinstance(patterns, list) or not 1 <= len(patterns) <= MAX_WATCH_AGENTS:
5248
+ raise ValueError(f"watchAgents debe ser una lista de 1 a {MAX_WATCH_AGENTS} patrones")
5249
+ options["watchAgents"] = list(dict.fromkeys(validate_agent_watch_pattern(pattern) for pattern in patterns))
5250
+ return options
5251
+
5252
+
5158
5253
  def parse_run_request(raw: bytes) -> dict:
5159
5254
  """Valida el contenido de --run-file y devuelve sus campos limpios; ValueError con el motivo si no vale."""
5160
5255
  data = _run_request_object(raw)
@@ -5167,10 +5262,13 @@ def parse_run_request(raw: bytes) -> dict:
5167
5262
  request[key] = value.strip()
5168
5263
  if "conversation_id" in request:
5169
5264
  request["conversation_id"] = _validate_conversation_id(request["conversation_id"])
5265
+ if "agent" in request:
5266
+ request["agent"] = validate_agent_id(request["agent"])
5170
5267
  if "systemDataPrompt" in data:
5171
5268
  if not isinstance(data["systemDataPrompt"], str):
5172
5269
  raise ValueError("systemDataPrompt debe ser un texto")
5173
- request["systemDataPrompt"] = _validate_project_prompt(data["systemDataPrompt"])
5270
+ request["systemDataPrompt"] = validate_project_prompt(data["systemDataPrompt"])
5271
+ request.update(_agent_options(data))
5174
5272
  for key, maximum in RUN_FILE_LIMIT_KEYS.items():
5175
5273
  if key in data:
5176
5274
  value = data[key]
@@ -5337,7 +5435,9 @@ def _run_target(params: dict) -> tuple[str, dict, str]:
5337
5435
  conv = get_conversation(clean_conv_id)
5338
5436
  if conv is None:
5339
5437
  raise ValueError(f"Conversación '{clean_conv_id}' no encontrada.")
5340
- profile = params.get("profile")
5438
+ # Una conversación de agente se reanuda con el perfil de su lanzamiento, no con el que pida la interfaz.
5439
+ launch = get_conversation_launch(clean_conv_id) if conv.get("agent") else None
5440
+ profile = (launch or {}).get("profile") or params.get("profile")
5341
5441
  if not isinstance(profile, str) or not profile.strip():
5342
5442
  conv_profile = conv.get("profileId")
5343
5443
  if not isinstance(conv_profile, str) or not conv_profile.strip():
@@ -5450,7 +5550,9 @@ class RunSession:
5450
5550
  conversation_id: str | None = None, run_id: str | None = None,
5451
5551
  tool_security: dict | None = None, profile_data: dict | None = None,
5452
5552
  new_conversation_id: str | None = None, system_data_prompt: str | None = None,
5453
- max_steps: int | None = None, timeout_seconds: int | None = None):
5553
+ max_steps: int | None = None, timeout_seconds: int | None = None, project_mode: bool | None = None,
5554
+ agent: str | None = None, launch: dict | None = None, watch_agents: tuple[str, ...] = (),
5555
+ track_run: bool = False):
5454
5556
  env_run_id = os.environ.get("ZEROCHAT_RUN_ID", "").strip()
5455
5557
  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))
5456
5558
  self.conversation_id = conversation_id
@@ -5459,11 +5561,20 @@ class RunSession:
5459
5561
  # en ninguna otra.
5460
5562
  self.new_conversation_id = None if conversation_id else (new_conversation_id or f"session_{uuid.uuid4()}")
5461
5563
  # Conversación cuyo estado se guarda en la tabla runs: la que indicó quien lanzó la ejecución (--conversation o
5462
- # --run-file), que es quien la sigue; una nueva con id del servidor no la sigue nadie.
5463
- self.state_conversation_id = conversation_id or new_conversation_id
5564
+ # --run-file), o cualquier ejecución con agent / --run-file aunque cree id nuevo; un --prompt suelto no deja fila.
5565
+ self.state_conversation_id = conversation_id or new_conversation_id or (self.new_conversation_id if (agent or track_run) else None)
5464
5566
  self.prompt = prompt
5465
5567
  # systemDataPrompt de --run-file: sustituye al del proyecto solo en esta ejecución (run_project_environment).
5466
5568
  self.system_data_prompt = system_data_prompt
5569
+ # agent de --run-file: marca la conversación nueva como de ese agente (run_conversation_meta).
5570
+ self.agent = agent
5571
+ # Petición de lanzamiento de un agente (--run-file): finish_run la guarda en su conversación.
5572
+ self.launch = launch
5573
+ # watchAgents de --run-file: habilita y autoriza check_agents solo en esta ejecución.
5574
+ self.watch_agents = tuple(watch_agents)
5575
+ # projectMode de --run-file: si el runner inyecta las normas y el estado del proyecto; None (--prompt y
5576
+ # --conversation) deja el modo proyecto por defecto del runner.
5577
+ self.project_mode = project_mode
5467
5578
  # Límites de --run-file: el de pasos lo aplica el bucle del runner y el de tiempo, run_supervisor.
5468
5579
  self.max_steps = max_steps
5469
5580
  self.timeout_seconds = timeout_seconds
@@ -5530,11 +5641,16 @@ class RunSession:
5530
5641
  self.status = "limit"
5531
5642
  self.error = message
5532
5643
  write_run_state(self)
5533
- wake = self._wake
5644
+ self.signal_finished()
5645
+ return True
5646
+
5647
+ def signal_finished(self) -> None:
5648
+ """Marca la ejecución como terminada y despierta a quien la espera con set_wake_event."""
5534
5649
  self.finished.set()
5650
+ with self.lock:
5651
+ wake = self._wake
5535
5652
  if wake is not None:
5536
5653
  wake.set()
5537
- return True
5538
5654
 
5539
5655
  def take_approved_call(self, tool_name: str, args: dict) -> bool:
5540
5656
  """Si es la llamada que la persona aprobó en la tarjeta pausada (mismo nombre y argumentos), la consume:
@@ -5569,6 +5685,26 @@ def run_project_environment(env: dict) -> dict:
5569
5685
  return {**env, "systemDataPrompt": session.system_data_prompt}
5570
5686
 
5571
5687
 
5688
+ def run_conversation_meta(session_meta):
5689
+ """La cabecera de una conversación que se guarda en una ejecución: añade `agent` a la nueva y, si tiene `launch`
5690
+ (--run-file con agente, nueva o continuada), incluye `launch`, `serverRun` y `profileId` desde el primer guardado."""
5691
+ session = RUN_SESSION
5692
+ if session is None or not isinstance(session_meta, dict):
5693
+ return session_meta
5694
+ target_id = session.conversation_id or session.new_conversation_id
5695
+ if not target_id or session_meta.get("id") != target_id:
5696
+ return session_meta
5697
+ patched = dict(session_meta)
5698
+ if session.agent and session_meta.get("id") == session.new_conversation_id:
5699
+ patched["agent"] = session.agent
5700
+ if session.launch:
5701
+ patched["launch"] = session.launch
5702
+ patched["serverRun"] = True
5703
+ if session.profile:
5704
+ patched["profileId"] = session.profile
5705
+ return patched
5706
+
5707
+
5572
5708
  def http_body_limit() -> int:
5573
5709
  """Tope del cuerpo que se lee: el general, o el de la exportación mientras se espera (ff-server
5574
5710
  rechaza después cualquier otro método que supere el general)."""
@@ -5614,7 +5750,7 @@ def _rpc_prompt(params: dict, session: RunSession) -> RpcOutcome:
5614
5750
  # Para switch_model, que busca por nombre: el runner no puede listar los perfiles con su credencial.
5615
5751
  # El listado no lleva API keys; la del que active la pide con zerochat/run/profile.
5616
5752
  "profiles": list_general_profiles(),
5617
- "export": export_format, "max_steps": session.max_steps})
5753
+ "export": export_format, "max_steps": session.max_steps, "project_mode": session.project_mode})
5618
5754
 
5619
5755
 
5620
5756
  def _rpc_profile(params: dict, session: RunSession) -> RpcOutcome:
@@ -5698,10 +5834,7 @@ def _rpc_result(params: dict, session: RunSession) -> RpcOutcome:
5698
5834
  session.status = "error"
5699
5835
  session.error = error
5700
5836
  write_run_state(session)
5701
- session.finished.set()
5702
- with session.lock:
5703
- if session._wake is not None:
5704
- session._wake.set()
5837
+ session.signal_finished()
5705
5838
  return rpc_result({"ok": True})
5706
5839
 
5707
5840
 
@@ -5880,11 +6013,15 @@ def _rpc_save_conversation(params: dict) -> RpcOutcome:
5880
6013
  if not isinstance(params, dict):
5881
6014
  raise ValueError("Los parámetros deben ser un objeto")
5882
6015
  upload_id = params.get("uploadId")
6016
+ raw_conv = params.get("conversation")
6017
+ if isinstance(raw_conv, dict) and "launch" in raw_conv:
6018
+ raw_conv = {k: v for k, v in raw_conv.items() if k != "launch"}
6019
+ conversation = run_conversation_meta(raw_conv)
5883
6020
  if upload_id is not None:
5884
6021
  if params.get("messages") is not None:
5885
6022
  raise ValueError("No se puede combinar uploadId y messages")
5886
- return rpc_result({"conversation": commit_conversation_upload(params.get("conversation"), upload_id)})
5887
- return rpc_result({"conversation": save_conversation(params.get("conversation"), params.get("messages"))})
6023
+ return rpc_result({"conversation": commit_conversation_upload(conversation, upload_id)})
6024
+ return rpc_result({"conversation": save_conversation(conversation, params.get("messages"))})
5888
6025
 
5889
6026
 
5890
6027
  def _rpc_rename_conversation(params: dict) -> RpcOutcome:
@@ -5899,6 +6036,7 @@ CONVERSATION_METHODS = {
5899
6036
  "zerochat/conversations/get": lambda params: rpc_result({"conversation": get_conversation(params.get("id"))}),
5900
6037
  "zerochat/conversations/save": _rpc_save_conversation,
5901
6038
  "zerochat/conversations/save_chunk": lambda params: rpc_result(save_conversation_chunk(params)),
6039
+ "zerochat/conversations/cancel_upload": lambda params: rpc_result(cancel_conversation_upload(params)),
5902
6040
  "zerochat/conversations/rename": _rpc_rename_conversation,
5903
6041
  "zerochat/conversations/delete": _rpc_delete_conversations,
5904
6042
  }
@@ -5987,6 +6125,100 @@ def _atomic_write_text(target: Path, text: str):
5987
6125
  f.write(text)
5988
6126
  temp_path.replace(target)
5989
6127
 
6128
+ # --- tools.agents ---
6129
+ """check_agents: estado de los agentes que vigila un agente master, solo en la ejecución --run-file con watchAgents.
6130
+
6131
+ Lee conversaciones y ejecuciones de SQLite filtrando estrictamente por el proyecto de la ejecución y por los patrones de
6132
+ watchAgents: nunca chats humanos (sin agent) ni conversaciones de otros proyectos.
6133
+ """
6134
+
6135
+
6136
+
6137
+
6138
+ AGENTS_TOOL = "check_agents"
6139
+ # Resumen de la respuesta final de cada agente en el listado.
6140
+ AGENT_RESULT_SUMMARY_CHARS = 500
6141
+ # Texto de los mensajes del último turno que devuelve el detalle, entre todos.
6142
+ AGENT_TURN_MAX_CHARS = 20000
6143
+
6144
+
6145
+ def _clip(text: str, limit: int) -> tuple[str, bool]:
6146
+ return (text, False) if len(text) <= limit else (text[:limit], True)
6147
+
6148
+
6149
+ def _conversation_project(ctx: SecurityContext) -> str:
6150
+ """El proyecto de las conversaciones de esta ejecución: su carpeta, o vacío en la carpeta general."""
6151
+ return "" if ctx.key == normalize_directory_path(str(get_no_project_dir())) else ctx.key
6152
+
6153
+
6154
+ def _watched_conversations(ctx: SecurityContext, patterns: tuple[str, ...], own_id: str) -> list[dict]:
6155
+ """Conversaciones de agentes vigilados del proyecto, de la más reciente a la más antigua, sin la del propio master."""
6156
+ project = _conversation_project(ctx)
6157
+ return [conv for conv in list_conversations()
6158
+ if conv["id"] != own_id and (conv.get("project") or "") == project and agent_matches(conv.get("agent"), patterns)]
6159
+
6160
+
6161
+ def _agent_state(conv: dict) -> dict:
6162
+ """Estado de la última ejecución de una conversación de agente, con la respuesta final resumida."""
6163
+ run = get_run_state(conv["id"]) or {}
6164
+ result, clipped = _clip(run.get("result_text") or "", AGENT_RESULT_SUMMARY_CHARS)
6165
+ return {
6166
+ "agent": conv["agent"],
6167
+ "conversation_id": conv["id"],
6168
+ "status": run.get("status"),
6169
+ "updated_at": run.get("updated_at") or conv.get("updatedAt"),
6170
+ "finished_at": run.get("finished_at"),
6171
+ "step_text": run.get("step_text") or "",
6172
+ "pending": run.get("pending"),
6173
+ "error": run.get("error"),
6174
+ "warnings": run.get("warnings") or [],
6175
+ "result_text": result,
6176
+ **({"result_truncated": True} if clipped else {}),
6177
+ }
6178
+
6179
+
6180
+ def _last_turn(history: list[dict]) -> tuple[list[dict], bool]:
6181
+ """Mensajes desde el último del usuario, con AGENT_TURN_MAX_CHARS de texto entre todos; True si se recortó."""
6182
+ start = max((index for index, message in enumerate(history) if message.get("role") == "user"), default=0)
6183
+ budget, truncated, messages = AGENT_TURN_MAX_CHARS, False, []
6184
+ for message in history[start:]:
6185
+ content, clipped = _clip("" if message.get("content") is None else str(message["content"]), budget)
6186
+ budget -= len(content)
6187
+ truncated = truncated or clipped
6188
+ entry = {"role": message.get("role"), "content": content}
6189
+ if message.get("name"):
6190
+ entry["name"] = message["name"]
6191
+ calls = [call.get("function", {}).get("name") for call in message.get("tool_calls") or [] if isinstance(call, dict)]
6192
+ if calls:
6193
+ entry["tool_calls"] = calls
6194
+ messages.append(entry)
6195
+ return messages, truncated
6196
+
6197
+
6198
+ def check_agents(agent: str | None = None, conversation_id: str | None = None, ctx: SecurityContext | None = None) -> str:
6199
+ """Sin argumentos, el estado de cada agente vigilado (su conversación más reciente); con agent o conversation_id,
6200
+ además los mensajes de su último turno."""
6201
+ session = current_run_session()
6202
+ patterns = session.watch_agents if session is not None else ()
6203
+ if not patterns or ctx is None:
6204
+ return _tool_error("check_agents is only available in a --run-file run with watchAgents.")
6205
+ convs = _watched_conversations(ctx, patterns, session.conversation_id or session.new_conversation_id or "")
6206
+ if conversation_id is None and agent is None:
6207
+ latest: dict[str, dict] = {}
6208
+ for conv in convs:
6209
+ latest.setdefault(conv["agent"], conv)
6210
+ return json.dumps({"success": True, "agents": [_agent_state(conv) for conv in latest.values()]}, ensure_ascii=False)
6211
+ if conversation_id is not None:
6212
+ conv = next((item for item in convs if item["id"] == conversation_id), None)
6213
+ else:
6214
+ conv = next((item for item in convs if item["agent"] == agent), None)
6215
+ if conv is None:
6216
+ return _tool_error("That agent or conversation is not a watched agent of this project.")
6217
+ full = get_conversation(conv["id"]) or {}
6218
+ messages, truncated = _last_turn(full.get("history") or [])
6219
+ return json.dumps({"success": True, **_agent_state(conv), "last_turn": messages,
6220
+ **({"last_turn_truncated": True} if truncated else {})}, ensure_ascii=False)
6221
+
5990
6222
  # --- tools.browser_action ---
5991
6223
  """Herramienta browser_action: una sesión persistente de Playwright con los motores propios o el navegador del sistema."""
5992
6224
 
@@ -7816,6 +8048,17 @@ class ProjectSession:
7816
8048
  return self.tools if kind == "tools" else self.servers
7817
8049
 
7818
8050
 
8051
+ @dataclasses.dataclass(frozen=True)
8052
+ class PolicyPatch:
8053
+ """Parche de políticas ya validado; None en un apartado es «no cambiar»."""
8054
+ allow_all: bool | None = None
8055
+ directory_rules: list[str] | None = None
8056
+ tools: dict | None = None
8057
+ servers: dict | None = None
8058
+ added_rules: list[str] = dataclasses.field(default_factory=list)
8059
+ command_patterns: dict | None = None
8060
+
8061
+
7819
8062
  class AccessController:
7820
8063
  """Motor de control de acceso y autorización del backend (PDP/PEP)."""
7821
8064
 
@@ -7997,7 +8240,7 @@ class AccessController:
7997
8240
  if total > MAX_POLICY_ENTRIES:
7998
8241
  raise ValueError(f"El número total de entradas ({total}) supera el máximo permitido ({MAX_POLICY_ENTRIES}).")
7999
8242
 
8000
- def _validate_state_payload(self, state: dict, scope: str) -> tuple[bool | None, list[str] | None, dict | None, dict | None]:
8243
+ def _validate_state_payload(self, state: dict, scope: str) -> PolicyPatch:
8001
8244
  if not isinstance(state, dict):
8002
8245
  raise ValueError("El estado de políticas debe ser un diccionario.")
8003
8246
 
@@ -8010,7 +8253,7 @@ class AccessController:
8010
8253
  clean_rules = self._validate_directory_rules(state["directoryRules"]) if "directoryRules" in state else None
8011
8254
  clean_tools = self._validate_policy_entries(state["tools"], "tools", scope) if "tools" in state else None
8012
8255
  clean_servers = self._validate_policy_entries(state["servers"], "servers", scope) if "servers" in state else None
8013
- return clean_allow_all, clean_rules, clean_tools, clean_servers
8256
+ return PolicyPatch(allow_all=clean_allow_all, directory_rules=clean_rules, tools=clean_tools, servers=clean_servers)
8014
8257
 
8015
8258
  @staticmethod
8016
8259
  def _validate_command_patterns_patch(raw) -> dict:
@@ -8028,49 +8271,49 @@ class AccessController:
8028
8271
  `addDirectoryRules` añade reglas a las guardadas dentro de la misma transacción y
8029
8272
  `commandPatterns` sustituye los patrones globales y del proyecto actual sin tocar otros proyectos.
8030
8273
  """
8031
- clean_allow_all, clean_rules, clean_tools, clean_servers = self._validate_state_payload(state, SCOPE_PERMANENT)
8032
- added_rules = self._validate_directory_rules(state["addDirectoryRules"]) if "addDirectoryRules" in state else []
8033
- clean_patterns = self._validate_command_patterns_patch(state["commandPatterns"]) if "commandPatterns" in state else None
8034
-
8035
- project = context.key
8274
+ patch = dataclasses.replace(
8275
+ self._validate_state_payload(state, SCOPE_PERMANENT),
8276
+ added_rules=self._validate_directory_rules(state["addDirectoryRules"]) if "addDirectoryRules" in state else [],
8277
+ command_patterns=self._validate_command_patterns_patch(state["commandPatterns"]) if "commandPatterns" in state else None,
8278
+ )
8036
8279
  default_rule = self.get_default_directory_rule(context)
8037
8280
 
8038
8281
  def mutator(global_state: dict, project_state: dict) -> None:
8039
- self._apply_state_patch(global_state, project_state, default_rule, clean_allow_all, clean_rules, added_rules, clean_tools, clean_servers, clean_patterns)
8282
+ self._apply_state_patch(global_state, project_state, default_rule, patch)
8040
8283
  self._update_permanent(context, mutator)
8041
- self._forget_session_overrides(project, clean_allow_all, clean_rules, added_rules, clean_tools, clean_servers)
8284
+ self._forget_session_overrides(context.key, patch)
8042
8285
  return self.export_state(context)
8043
8286
 
8044
- def _apply_state_patch(self, global_state: dict, project_state: dict, default_rule: str, clean_allow_all, clean_rules, added_rules, clean_tools, clean_servers, clean_patterns):
8287
+ def _apply_state_patch(self, global_state: dict, project_state: dict, default_rule: str, patch: PolicyPatch):
8045
8288
  """Aplica sobre el estado guardado los apartados del parche que vienen (None es «no cambiar»)."""
8046
- if clean_allow_all is not None:
8047
- project_state["allowAll"] = clean_allow_all
8048
- if clean_rules is not None:
8049
- project_state["directoryRules"] = None if clean_rules == [default_rule] else clean_rules
8050
- if added_rules:
8289
+ if patch.allow_all is not None:
8290
+ project_state["allowAll"] = patch.allow_all
8291
+ if patch.directory_rules is not None:
8292
+ project_state["directoryRules"] = None if patch.directory_rules == [default_rule] else patch.directory_rules
8293
+ if patch.added_rules:
8051
8294
  base_rules = project_state["directoryRules"] if project_state["directoryRules"] is not None else [default_rule]
8052
- project_state["directoryRules"] = self._append_rules(base_rules, added_rules)
8053
- if clean_tools is not None:
8054
- global_state["tools"] = self._apply_entry_patch(global_state.get("tools"), clean_tools)
8055
- if clean_servers is not None:
8056
- global_state["servers"] = self._apply_entry_patch(global_state.get("servers"), clean_servers)
8057
- if clean_patterns is not None:
8058
- global_state["commandPatterns"] = clean_pattern_list(clean_patterns["global"], "commandPatterns.global")
8059
- project_state["commandPatterns"] = clean_pattern_list(clean_patterns["project"], "commandPatterns.project")
8060
-
8061
- def _forget_session_overrides(self, project: str, clean_allow_all, clean_rules, added_rules, clean_tools, clean_servers):
8295
+ project_state["directoryRules"] = self._append_rules(base_rules, patch.added_rules)
8296
+ if patch.tools is not None:
8297
+ global_state["tools"] = self._apply_entry_patch(global_state.get("tools"), patch.tools)
8298
+ if patch.servers is not None:
8299
+ global_state["servers"] = self._apply_entry_patch(global_state.get("servers"), patch.servers)
8300
+ if patch.command_patterns is not None:
8301
+ global_state["commandPatterns"] = clean_pattern_list(patch.command_patterns["global"], "commandPatterns.global")
8302
+ project_state["commandPatterns"] = clean_pattern_list(patch.command_patterns["project"], "commandPatterns.project")
8303
+
8304
+ def _forget_session_overrides(self, project: str, patch: PolicyPatch):
8062
8305
  """Lo guardado sustituye o revoca lo equivalente en la sesión (las reglas y permitir todo, solo en su proyecto)."""
8063
8306
  with self._lock:
8064
8307
  for key, session in self.sessions.items():
8065
8308
  if key == project:
8066
- if clean_allow_all is not None:
8309
+ if patch.allow_all is not None:
8067
8310
  session.allow_all = None
8068
- if clean_rules is not None:
8311
+ if patch.directory_rules is not None:
8069
8312
  session.directory_rules = None
8070
- elif added_rules and session.directory_rules is not None:
8071
- session.directory_rules = self._append_rules(session.directory_rules, added_rules)
8072
- for kind, patch in (("tools", clean_tools), ("servers", clean_servers)):
8073
- for item_id in patch or {}:
8313
+ elif patch.added_rules and session.directory_rules is not None:
8314
+ session.directory_rules = self._append_rules(session.directory_rules, patch.added_rules)
8315
+ for kind, entries in (("tools", patch.tools), ("servers", patch.servers)):
8316
+ for item_id in entries or {}:
8074
8317
  session.entries(kind).pop(item_id, None)
8075
8318
 
8076
8319
  @staticmethod
@@ -8095,19 +8338,19 @@ class AccessController:
8095
8338
  Aplica una capa de políticas temporal en memoria para una ejecución en servidor, sin persistir.
8096
8339
  De los patrones de comando solo toma los de sesión: los guardados se leen de la misma base de datos.
8097
8340
  """
8098
- clean_allow_all, clean_rules, clean_tools, clean_servers = self._validate_state_payload(state, SCOPE_SESSION)
8341
+ patch = self._validate_state_payload(state, SCOPE_SESSION)
8099
8342
  raw_patterns = state.get("commandPatterns")
8100
8343
  session_patterns = self._limit_patterns(clean_pattern_list(raw_patterns.get("session") or [], "commandPatterns.session")) \
8101
8344
  if isinstance(raw_patterns, dict) else None
8102
8345
 
8103
8346
  with self._lock:
8104
8347
  session = self._session(context)
8105
- rules = clean_rules if clean_rules is not None else session.directory_rules
8106
- tools = self._apply_entry_patch(session.tools, clean_tools or {})
8107
- servers = self._apply_entry_patch(session.servers, clean_servers or {})
8348
+ rules = patch.directory_rules if patch.directory_rules is not None else session.directory_rules
8349
+ tools = self._apply_entry_patch(session.tools, patch.tools or {})
8350
+ servers = self._apply_entry_patch(session.servers, patch.servers or {})
8108
8351
  self._check_entry_limit({"directoryRules": rules, "tools": tools, "servers": servers})
8109
- if clean_allow_all is not None:
8110
- session.allow_all = clean_allow_all
8352
+ if patch.allow_all is not None:
8353
+ session.allow_all = patch.allow_all
8111
8354
  session.directory_rules, session.tools, session.servers = rules, tools, servers
8112
8355
  if session_patterns is not None:
8113
8356
  session.command_patterns = session_patterns
@@ -9911,6 +10154,24 @@ LOCAL_TOOLS_DEFINITIONS = [
9911
10154
  }
9912
10155
  }
9913
10156
  ]
10157
+ # Solo se publica en una ejecución --run-file con watchAgents (server/rpc.py), que además la autoriza; fuera de ella
10158
+ # el manejador se niega a responder.
10159
+ CHECK_AGENTS_DEFINITION = {
10160
+ "name": AGENTS_TOOL,
10161
+ "description": (
10162
+ "Status of the agents of this project that this run supervises (watchAgents). Without arguments, one entry per "
10163
+ "agent with its latest conversation: status (running, needs_input, completed, error, limit), step, pending input, "
10164
+ "error, warnings and a summary of its final answer. With agent or conversation_id, also the messages of its last turn."
10165
+ ),
10166
+ "inputSchema": {
10167
+ "type": "object",
10168
+ "properties": {
10169
+ "agent": {"type": "string", "maxLength": MAX_AGENT_ID_LENGTH, "description": "Agent id <set>.<name>: details of its latest conversation"},
10170
+ "conversation_id": {"type": "string", "maxLength": MAX_CONVERSATION_ID_LENGTH, "description": "Details of this agent conversation"}
10171
+ }
10172
+ }
10173
+ }
10174
+
9914
10175
  LOCAL_TOOL_HANDLERS = {
9915
10176
  "list_directory": list_directory,
9916
10177
  "read_file": read_file,
@@ -9922,6 +10183,7 @@ LOCAL_TOOL_HANDLERS = {
9922
10183
  "get_diagnostics": get_diagnostics,
9923
10184
  "browser_action": browser_action,
9924
10185
  "browser_fill_secret": browser_fill_secret,
10186
+ AGENTS_TOOL: check_agents,
9925
10187
  }
9926
10188
 
9927
10189
 
@@ -9946,7 +10208,7 @@ def _argument_error(name: str, value, prop: dict | None) -> str | None:
9946
10208
 
9947
10209
  def validate_local_tool_arguments(tool_name: str, arguments: dict) -> str | None:
9948
10210
  """Valida tipos y límites de las herramientas locales a partir de su definición canónica."""
9949
- definition = next((item for item in LOCAL_TOOLS_DEFINITIONS if item["name"] == tool_name), None)
10211
+ definition = next((item for item in (*LOCAL_TOOLS_DEFINITIONS, CHECK_AGENTS_DEFINITION) if item["name"] == tool_name), None)
9950
10212
  if definition is None:
9951
10213
  return None
9952
10214
 
@@ -10276,32 +10538,35 @@ METADATA_HOSTS = frozenset({
10276
10538
  "instance-data",
10277
10539
  "100.100.100.200",
10278
10540
  })
10279
- DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
10280
10541
  # El User-Agent activo se sustituye por el de la primera petición del frontend (variabilidad de
10281
10542
  # fingerprint); sin frontend (--prompt/--conversation) se usa el último guardado o el por defecto.
10282
10543
  ACTIVE_USER_AGENT = DEFAULT_USER_AGENT
10544
+ # Último User-Agent real guardado en SQLite: se lee una sola vez por proceso, no en cada petición web.
10545
+ _STORED_USER_AGENT: str | None = None
10546
+ _STORED_USER_AGENT_LOADED = False
10283
10547
 
10284
10548
 
10285
10549
  def capture_frontend_user_agent(user_agent: str) -> None:
10286
10550
  """Adopta y persiste el User-Agent de la primera petición del frontend para las salidas web y Playwright."""
10287
- global ACTIVE_USER_AGENT
10551
+ global ACTIVE_USER_AGENT, _STORED_USER_AGENT, _STORED_USER_AGENT_LOADED
10288
10552
  cleaned = user_agent.strip() if isinstance(user_agent, str) else ""
10289
10553
  if ACTIVE_USER_AGENT is DEFAULT_USER_AGENT and cleaned:
10290
10554
  ACTIVE_USER_AGENT = cleaned
10291
10555
  set_service_user_agent(ACTIVE_USER_AGENT, from_frontend=True)
10292
10556
  save_last_frontend_user_agent(cleaned)
10557
+ _STORED_USER_AGENT, _STORED_USER_AGENT_LOADED = cleaned, True
10293
10558
 
10294
10559
 
10295
10560
  def effective_user_agent() -> str:
10296
10561
  """User-Agent activo del servidor o, en desatendido sin frontend, el último capturado del navegador."""
10562
+ global _STORED_USER_AGENT, _STORED_USER_AGENT_LOADED
10297
10563
  if ACTIVE_USER_AGENT is not DEFAULT_USER_AGENT:
10298
10564
  return ACTIVE_USER_AGENT
10299
- return load_last_frontend_user_agent() or DEFAULT_USER_AGENT
10565
+ if not _STORED_USER_AGENT_LOADED:
10566
+ _STORED_USER_AGENT, _STORED_USER_AGENT_LOADED = load_last_frontend_user_agent(), True
10567
+ return _STORED_USER_AGENT or DEFAULT_USER_AGENT
10300
10568
 
10301
10569
 
10302
- # Los motores propios de Playwright arrancan con el User-Agent por defecto hasta que el
10303
- # frontend fija el suyo en la primera petición.
10304
- set_service_user_agent(DEFAULT_USER_AGENT)
10305
10570
  WEB_FETCH_MAX_BYTES = 10 * 1024 * 1024
10306
10571
  WEB_FETCH_MAX_REDIRECTS = 5
10307
10572
  WEB_FETCH_READ_CHUNK = 64 * 1024
@@ -10507,7 +10772,10 @@ decide quién atiende cada uno.
10507
10772
 
10508
10773
 
10509
10774
  def _local_tools() -> list[dict]:
10510
- return [dict(definition) for definition in LOCAL_TOOLS_DEFINITIONS]
10775
+ """Las herramientas locales; check_agents, solo en la ejecución --run-file que vigila agentes (watchAgents)."""
10776
+ session = current_run_session()
10777
+ extra = (CHECK_AGENTS_DEFINITION,) if session is not None and session.watch_agents else ()
10778
+ return [dict(definition) for definition in (*LOCAL_TOOLS_DEFINITIONS, *extra)]
10511
10779
 
10512
10780
 
10513
10781
  def rpc_login(params: dict) -> RpcOutcome:
@@ -10600,12 +10868,8 @@ def _list_project_secrets(_params: dict, ctx: SecurityContext) -> RpcOutcome:
10600
10868
 
10601
10869
 
10602
10870
  def _set_project_secret(params: dict, ctx: SecurityContext) -> RpcOutcome:
10603
- name, value = params.get("name"), params.get("value")
10604
- if value is not None and not isinstance(value, str):
10605
- return rpc_error(INVALID_PARAMS, "value debe ser texto o null")
10606
10871
  try:
10607
- secrets = delete_project_secret(ctx.key, name) if value is None else save_project_secret(ctx.key, name, value)
10608
- return rpc_result({"secrets": secrets})
10872
+ return rpc_result({"secrets": save_project_secret(ctx.key, params.get("name"), params.get("value"))})
10609
10873
  except ValueError as exc:
10610
10874
  return rpc_error(INVALID_PARAMS, str(exc))
10611
10875
 
@@ -10621,18 +10885,20 @@ def _delete_project(params: dict, ctx: SecurityContext) -> RpcOutcome:
10621
10885
  try:
10622
10886
  delete_directory = bool(params.get("deleteDirectory"))
10623
10887
  confirm_path = str(params.get("confirmPath") or "").strip()
10624
- if JOBS.running(ctx.key) or any(run.get("project") == ctx.key and run.get("status") == "running" for run in list_run_states()):
10888
+ if JOBS.running(ctx.key):
10625
10889
  raise ValueError("Detén los comandos y ejecuciones activas del proyecto antes de borrarlo.")
10890
+ target = None
10626
10891
  if delete_directory:
10627
10892
  target = validate_deletable_project_dir(ctx)
10628
10893
  if confirm_path != ctx.key and confirm_path != str(target):
10629
10894
  raise ValueError("La ruta de confirmación no coincide con el directorio del proyecto.")
10630
10895
  if has_nested_project_data(ctx.key):
10631
10896
  raise ValueError("Existen subproyectos guardados dentro de este directorio: borra primero sus datos.")
10632
- if target.exists():
10633
- shutil.rmtree(target)
10634
- ACCESS_CONTROLLER.drop_project_session(ctx.key)
10897
+ # Primero los datos (atómico y con la comprobación de ejecuciones en marcha); el disco, solo si eso salió bien.
10635
10898
  deleted_ids = delete_project_storage(ctx.key)
10899
+ ACCESS_CONTROLLER.drop_project_session(ctx.key)
10900
+ if target is not None and target.exists():
10901
+ shutil.rmtree(target)
10636
10902
  return rpc_result({
10637
10903
  "deleted": ctx.key,
10638
10904
  "deletedDirectory": delete_directory,
@@ -11184,10 +11450,9 @@ def build_parser() -> ZeroChatArgumentParser:
11184
11450
  parser.add_argument("--no-venv", action="store_true", help="Omitir la comprobación/creación de ~/zerochat/.venv")
11185
11451
  parser.add_argument("--test", action="store_true", help="Ejecutar autocomprobación interna de herramientas")
11186
11452
  parser.add_argument("--list-profiles", action="store_true", help="Listar los perfiles de conexión generales almacenados en el servidor local")
11187
- parser.add_argument("--list-conversations", action="store_true", help="Listar las conversaciones almacenadas en el servidor local")
11188
11453
  parser.add_argument("--prompt", default=None, help="Ejecutar este prompt sin interfaz gráfica con Node.js, imprimir solo la respuesta final y terminar (salida 0 terminado, 1 error de generación, 2 runner cerrado sin resultado, 3 fallo de arranque, 4 argumentos no válidos, 5 pausada a la espera del usuario, con su pregunta en la salida, 6 límite de --run-file alcanzado)")
11189
11454
  parser.add_argument("--conversation", default=None, help="Con --prompt o para continuar, id de la conversación almacenada en SQLite")
11190
- parser.add_argument("--run-file", default=None, metavar="FICHERO", help="Ejecutar la petición del fichero JSON (- para leerla de stdin) en lugar de --prompt, --conversation y --profile: prompt, conversation_id (la continúa o, si no existe, la crea con ese id), profile, systemDataPrompt, maxSteps y timeout (segundos); exige un entorno de proyecto guardado, del que salen siempre herramientas y permisos")
11455
+ parser.add_argument("--run-file", default=None, metavar="FICHERO", help="Ejecutar la petición del fichero JSON (- para leerla de stdin) en lugar de --prompt, --conversation y --profile: prompt, conversation_id (la continúa o, si no existe, la crea con ese id), profile, agent (<subconjunto>.<nombre>: marca la conversación nueva como de ese agente), systemDataPrompt, watchAgents (patrones de agentes del proyecto que vigila con check_agents), projectMode (true inyecta AGENTS.md y .zerochat/state.md; por defecto no), maxSteps y timeout (segundos); exige un entorno de proyecto guardado, del que salen siempre herramientas y permisos")
11191
11456
  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)")
11192
11457
  parser.add_argument("--log", choices=("on", "off"), default=None, help="Mostrar la cabecera y el registro del servidor (default: on; off en modo ejecución)")
11193
11458
  parser.add_argument("--export", default=None, metavar="FICHERO", help=f"Con --prompt, --conversation o --run-file, guardar la conversación en FICHERO; el formato sale de la extensión ({', '.join(RUN_EXPORT_FORMATS)})")
@@ -11305,14 +11570,33 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
11305
11570
  raw_prompt, raw_conversation, raw_profile = args.prompt, args.conversation, args.profile
11306
11571
  prompt = _run_prompt(parser, raw_prompt)
11307
11572
  conversation_id, conv, new_conversation_id = _run_conversation(parser, raw_conversation, prompt, allow_new=args.run_file is not None)
11573
+ # El agente se fija al crear la conversación: continuarla con otro, o sin él, mezclaría historiales.
11574
+ if args.run_file is not None and conv is not None and conv.get("agent") != request.get("agent"):
11575
+ parser.error(f"la conversación '{conversation_id}' es del agente '{conv.get('agent') or '(ninguno)'}', no de "
11576
+ f"'{request.get('agent') or '(ninguno)'}'")
11577
+ # Continuar sin --run-file (la interfaz o --conversation) una conversación de agente repite su último lanzamiento:
11578
+ # su perfil, su manual (systemDataPrompt), su projectMode y sus límites, no los de quien la reanuda.
11579
+ options = request
11580
+ if args.run_file is None and conv is not None and conv.get("agent"):
11581
+ options = {"projectMode": False, "agent": conv["agent"], **(get_conversation_launch(conversation_id) or {})}
11582
+ launch_profile = options.get("profile")
11583
+ if launch_profile and raw_profile is not None and raw_profile.strip() != launch_profile:
11584
+ parser.error(f"la conversación '{conversation_id}' es del agente '{conv['agent']}' y se continúa con el perfil "
11585
+ f"de su lanzamiento, '{launch_profile}', no con '{raw_profile.strip()}'")
11586
+ raw_profile = launch_profile or raw_profile
11308
11587
  _check_run_flags(parser, args)
11309
11588
  profile_name, profile_data = _run_profile(parser, raw_profile, conv)
11310
11589
  export_path = _run_export_path(parser, args)
11311
11590
  if conversation_id and args.run_file is None:
11312
11591
  mark_conversation_server_run(conversation_id, profile_name)
11592
+ launch = None
11593
+ if args.run_file is not None and request.get("agent"):
11594
+ launch = {"profile": profile_name, **{key: request[key] for key in RUN_LAUNCH_KEYS if key in request}}
11313
11595
  return RunSession(prompt, profile_name, export_path, conversation_id=conversation_id, profile_data=profile_data,
11314
- new_conversation_id=new_conversation_id, system_data_prompt=request.get("systemDataPrompt"),
11315
- max_steps=request.get("maxSteps"), timeout_seconds=request.get("timeout"))
11596
+ new_conversation_id=new_conversation_id, system_data_prompt=options.get("systemDataPrompt"),
11597
+ max_steps=options.get("maxSteps"), timeout_seconds=options.get("timeout"),
11598
+ project_mode=options.get("projectMode"), agent=options.get("agent"), launch=launch,
11599
+ watch_agents=tuple(options.get("watchAgents") or ()), track_run=args.run_file is not None)
11316
11600
 
11317
11601
 
11318
11602
  def redirect_log(args):
@@ -11389,6 +11673,7 @@ def reset_session_authorizations():
11389
11673
  name: {"policy": POLICY_ALLOW}
11390
11674
  for name in LOCAL_TOOL_HANDLERS
11391
11675
  if name != COMMAND_TOOL
11676
+ and (name != AGENTS_TOOL or session.watch_agents)
11392
11677
  and not get_integrated_path_access(name)
11393
11678
  and (permanent_tools.get(name) or {}).get("policy") != POLICY_DENY
11394
11679
  }
@@ -11599,20 +11884,6 @@ def main():
11599
11884
  print(f"- {p['name']} ({api_type} / {model}) [{api_url}]")
11600
11885
  return
11601
11886
 
11602
- if getattr(args, "list_conversations", False):
11603
- conversations = list_conversations()
11604
- if not conversations:
11605
- print("No hay conversaciones almacenadas en el servidor local.")
11606
- else:
11607
- print("Conversaciones almacenadas:")
11608
- for c in conversations:
11609
- date_str = datetime.datetime.fromtimestamp(c["updatedAt"] / 1000).strftime("%Y-%m-%d %H:%M") if c.get("updatedAt") else ""
11610
- count = c.get("messageCount", 0)
11611
- msg_text = "1 mensaje" if count == 1 else f"{count} mensajes"
11612
- date_suffix = f", {date_str}" if date_str else ""
11613
- print(f"- [{c['id']}] {c['title']} ({msg_text}{date_suffix})")
11614
- return
11615
-
11616
11887
  if args.test:
11617
11888
  sys.exit(0 if run_self_test() else 1)
11618
11889
 
File without changes
File without changes
File without changes