zerochat 10.52.0__tar.gz → 10.53.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {zerochat-10.52.0/zerochat.egg-info → zerochat-10.53.0}/PKG-INFO +1 -1
- {zerochat-10.52.0 → zerochat-10.53.0}/pyproject.toml +1 -1
- {zerochat-10.52.0 → zerochat-10.53.0/zerochat.egg-info}/PKG-INFO +1 -1
- {zerochat-10.52.0 → zerochat-10.53.0}/zerochat.py +290 -127
- {zerochat-10.52.0 → zerochat-10.53.0}/LICENSE +0 -0
- {zerochat-10.52.0 → zerochat-10.53.0}/README.md +0 -0
- {zerochat-10.52.0 → zerochat-10.53.0}/setup.cfg +0 -0
- {zerochat-10.52.0 → zerochat-10.53.0}/zerochat.egg-info/SOURCES.txt +0 -0
- {zerochat-10.52.0 → zerochat-10.53.0}/zerochat.egg-info/dependency_links.txt +0 -0
- {zerochat-10.52.0 → zerochat-10.53.0}/zerochat.egg-info/entry_points.txt +0 -0
- {zerochat-10.52.0 → zerochat-10.53.0}/zerochat.egg-info/top_level.txt +0 -0
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "zerochat"
|
|
7
|
-
version = "10.
|
|
7
|
+
version = "10.53.0"
|
|
8
8
|
description = "Personal, private AI workspace and unattended agent runtime: web UI, local tools, MCP services and controller orchestration"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -518,6 +518,7 @@ RUNNER_ALLOWED_METHODS = frozenset({
|
|
|
518
518
|
"zerochat/jobs/stop",
|
|
519
519
|
"zerochat/heartbeat",
|
|
520
520
|
"zerochat/external/servers/start",
|
|
521
|
+
"zerochat/external/servers/wait",
|
|
521
522
|
"zerochat/external/servers/stop",
|
|
522
523
|
"zerochat/sandbox/execute",
|
|
523
524
|
})
|
|
@@ -1005,6 +1006,8 @@ def wait_pid_exit(pid: int, timeout: float | None) -> bool | None:
|
|
|
1005
1006
|
return _windows_wait_pid_exit(pid, timeout)
|
|
1006
1007
|
except ProcessLookupError:
|
|
1007
1008
|
return True
|
|
1009
|
+
except OSError:
|
|
1010
|
+
return None
|
|
1008
1011
|
|
|
1009
1012
|
|
|
1010
1013
|
def _windows_wait_pid_exit(pid: int, timeout: float | None) -> bool | None:
|
|
@@ -1171,7 +1174,7 @@ def parse_nonneg_int(value, label: str, default: int = 0) -> int:
|
|
|
1171
1174
|
|
|
1172
1175
|
|
|
1173
1176
|
|
|
1174
|
-
SOURCE_BACKEND_VERSION = "10.
|
|
1177
|
+
SOURCE_BACKEND_VERSION = "10.53.0"
|
|
1175
1178
|
|
|
1176
1179
|
|
|
1177
1180
|
def _read_source_version(filename: str) -> str | None:
|
|
@@ -1318,10 +1321,10 @@ CATALOG_SCHEMA_VERSION = 1
|
|
|
1318
1321
|
# Tope de cada descarga (el catálogo y cada fichero): los de ahora ocupan unos pocos KiB.
|
|
1319
1322
|
CATALOG_MAX_BYTES = 1024 * 1024
|
|
1320
1323
|
CATALOG_TIMEOUT_SECONDS = 10
|
|
1321
|
-
SERVICE_ID_PATTERN = re.compile(r"
|
|
1324
|
+
SERVICE_ID_PATTERN = re.compile(r"[a-z0-9][a-z0-9_-]{0,63}")
|
|
1322
1325
|
# Rutas relativas sin segmentos ocultos ni '..': un segmento no empieza por punto.
|
|
1323
|
-
SERVICE_FILE_PATTERN = re.compile(r"
|
|
1324
|
-
SHA256_PATTERN = re.compile(r"
|
|
1326
|
+
SERVICE_FILE_PATTERN = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9_.-]*(?:/[A-Za-z0-9_-][A-Za-z0-9_.-]*)*")
|
|
1327
|
+
SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
|
|
1325
1328
|
SERVICE_DEFINITION = "service.json"
|
|
1326
1329
|
|
|
1327
1330
|
|
|
@@ -1354,7 +1357,7 @@ def parse_catalog(raw: bytes) -> dict[str, dict]:
|
|
|
1354
1357
|
if not isinstance(services, dict):
|
|
1355
1358
|
raise ValueError("El catálogo de servicios no tiene services")
|
|
1356
1359
|
for server_id, entry in services.items():
|
|
1357
|
-
if not SERVICE_ID_PATTERN.
|
|
1360
|
+
if not isinstance(server_id, str) or not SERVICE_ID_PATTERN.fullmatch(server_id):
|
|
1358
1361
|
raise ValueError(f"Id de servicio no válido en el catálogo: {server_id!r}")
|
|
1359
1362
|
if not isinstance(entry, dict) or not isinstance(entry.get("version"), str) or not entry["version"]:
|
|
1360
1363
|
raise ValueError(f"El servicio {server_id} del catálogo no tiene version")
|
|
@@ -1362,7 +1365,7 @@ def parse_catalog(raw: bytes) -> dict[str, dict]:
|
|
|
1362
1365
|
if not isinstance(files, dict) or SERVICE_DEFINITION not in files:
|
|
1363
1366
|
raise ValueError(f"El servicio {server_id} del catálogo no incluye {SERVICE_DEFINITION}")
|
|
1364
1367
|
for path, digest in files.items():
|
|
1365
|
-
if not SERVICE_FILE_PATTERN.
|
|
1368
|
+
if not isinstance(path, str) or not SERVICE_FILE_PATTERN.fullmatch(path) or not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest):
|
|
1366
1369
|
raise ValueError(f"Fichero no válido en el servicio {server_id} del catálogo: {path!r}")
|
|
1367
1370
|
return services
|
|
1368
1371
|
|
|
@@ -1396,6 +1399,12 @@ def download_service(base: str, server_id: str, entry: dict) -> dict[str, bytes]
|
|
|
1396
1399
|
|
|
1397
1400
|
def install_service(services_root: Path, server_id: str, files: dict[str, bytes]) -> None:
|
|
1398
1401
|
"""Escribe los ficheros del servicio, cada uno de forma atómica; service.json, con la versión, el último."""
|
|
1402
|
+
services_root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
1403
|
+
if os.name != "nt":
|
|
1404
|
+
try:
|
|
1405
|
+
services_root.chmod(0o700)
|
|
1406
|
+
except OSError:
|
|
1407
|
+
pass
|
|
1399
1408
|
service_dir = services_root / server_id
|
|
1400
1409
|
for path in sorted(files, key=lambda name: name == SERVICE_DEFINITION):
|
|
1401
1410
|
destination = service_dir / path
|
|
@@ -1687,7 +1696,8 @@ class StdioMcpClient:
|
|
|
1687
1696
|
# --- run_mode.runner_loader ---
|
|
1688
1697
|
"""Cargador del runner de Node.js: descarga los módulos de la interfaz como un navegador y los ejecuta.
|
|
1689
1698
|
|
|
1690
|
-
El servidor lo lanza con `node --permission -e RUNNER_LOADER_SCRIPT <caché> <
|
|
1699
|
+
El servidor lo lanza con `node --permission -e RUNNER_LOADER_SCRIPT <caché> <política>` (la URL con el token
|
|
1700
|
+
viaja en la variable de entorno `ZEROCHAT_RUNNER_URL`, nunca en `argv`, y el cargador la borra al leerla) y una
|
|
1691
1701
|
tubería como stdin: cuando se cierra (muere el proceso que lo lanzó), el runner termina. Desde la
|
|
1692
1702
|
carpeta de la interfaz (GitHub Pages en producción, este servidor en desarrollo) descarga `js/run-node.js` y,
|
|
1693
1703
|
siguiendo sus `require('./…')`, los módulos que usa, en paralelo; los ejecuta con un `require` mínimo que los
|
|
@@ -1710,6 +1720,8 @@ de terceros que se cargan bajo demanda (`ChatVendorLoader`) siguen el mismo cami
|
|
|
1710
1720
|
# Política de caché del runner: ejecutar la caché si es de la versión publicada, o descargar siempre (desarrollo).
|
|
1711
1721
|
RUNNER_CACHE_BY_VERSION = "version"
|
|
1712
1722
|
RUNNER_CACHE_ALWAYS_DOWNLOAD = "always"
|
|
1723
|
+
# Variable de entorno en la que viaja la URL de la interfaz con el runner_token (fuera de argv; se borra al leerla).
|
|
1724
|
+
RUNNER_URL_ENV = "ZEROCHAT_RUNNER_URL"
|
|
1713
1725
|
|
|
1714
1726
|
# Tope de lo descargado en una ejecución: la interfaz completa ocupa unas pocas centenas de KiB.
|
|
1715
1727
|
RUNNER_MAX_BYTES = 16 * 1024 * 1024
|
|
@@ -1719,7 +1731,10 @@ RUNNER_LOADER_SCRIPT = r"""
|
|
|
1719
1731
|
const fs = require('node:fs');
|
|
1720
1732
|
const vm = require('node:vm');
|
|
1721
1733
|
|
|
1722
|
-
const [cacheFile,
|
|
1734
|
+
const [cacheFile, cachePolicy] = process.argv.slice(1);
|
|
1735
|
+
const uiUrl = process.env.__RUNNER_URL_ENV__ || '';
|
|
1736
|
+
delete process.env.__RUNNER_URL_ENV__;
|
|
1737
|
+
if (!uiUrl) throw new Error('Missing runner URL in environment.');
|
|
1723
1738
|
|
|
1724
1739
|
// El proceso zerochat que lanza el runner le da como stdin una tubería en la que nunca escribe: el sistema la cierra
|
|
1725
1740
|
// cuando ese proceso muere, también con SIGKILL, y el runner termina en vez de seguir llamando al modelo por su cuenta.
|
|
@@ -1871,7 +1886,7 @@ async function loadFiles(version) {
|
|
|
1871
1886
|
process.exit(1);
|
|
1872
1887
|
});
|
|
1873
1888
|
""".replace("__MAX_BYTES__", str(RUNNER_MAX_BYTES)).replace("__VERSION_PATTERN__", json.dumps(UI_VERSION_TITLE_PATTERN)).replace(
|
|
1874
|
-
"__BY_VERSION__", RUNNER_CACHE_BY_VERSION)
|
|
1889
|
+
"__BY_VERSION__", RUNNER_CACHE_BY_VERSION).replace("__RUNNER_URL_ENV__", RUNNER_URL_ENV)
|
|
1875
1890
|
|
|
1876
1891
|
# --- security.context ---
|
|
1877
1892
|
"""Proyecto de cada petición (SecurityContext): carpeta canónica, rutas resueltas contra ella y clave de su sesión."""
|
|
@@ -3055,6 +3070,8 @@ def _merge_saved_header(existing, session_meta: dict, created_at: int, title: st
|
|
|
3055
3070
|
extra = {**existing_extra, **extra}
|
|
3056
3071
|
if existing_extra.get("project"):
|
|
3057
3072
|
extra["project"] = existing_extra["project"]
|
|
3073
|
+
else:
|
|
3074
|
+
extra.pop("project", None)
|
|
3058
3075
|
extra.pop("agent", None)
|
|
3059
3076
|
if existing_extra.get("agent"):
|
|
3060
3077
|
extra["agent"] = existing_extra["agent"]
|
|
@@ -4083,7 +4100,7 @@ PLAYWRIGHT_SERVER_ID = "playwright"
|
|
|
4083
4100
|
PLAYWRIGHT_EXTENSION_ID = "mmlmfjhmonkocbjadbfplnigmagldckm"
|
|
4084
4101
|
# Token que muestra la extensión: con él la conexión no pide aceptarla en el navegador. Es de solo
|
|
4085
4102
|
# escritura, como los secretos MCP: ningún método lo devuelve, solo si está guardado.
|
|
4086
|
-
_EXTENSION_TOKEN = re.compile(r"
|
|
4103
|
+
_EXTENSION_TOKEN = re.compile(r"[A-Za-z0-9_-]{1,256}")
|
|
4087
4104
|
_BROWSER_CONFIG_CHOICES = {
|
|
4088
4105
|
"mode": BROWSER_MODES,
|
|
4089
4106
|
"engine": ALL_OWN_ENGINES,
|
|
@@ -4157,7 +4174,7 @@ def save_extension_token(token) -> bool:
|
|
|
4157
4174
|
if token is None:
|
|
4158
4175
|
delete_secret(BROWSER_EXTENSION_TOKEN_KEY)
|
|
4159
4176
|
return False
|
|
4160
|
-
if not isinstance(token, str) or not _EXTENSION_TOKEN.
|
|
4177
|
+
if not isinstance(token, str) or not _EXTENSION_TOKEN.fullmatch(token):
|
|
4161
4178
|
raise ValueError("token debe tener de 1 a 256 letras, cifras, guiones o guiones bajos, o ser null")
|
|
4162
4179
|
save_secret(BROWSER_EXTENSION_TOKEN_KEY, token)
|
|
4163
4180
|
return True
|
|
@@ -5355,6 +5372,8 @@ DEFAULT_RUN_REASONING = "medium"
|
|
|
5355
5372
|
RUN_FILE_MAX_BYTES = MAX_HTTP_BODY_BYTES
|
|
5356
5373
|
# Marca que pasa start_server_run al hijo de una conversación interactiva cuando «Subagentes» está encendido.
|
|
5357
5374
|
ZEROCHAT_RUN_SUBAGENTS_ENV = "ZEROCHAT_RUN_SUBAGENTS"
|
|
5375
|
+
# Error que escribe el runner al interrumpirse sin resultado (p. ej. SIGTERM); stop_agent lo reconoce para marcar parada.
|
|
5376
|
+
RUN_INTERRUPTED_ERROR = "El runner se cerró o la ejecución se interrumpió sin resultado."
|
|
5358
5377
|
|
|
5359
5378
|
|
|
5360
5379
|
# Procesos de ejecución (PID y huella de arranque) cuyo final espera un hilo, y los que ya terminaron: uno que lanzó
|
|
@@ -5780,9 +5799,9 @@ def start_server_run(params: dict) -> dict:
|
|
|
5780
5799
|
raise ValueError(f"La carpeta del proyecto de la conversación ya no existe: {project}")
|
|
5781
5800
|
|
|
5782
5801
|
run_id = secrets.token_urlsafe(24)
|
|
5783
|
-
cmd = [sys.executable, str(Path(__file__).resolve()), "--conversation", clean_conv_id, "--profile"
|
|
5802
|
+
cmd = [sys.executable, str(Path(__file__).resolve()), "--conversation", clean_conv_id, f"--profile={profile_name}"]
|
|
5784
5803
|
if prompt:
|
|
5785
|
-
cmd.
|
|
5804
|
+
cmd.append(f"--prompt={prompt}")
|
|
5786
5805
|
|
|
5787
5806
|
env = dict(os.environ)
|
|
5788
5807
|
env["ZEROCHAT_RUN_ID"] = run_id
|
|
@@ -5943,6 +5962,7 @@ class RunSession(ControllerState):
|
|
|
5943
5962
|
# Límites de --run-file: el de pasos lo aplica el bucle del runner y el de tiempo, run_supervisor.
|
|
5944
5963
|
self.max_steps = max_steps
|
|
5945
5964
|
self.timeout_seconds = timeout_seconds
|
|
5965
|
+
self.started_monotonic = time.monotonic()
|
|
5946
5966
|
# Perfil (nombre o id) que la interfaz usa solo en esta ejecución; por defecto, local del servidor.
|
|
5947
5967
|
self.profile = profile
|
|
5948
5968
|
self.profile_data = profile_data
|
|
@@ -6290,7 +6310,7 @@ def run_outcome(session: RunSession) -> tuple[int, str | None]:
|
|
|
6290
6310
|
if session.export_path and not session.exported:
|
|
6291
6311
|
run_error(session.export_error or f"La interfaz no envió la conversación para {session.export_path}.")
|
|
6292
6312
|
if session.result is None:
|
|
6293
|
-
run_error(session.stop_reason or session.error or
|
|
6313
|
+
run_error(session.stop_reason or session.error or RUN_INTERRUPTED_ERROR)
|
|
6294
6314
|
return RUN_EXIT_NO_RESULT, None
|
|
6295
6315
|
if "limit" in session.result:
|
|
6296
6316
|
console_error(timestamp_message(f"[run] {session.result['limit']} Lo hecho queda grabado en la conversación."))
|
|
@@ -6419,8 +6439,8 @@ def _rpc_save_conversation(params: dict) -> RpcOutcome:
|
|
|
6419
6439
|
raise ValueError("Los parámetros deben ser un objeto")
|
|
6420
6440
|
upload_id = params.get("uploadId")
|
|
6421
6441
|
raw_conv = params.get("conversation")
|
|
6422
|
-
if isinstance(raw_conv, dict) and "launch" in raw_conv:
|
|
6423
|
-
raw_conv = {k: v for k, v in raw_conv.items() if k
|
|
6442
|
+
if isinstance(raw_conv, dict) and ("launch" in raw_conv or "agent" in raw_conv):
|
|
6443
|
+
raw_conv = {k: v for k, v in raw_conv.items() if k not in ("launch", "agent")}
|
|
6424
6444
|
conversation = run_conversation_meta(raw_conv)
|
|
6425
6445
|
# Una ejecución viva es la única que escribe su conversación: la copia de la interfaz la pisaría a medias.
|
|
6426
6446
|
# En un servidor de ejecución solo llega su runner (M87-D2), que sí guarda la suya.
|
|
@@ -6545,89 +6565,47 @@ def _atomic_write_text(target: Path, text: str):
|
|
|
6545
6565
|
temp_path.unlink(missing_ok=True)
|
|
6546
6566
|
|
|
6547
6567
|
# --- tools.browser_secret ---
|
|
6548
|
-
"""
|
|
6549
|
-
|
|
6568
|
+
"""Herramientas locales complementarias de Playwright MCP: secretos y estado de sesión (cookies/storage) por proyecto."""
|
|
6550
6569
|
|
|
6551
6570
|
|
|
6552
6571
|
|
|
6553
6572
|
|
|
6554
|
-
BROWSER_SECRET_MODES = ("input", "keypad")
|
|
6555
6573
|
|
|
6574
|
+
PLAYWRIGHT_LOCAL_TOOLS = frozenset({"browser_fill_secret", "browser_save_state", "browser_load_state"})
|
|
6575
|
+
MAX_BROWSER_STATES_PER_PROJECT = 32
|
|
6576
|
+
_STATE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
|
|
6556
6577
|
|
|
6557
|
-
def _scrub_secret(text: str, secret_value: str) -> str:
|
|
6558
|
-
return text.replace(secret_value, "***") if secret_value and text else text
|
|
6559
6578
|
|
|
6560
|
-
|
|
6561
|
-
def _mcp_call_error(tool_name: str, arguments: dict, secret_value: str) -> str | None:
|
|
6579
|
+
def _mcp_call_failed(tool_name: str, arguments: dict) -> bool:
|
|
6562
6580
|
result = GLOBAL_MCP_MANAGER.call(public_tool_name(PLAYWRIGHT_SERVER_ID, tool_name), arguments)
|
|
6563
|
-
|
|
6564
|
-
return None
|
|
6565
|
-
parts = [str(item.get("text") or "") for item in (result.get("content") or []) if isinstance(item, dict)]
|
|
6566
|
-
detail = _scrub_secret(" ".join(p for p in parts if p).strip(), secret_value)
|
|
6567
|
-
return detail or f"Playwright {tool_name} failed."
|
|
6581
|
+
return bool(isinstance(result, dict) and result.get("isError"))
|
|
6568
6582
|
|
|
6569
6583
|
|
|
6570
6584
|
def _fill_input_secret(secret_value: str, ref: str, element: str, submit: bool) -> str | None:
|
|
6571
6585
|
clean_ref = ref.strip() if isinstance(ref, str) else ""
|
|
6572
6586
|
if not clean_ref:
|
|
6573
|
-
return "
|
|
6587
|
+
return "Se requiere un 'ref' no vacío."
|
|
6574
6588
|
label = element.strip() if isinstance(element, str) and element.strip() else "input field"
|
|
6575
|
-
|
|
6589
|
+
if _mcp_call_failed("browser_type", {
|
|
6576
6590
|
"element": label,
|
|
6577
6591
|
"target": clean_ref,
|
|
6578
6592
|
"text": secret_value,
|
|
6579
6593
|
"submit": bool(submit),
|
|
6580
|
-
}
|
|
6581
|
-
|
|
6582
|
-
|
|
6583
|
-
def _is_xy_target(target) -> bool:
|
|
6584
|
-
if not isinstance(target, (list, tuple)) or len(target) != 2:
|
|
6585
|
-
return False
|
|
6586
|
-
return all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in target)
|
|
6587
|
-
|
|
6588
|
-
|
|
6589
|
-
def _keypad_click(target) -> tuple[str, dict]:
|
|
6590
|
-
"""Herramienta y argumentos de Playwright MCP que pulsan una tecla: un 'ref' o coordenadas [x, y]."""
|
|
6591
|
-
if _is_xy_target(target):
|
|
6592
|
-
return "browser_mouse_click_xy", {"x": float(target[0]), "y": float(target[1])}
|
|
6593
|
-
return "browser_click", {"element": "keypad button", "target": target.strip()}
|
|
6594
|
-
|
|
6595
|
-
|
|
6596
|
-
def _fill_keypad_secret(secret_value: str, keypad_map) -> str | None:
|
|
6597
|
-
"""Pulsa el secreto en un teclado virtual. Ninguna respuesta depende de qué carácter falló ni de la longitud: el
|
|
6598
|
-
mapa se valida entero antes de pulsar y un fallo de Playwright a mitad da siempre el mismo mensaje, sin su detalle
|
|
6599
|
-
(que nombraría la tecla y con ella el carácter)."""
|
|
6600
|
-
if not isinstance(keypad_map, dict) or not keypad_map:
|
|
6601
|
-
return "El modo 'keypad' requiere un objeto keypad_map no vacío."
|
|
6602
|
-
if not all((isinstance(target, str) and target.strip()) or _is_xy_target(target) for target in keypad_map.values()):
|
|
6603
|
-
return "Cada entrada de keypad_map debe ser un 'ref' de texto o coordenadas [x, y]."
|
|
6604
|
-
if any(ch not in keypad_map for ch in secret_value):
|
|
6605
|
-
return "keypad_map no cubre todos los caracteres del secreto."
|
|
6606
|
-
for ch in secret_value:
|
|
6607
|
-
tool_name, arguments = _keypad_click(keypad_map[ch])
|
|
6608
|
-
try:
|
|
6609
|
-
failed = _mcp_call_error(tool_name, arguments, secret_value) is not None
|
|
6610
|
-
except Exception:
|
|
6611
|
-
failed = True
|
|
6612
|
-
if failed:
|
|
6613
|
-
return "Playwright no pudo pulsar una tecla del teclado virtual: toma una instantánea nueva y repite con sus refs actuales."
|
|
6594
|
+
}):
|
|
6595
|
+
return "Playwright no pudo rellenar el campo del secreto: comprueba la referencia y vuelve a intentarlo."
|
|
6614
6596
|
return None
|
|
6615
6597
|
|
|
6616
6598
|
|
|
6617
6599
|
def browser_fill_secret(
|
|
6618
6600
|
secret: str,
|
|
6619
|
-
|
|
6620
|
-
ref: str = "",
|
|
6601
|
+
ref: str,
|
|
6621
6602
|
element: str = "",
|
|
6622
6603
|
submit: bool = False,
|
|
6623
|
-
keypad_map: dict | None = None,
|
|
6624
6604
|
ctx: SecurityContext | None = None,
|
|
6625
6605
|
) -> str:
|
|
6626
|
-
"""Introduce un secreto guardado del proyecto en un campo input
|
|
6606
|
+
"""Introduce un secreto guardado del proyecto en un campo input de Playwright MCP."""
|
|
6627
6607
|
if ctx is None:
|
|
6628
6608
|
return _tool_error("Se requiere contexto de proyecto para leer secretos.")
|
|
6629
|
-
if mode not in BROWSER_SECRET_MODES:
|
|
6630
|
-
return _tool_error(f"Modalidad no válida: {mode}")
|
|
6631
6609
|
try:
|
|
6632
6610
|
secret_value = get_project_secret(ctx.key, secret)
|
|
6633
6611
|
except ValueError as exc:
|
|
@@ -6635,16 +6613,73 @@ def browser_fill_secret(
|
|
|
6635
6613
|
if secret_value is None:
|
|
6636
6614
|
return _tool_error(f"El secreto '{secret}' no está guardado en este proyecto.")
|
|
6637
6615
|
try:
|
|
6638
|
-
err = (
|
|
6639
|
-
|
|
6640
|
-
|
|
6641
|
-
else _fill_keypad_secret(secret_value, keypad_map)
|
|
6642
|
-
)
|
|
6643
|
-
except Exception as exc:
|
|
6644
|
-
return _tool_error(f"Error ejecutando Playwright MCP: {_scrub_secret(str(exc), secret_value)}")
|
|
6616
|
+
err = _fill_input_secret(secret_value, ref, element, submit)
|
|
6617
|
+
except Exception:
|
|
6618
|
+
return _tool_error("Error ejecutando Playwright MCP al rellenar el secreto.")
|
|
6645
6619
|
if err:
|
|
6646
6620
|
return _tool_error(err)
|
|
6647
|
-
return json.dumps({"success": True, "
|
|
6621
|
+
return json.dumps({"success": True, "secret": secret})
|
|
6622
|
+
|
|
6623
|
+
|
|
6624
|
+
def _browser_state_location(ctx: SecurityContext, name: str) -> tuple[str, Path]:
|
|
6625
|
+
if not isinstance(name, str) or not _STATE_NAME_RE.fullmatch(name):
|
|
6626
|
+
raise ValueError("State name must be 1-64 characters of letters, digits, '-' or '_'.")
|
|
6627
|
+
project_hash = hashlib.sha256(ctx.key.encode("utf-8")).hexdigest()[:24]
|
|
6628
|
+
rel_path = f"states/{project_hash}/{name}.json"
|
|
6629
|
+
full_path = GLOBAL_MCP_MANAGER.services_root / PLAYWRIGHT_SERVER_ID / "states" / project_hash / f"{name}.json"
|
|
6630
|
+
return rel_path, full_path
|
|
6631
|
+
|
|
6632
|
+
|
|
6633
|
+
def _chmod_private(path: Path, mode: int) -> None:
|
|
6634
|
+
if os.name != "nt":
|
|
6635
|
+
path.chmod(mode)
|
|
6636
|
+
|
|
6637
|
+
|
|
6638
|
+
def browser_save_state(name: str, ctx: SecurityContext | None = None) -> str:
|
|
6639
|
+
"""Guarda el estado actual del navegador (cookies y localStorage) bajo el proyecto activo."""
|
|
6640
|
+
if ctx is None:
|
|
6641
|
+
return _tool_error("Project context is required to save browser state.")
|
|
6642
|
+
try:
|
|
6643
|
+
rel_path, target = _browser_state_location(ctx, name)
|
|
6644
|
+
except ValueError as exc:
|
|
6645
|
+
return _tool_error(str(exc))
|
|
6646
|
+
states_root = target.parent.parent
|
|
6647
|
+
project_dir = target.parent
|
|
6648
|
+
states_root.mkdir(parents=True, exist_ok=True)
|
|
6649
|
+
_chmod_private(states_root, 0o700)
|
|
6650
|
+
project_dir.mkdir(parents=True, exist_ok=True)
|
|
6651
|
+
_chmod_private(project_dir, 0o700)
|
|
6652
|
+
if not target.exists():
|
|
6653
|
+
existing = sum(1 for item in project_dir.iterdir() if item.is_file() and item.suffix == ".json")
|
|
6654
|
+
if existing >= MAX_BROWSER_STATES_PER_PROJECT:
|
|
6655
|
+
return _tool_error(f"Project reached the maximum of {MAX_BROWSER_STATES_PER_PROJECT} saved browser states.")
|
|
6656
|
+
try:
|
|
6657
|
+
failed = _mcp_call_failed("browser_storage_state", {"filename": rel_path})
|
|
6658
|
+
except Exception:
|
|
6659
|
+
return _tool_error("Error running Playwright MCP while saving browser state.")
|
|
6660
|
+
if failed or not target.is_file():
|
|
6661
|
+
return _tool_error("Playwright could not save the browser state.")
|
|
6662
|
+
_chmod_private(target, 0o600)
|
|
6663
|
+
return json.dumps({"success": True, "name": name, "saved": True})
|
|
6664
|
+
|
|
6665
|
+
|
|
6666
|
+
def browser_load_state(name: str, ctx: SecurityContext | None = None) -> str:
|
|
6667
|
+
"""Restaura un estado guardado del navegador (cookies y localStorage) del proyecto activo."""
|
|
6668
|
+
if ctx is None:
|
|
6669
|
+
return _tool_error("Project context is required to load browser state.")
|
|
6670
|
+
try:
|
|
6671
|
+
rel_path, target = _browser_state_location(ctx, name)
|
|
6672
|
+
except ValueError as exc:
|
|
6673
|
+
return _tool_error(str(exc))
|
|
6674
|
+
if not target.is_file():
|
|
6675
|
+
return _tool_error(f"Saved browser state '{name}' does not exist for this project.")
|
|
6676
|
+
try:
|
|
6677
|
+
failed = _mcp_call_failed("browser_set_storage_state", {"filename": rel_path})
|
|
6678
|
+
except Exception:
|
|
6679
|
+
return _tool_error("Error running Playwright MCP while loading browser state.")
|
|
6680
|
+
if failed:
|
|
6681
|
+
return _tool_error("Playwright could not restore the browser state.")
|
|
6682
|
+
return json.dumps({"success": True, "name": name, "loaded": True})
|
|
6648
6683
|
|
|
6649
6684
|
# --- tools.diff ---
|
|
6650
6685
|
"""Visor de diferencias (zerochat/diff/open): diff frente a Git HEAD en HTML propio o con git difftool."""
|
|
@@ -6886,6 +6921,7 @@ def _open_gui_file_diff(path: str, ctx: SecurityContext, commit_fallback: bool =
|
|
|
6886
6921
|
popen_kwargs["start_new_session"] = True
|
|
6887
6922
|
|
|
6888
6923
|
proc = subprocess.Popen(cmd, **popen_kwargs)
|
|
6924
|
+
threading.Thread(target=proc.wait, daemon=True).start()
|
|
6889
6925
|
return {
|
|
6890
6926
|
"success": True,
|
|
6891
6927
|
"has_diff": True,
|
|
@@ -7290,8 +7326,7 @@ def _full_file_bytes(git_bin: str, repo_root: Path, target: Path, rel_path: str,
|
|
|
7290
7326
|
"""El archivo entero para el visor: el del commit si se muestra uno, si no el del disco (hasta DIFF_MAX_BYTES)."""
|
|
7291
7327
|
if commit:
|
|
7292
7328
|
shown, truncated, code = _capped_git_output([git_bin, "show", f"{commit}:{rel_path}"], repo_root, 5)
|
|
7293
|
-
if code == 0 and not truncated
|
|
7294
|
-
return shown
|
|
7329
|
+
return shown if code == 0 and not truncated else None
|
|
7295
7330
|
try:
|
|
7296
7331
|
if target.is_file() and target.stat().st_size <= DIFF_MAX_BYTES:
|
|
7297
7332
|
return target.read_bytes()
|
|
@@ -8360,9 +8395,7 @@ class AccessController:
|
|
|
8360
8395
|
@staticmethod
|
|
8361
8396
|
def _check_entry_limit(state: dict):
|
|
8362
8397
|
"""Único tope de entradas, sobre el estado resultante (guardado o capa de sesión)."""
|
|
8363
|
-
|
|
8364
|
-
dir_count = sum(len(v) for v in dir_rules.values()) if isinstance(dir_rules, dict) else len(dir_rules or [])
|
|
8365
|
-
total = dir_count + len(state.get("tools") or {}) + len(state.get("servers") or {})
|
|
8398
|
+
total = len(state.get("directoryRules") or []) + len(state.get("tools") or {}) + len(state.get("servers") or {})
|
|
8366
8399
|
if total > MAX_POLICY_ENTRIES:
|
|
8367
8400
|
raise ValueError(f"El número total de entradas ({total}) supera el máximo permitido ({MAX_POLICY_ENTRIES}).")
|
|
8368
8401
|
|
|
@@ -8438,6 +8471,8 @@ class AccessController:
|
|
|
8438
8471
|
session.directory_rules = None
|
|
8439
8472
|
elif patch.added_rules and session.directory_rules is not None:
|
|
8440
8473
|
session.directory_rules = self._append_rules(session.directory_rules, patch.added_rules)
|
|
8474
|
+
if patch.command_patterns is not None:
|
|
8475
|
+
session.command_patterns.clear()
|
|
8441
8476
|
for kind, entries in (("tools", patch.tools), ("servers", patch.servers)):
|
|
8442
8477
|
for item_id in entries or {}:
|
|
8443
8478
|
session.entries(kind).pop(item_id, None)
|
|
@@ -8631,7 +8666,12 @@ class AccessController:
|
|
|
8631
8666
|
if checked is None:
|
|
8632
8667
|
return None
|
|
8633
8668
|
challenges.pop(challenge_id)
|
|
8634
|
-
|
|
8669
|
+
try:
|
|
8670
|
+
self._record_decision(challenge, decision, *checked, context)
|
|
8671
|
+
except Exception:
|
|
8672
|
+
with self._lock:
|
|
8673
|
+
self._session(context).challenges.setdefault(challenge_id, challenge)
|
|
8674
|
+
raise
|
|
8635
8675
|
return challenge
|
|
8636
8676
|
|
|
8637
8677
|
def revoke_challenge(self, challenge_id: str, *, context: SecurityContext) -> bool:
|
|
@@ -8647,6 +8687,8 @@ class AccessController:
|
|
|
8647
8687
|
if decision == "allow_server_always" and not challenge.get("serverId"):
|
|
8648
8688
|
return None
|
|
8649
8689
|
rules = self._validate_directory_rules([directory_rule]) if directory_rule else []
|
|
8690
|
+
if rules and decision == "allow_once":
|
|
8691
|
+
raise ValueError("allow_once no admite una regla de carpeta.")
|
|
8650
8692
|
if rules and command_pattern:
|
|
8651
8693
|
raise ValueError("Una decisión lleva un patrón de comando o una regla de carpeta, no los dos.")
|
|
8652
8694
|
return (None if rules else self._validate_command_pattern(decision, command_pattern, challenge)), rules
|
|
@@ -8866,7 +8908,10 @@ class AccessController:
|
|
|
8866
8908
|
if resolved is None:
|
|
8867
8909
|
return None
|
|
8868
8910
|
folders.append(resolved if resolved.is_dir() else resolved.parent)
|
|
8869
|
-
|
|
8911
|
+
try:
|
|
8912
|
+
common = Path(os.path.commonpath(folders))
|
|
8913
|
+
except ValueError:
|
|
8914
|
+
return None
|
|
8870
8915
|
home = Path.home().resolve()
|
|
8871
8916
|
if home not in common.parents or any(part.startswith(".") for part in common.relative_to(home).parts):
|
|
8872
8917
|
return None
|
|
@@ -8978,7 +9023,7 @@ def _agent_conversations(ctx: SecurityContext, own_id: str, state: ControllerSta
|
|
|
8978
9023
|
convs = [conv for conv in list_conversations()
|
|
8979
9024
|
if conv["id"] != own_id and conv.get("agent") and (conv.get("project") or "") == project]
|
|
8980
9025
|
saved = {conv["id"] for conv in convs}
|
|
8981
|
-
pending = [{"id": conv_id, **meta} for conv_id, meta in state.launched_agents.items()
|
|
9026
|
+
pending = [{"id": conv_id, **meta, "_unsaved": True} for conv_id, meta in state.launched_agents.items()
|
|
8982
9027
|
if conv_id not in saved and meta["project"] == project]
|
|
8983
9028
|
if not pending:
|
|
8984
9029
|
return convs
|
|
@@ -9007,14 +9052,21 @@ def _agent_state(conv: dict, run: dict) -> dict:
|
|
|
9007
9052
|
AGENT_CUT_STATUSES = ("limit", "error")
|
|
9008
9053
|
|
|
9009
9054
|
|
|
9055
|
+
def _last_turn_start(history: list[dict]) -> int:
|
|
9056
|
+
"""Índice del último mensaje del usuario (la evidencia visual _toolEvidence es parte del turno, no su inicio)."""
|
|
9057
|
+
return max((index for index, message in enumerate(history)
|
|
9058
|
+
if message.get("role") == "user" and not message.get("_toolEvidence")), default=0)
|
|
9059
|
+
|
|
9060
|
+
|
|
9010
9061
|
def _final_answer(conv: dict, state: dict, run: dict) -> tuple[str, bool]:
|
|
9011
9062
|
"""La respuesta final y si es parcial: la que entregó o, si se cortó (límite, error o proceso muerto) sin
|
|
9012
|
-
entregarla, el último texto del asistente
|
|
9063
|
+
entregarla, el último texto del asistente de su último turno, que dice al menos dónde se quedó."""
|
|
9013
9064
|
result = run.get("result_text") or ""
|
|
9014
9065
|
if result or state["status"] not in AGENT_CUT_STATUSES:
|
|
9015
9066
|
return result, False
|
|
9016
9067
|
history = (get_conversation(conv["id"]) or {}).get("history") or []
|
|
9017
|
-
|
|
9068
|
+
start = _last_turn_start(history)
|
|
9069
|
+
partial = next((message["content"].strip() for message in reversed(history[start:]) if message.get("role") == "assistant"
|
|
9018
9070
|
and isinstance(message.get("content"), str) and message["content"].strip()), "")
|
|
9019
9071
|
return partial, bool(partial)
|
|
9020
9072
|
|
|
@@ -9071,10 +9123,8 @@ def _result_page(result: str, offset: int) -> dict:
|
|
|
9071
9123
|
|
|
9072
9124
|
|
|
9073
9125
|
def _last_turn(history: list[dict]) -> tuple[list[dict], bool]:
|
|
9074
|
-
"""Mensajes desde el último del usuario, con AGENT_TURN_MAX_CHARS de texto entre todos; True si se recortó.
|
|
9075
|
-
|
|
9076
|
-
start = max((index for index, message in enumerate(history)
|
|
9077
|
-
if message.get("role") == "user" and not message.get("_toolEvidence")), default=0)
|
|
9126
|
+
"""Mensajes desde el último del usuario, con AGENT_TURN_MAX_CHARS de texto entre todos; True si se recortó."""
|
|
9127
|
+
start = _last_turn_start(history)
|
|
9078
9128
|
budget, truncated, messages = AGENT_TURN_MAX_CHARS, False, []
|
|
9079
9129
|
for message in history[start:]:
|
|
9080
9130
|
content, clipped = _clip("" if message.get("content") is None else str(message["content"]), budget)
|
|
@@ -9152,6 +9202,8 @@ def _prune(convs: list[dict], agent: str | None, keep: int) -> str:
|
|
|
9152
9202
|
de runs; las que están en marcha o esperan a una persona se conservan y se indican."""
|
|
9153
9203
|
deleted, skipped, seen = [], [], {}
|
|
9154
9204
|
for conv in convs: # De la más reciente a la más antigua.
|
|
9205
|
+
if conv.get("_unsaved"):
|
|
9206
|
+
continue
|
|
9155
9207
|
if agent is not None and conv["agent"] != agent:
|
|
9156
9208
|
continue
|
|
9157
9209
|
seen[conv["agent"]] = seen.get(conv["agent"], 0) + 1
|
|
@@ -9239,7 +9291,7 @@ def stop_agent(conversation_id: str | None = None, project: str | None = None,
|
|
|
9239
9291
|
_kill_process_tree(run["pid"], grace_seconds=AGENT_STOP_GRACE_SECONDS)
|
|
9240
9292
|
# Releer tras el plazo de gracia para conservar usage/warnings recientes o un resultado terminado a tiempo.
|
|
9241
9293
|
fresh = get_run_state(conv_id) or run
|
|
9242
|
-
if fresh.get("status") != "running":
|
|
9294
|
+
if fresh.get("status") != "running" and not (fresh.get("status") == "error" and fresh.get("error") == RUN_INTERRUPTED_ERROR):
|
|
9243
9295
|
return _detail(conv, fresh, state, 0, False, {"stopped": False})
|
|
9244
9296
|
now = int(time.time() * 1000)
|
|
9245
9297
|
upsert_run_state({**fresh, "status": "error", "error": AGENT_STOPPED_ERROR, "updated_at": now, "finished_at": now})
|
|
@@ -9369,7 +9421,8 @@ def launch_agent(run_file: str | None = None, prompt: str | None = None, project
|
|
|
9369
9421
|
return _tool_error(str(exc))
|
|
9370
9422
|
if run_file is None:
|
|
9371
9423
|
try:
|
|
9372
|
-
|
|
9424
|
+
inline_keys = {INLINE_LAUNCH_FIELDS[key] for key in fields}
|
|
9425
|
+
return _launch(_inline_request(fields, prompt), prompt, target, own_id, state, inline_keys=inline_keys)
|
|
9373
9426
|
except ValueError as exc:
|
|
9374
9427
|
return _tool_error(str(exc))
|
|
9375
9428
|
if fields:
|
|
@@ -9410,7 +9463,8 @@ def _target_conversation(conv_id: str | None, agent: str, target: SecurityContex
|
|
|
9410
9463
|
return conv
|
|
9411
9464
|
|
|
9412
9465
|
|
|
9413
|
-
def _launch(request: dict, prompt: str | None, target: SecurityContext, own_id: str, state: ControllerState
|
|
9466
|
+
def _launch(request: dict, prompt: str | None, target: SecurityContext, own_id: str, state: ControllerState,
|
|
9467
|
+
*, inline_keys: set[str] | None = None) -> str:
|
|
9414
9468
|
agent = request.get("agent")
|
|
9415
9469
|
if not agent:
|
|
9416
9470
|
raise ValueError("The run-file must set an agent.")
|
|
@@ -9428,6 +9482,13 @@ def _launch(request: dict, prompt: str | None, target: SecurityContext, own_id:
|
|
|
9428
9482
|
conv = _target_conversation(conv_id, agent, target, own_id)
|
|
9429
9483
|
if "prompt" not in request and conv is None:
|
|
9430
9484
|
raise ValueError("The conversation does not exist yet: give prompt to start it.")
|
|
9485
|
+
# Continuar en línea una conversación existente conserva el lanzamiento guardado (manual, disabledTools, perfil,
|
|
9486
|
+
# razonamiento y límites) salvo lo que la llamada sobreescriba de forma explícita.
|
|
9487
|
+
if inline_keys is not None and conv is not None:
|
|
9488
|
+
stored = get_conversation_launch(conv_id) or {}
|
|
9489
|
+
for key in ("profile", *RUN_LAUNCH_KEYS):
|
|
9490
|
+
if key not in inline_keys and key in stored and (key != "disabledTools" or stored[key]):
|
|
9491
|
+
request[key] = stored[key]
|
|
9431
9492
|
request["conversation_id"] = conv_id or f"session_{uuid.uuid4()}"
|
|
9432
9493
|
try:
|
|
9433
9494
|
check_no_active_run(request["conversation_id"])
|
|
@@ -9616,11 +9677,37 @@ def _read_line_range(target: Path, start: int, count: int, max_bytes: int) -> tu
|
|
|
9616
9677
|
|
|
9617
9678
|
# Tope por defecto de read_file: alineado con los 60.000 chars de web/MCP, por debajo de los 64.000 de ChatContextManager.
|
|
9618
9679
|
READ_FILE_DEFAULT_MAX_BYTES = 60000
|
|
9680
|
+
# Formatos de imagen ráster admitidos por read_file (alineados con SAFE_IMAGE_MIME_TYPES en js/utils.js).
|
|
9681
|
+
# 6 MiB binarios producen exactamente 8 MiB en base64 (MAX_IMAGE_BASE64_LENGTH en js/mcp-results.js).
|
|
9682
|
+
READ_FILE_IMAGE_MIME_BY_EXT = {
|
|
9683
|
+
".png": "image/png",
|
|
9684
|
+
".jpg": "image/jpeg",
|
|
9685
|
+
".jpeg": "image/jpeg",
|
|
9686
|
+
".webp": "image/webp",
|
|
9687
|
+
".gif": "image/gif",
|
|
9688
|
+
}
|
|
9689
|
+
READ_FILE_IMAGE_MAX_BYTES = 6 * 1024 * 1024
|
|
9690
|
+
|
|
9691
|
+
|
|
9692
|
+
def _read_image_file(target: Path, path: str, mime_type: str) -> str:
|
|
9693
|
+
with open(target, "rb") as handle:
|
|
9694
|
+
raw = handle.read(READ_FILE_IMAGE_MAX_BYTES + 1)
|
|
9695
|
+
if not raw:
|
|
9696
|
+
return _tool_error(f"Image '{path}' is empty.")
|
|
9697
|
+
if len(raw) > READ_FILE_IMAGE_MAX_BYTES:
|
|
9698
|
+
return _tool_error(f"Image '{path}' exceeds the maximum size of {READ_FILE_IMAGE_MAX_BYTES} bytes.")
|
|
9699
|
+
return json.dumps({
|
|
9700
|
+
"success": True,
|
|
9701
|
+
"path": str(target),
|
|
9702
|
+
"size_bytes": len(raw),
|
|
9703
|
+
"mime_type": mime_type,
|
|
9704
|
+
"image_base64": base64.b64encode(raw).decode("ascii"),
|
|
9705
|
+
}, ensure_ascii=False, indent=2)
|
|
9619
9706
|
|
|
9620
9707
|
|
|
9621
9708
|
def read_file(path: str, start_line: int = 1, end_line: int = None, max_lines: int = 500, max_bytes: int = READ_FILE_DEFAULT_MAX_BYTES,
|
|
9622
9709
|
tail_lines: int | None = None, *, ctx: SecurityContext) -> str:
|
|
9623
|
-
"""Read text content from a local file in streaming mode with safe ranges and bounds,
|
|
9710
|
+
"""Read text content from a local file in streaming mode with safe ranges and bounds, its last lines, or a raster image."""
|
|
9624
9711
|
try:
|
|
9625
9712
|
target = ctx.absolute(path)
|
|
9626
9713
|
if not target.exists():
|
|
@@ -9628,6 +9715,10 @@ def read_file(path: str, start_line: int = 1, end_line: int = None, max_lines: i
|
|
|
9628
9715
|
if not target.is_file():
|
|
9629
9716
|
return _tool_error(f"Path '{path}' is not a regular file.")
|
|
9630
9717
|
|
|
9718
|
+
image_mime = READ_FILE_IMAGE_MIME_BY_EXT.get(target.suffix.lower())
|
|
9719
|
+
if image_mime:
|
|
9720
|
+
return _read_image_file(target, path, image_mime)
|
|
9721
|
+
|
|
9631
9722
|
file_size = target.stat().st_size
|
|
9632
9723
|
safe_max_bytes = max(1024, min(int(max_bytes), 2000000))
|
|
9633
9724
|
if tail_lines is not None:
|
|
@@ -9849,11 +9940,12 @@ def validate_deletable_project_dir(ctx: SecurityContext) -> Path:
|
|
|
9849
9940
|
no_project = get_no_project_dir().resolve()
|
|
9850
9941
|
data_dir = get_data_dir().resolve()
|
|
9851
9942
|
home = Path.home().resolve()
|
|
9852
|
-
if target == target.parent or target == home or target == no_project:
|
|
9943
|
+
if target == target.parent or target == home or target in home.parents or target == no_project:
|
|
9853
9944
|
raise ValueError("No se puede borrar la carpeta general, la carpeta personal ni una raíz del sistema.")
|
|
9854
9945
|
if target == data_dir or target in data_dir.parents:
|
|
9855
9946
|
raise ValueError("No se puede borrar la carpeta de datos de ZeroChat.")
|
|
9856
|
-
|
|
9947
|
+
startup = project_context().workspace_dir.resolve()
|
|
9948
|
+
if target == startup or target in startup.parents:
|
|
9857
9949
|
raise ValueError("Es la carpeta con la que arrancó ZeroChat: arráncalo desde otra para borrarla.")
|
|
9858
9950
|
return target
|
|
9859
9951
|
|
|
@@ -10460,7 +10552,10 @@ def is_dangerous_host(hostname: str) -> bool:
|
|
|
10460
10552
|
return True
|
|
10461
10553
|
if clean_host.endswith((".localhost", ".local", ".internal")):
|
|
10462
10554
|
return True
|
|
10463
|
-
|
|
10555
|
+
try:
|
|
10556
|
+
return not _is_public_ip(clean_host)
|
|
10557
|
+
except ValueError:
|
|
10558
|
+
return any(not _is_public_ip(address) for address in _resolved_addresses(clean_host))
|
|
10464
10559
|
|
|
10465
10560
|
|
|
10466
10561
|
def _is_metadata_ip(address: str) -> bool:
|
|
@@ -10495,32 +10590,59 @@ def _validate_web_url(url: str) -> str:
|
|
|
10495
10590
|
|
|
10496
10591
|
|
|
10497
10592
|
class _ValidatingRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
10498
|
-
"""Sigue redirecciones
|
|
10593
|
+
"""Sigue redirecciones (hasta WEB_FETCH_MAX_REDIRECTS saltos totales, sin leer cuerpos 30x) solo si el destino
|
|
10594
|
+
supera la misma validación anti-SSRF que la URL pedida."""
|
|
10499
10595
|
max_redirections = WEB_FETCH_MAX_REDIRECTS
|
|
10500
10596
|
|
|
10501
10597
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
10598
|
+
hops = getattr(req, "_zerochat_hops", 0) + 1
|
|
10599
|
+
if hops > WEB_FETCH_MAX_REDIRECTS:
|
|
10600
|
+
raise urllib.error.HTTPError(newurl, code, self.inf_msg + msg, headers, fp)
|
|
10502
10601
|
_validate_web_url(newurl)
|
|
10503
|
-
|
|
10602
|
+
new_req = super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
10603
|
+
if new_req is not None:
|
|
10604
|
+
new_req._zerochat_hops = hops # pyright: ignore[reportAttributeAccessIssue]
|
|
10605
|
+
return new_req
|
|
10606
|
+
|
|
10607
|
+
def http_error_302(self, req, fp, code, msg, headers):
|
|
10608
|
+
location = headers.get("location") or headers.get("uri")
|
|
10609
|
+
if not location:
|
|
10610
|
+
return
|
|
10611
|
+
newurl = urllib.parse.urljoin(req.full_url, location.strip())
|
|
10612
|
+
new_req = self.redirect_request(req, fp, code, msg, headers, newurl)
|
|
10613
|
+
if not new_req:
|
|
10614
|
+
return
|
|
10615
|
+
fp.close()
|
|
10616
|
+
return self.parent.open(new_req, timeout=req.timeout)
|
|
10617
|
+
|
|
10618
|
+
http_error_301 = http_error_303 = http_error_307 = http_error_308 = http_error_302
|
|
10504
10619
|
|
|
10505
10620
|
|
|
10506
10621
|
_WEB_OPENER = urllib.request.build_opener(_ValidatingRedirectHandler)
|
|
10507
10622
|
|
|
10508
10623
|
|
|
10509
10624
|
def _read_limited_body(stream, content_encoding: str, max_bytes: int) -> tuple[bytes, bool]:
|
|
10510
|
-
"""Lee el cuerpo ya descomprimido hasta `max_bytes
|
|
10625
|
+
"""Lee el cuerpo ya descomprimido hasta `max_bytes` (y acota los bytes comprimidos leídos); indica si truncó."""
|
|
10511
10626
|
encoding = (content_encoding or "").strip().lower()
|
|
10512
10627
|
# MAX_WBITS | 32 detecta la cabecera gzip o zlib.
|
|
10513
10628
|
decompressor = zlib.decompressobj(zlib.MAX_WBITS | 32) if encoding in ("gzip", "x-gzip", "deflate") else None
|
|
10514
10629
|
data = bytearray()
|
|
10630
|
+
raw_read = 0
|
|
10631
|
+
max_raw = max(max_bytes, WEB_FETCH_MAX_BYTES)
|
|
10632
|
+
truncated = False
|
|
10515
10633
|
while len(data) <= max_bytes:
|
|
10516
10634
|
chunk = stream.read(WEB_FETCH_READ_CHUNK)
|
|
10517
10635
|
if not chunk:
|
|
10518
10636
|
break
|
|
10637
|
+
raw_read += len(chunk)
|
|
10519
10638
|
if decompressor:
|
|
10520
10639
|
# La salida se limita al hueco restante: un cuerpo comprimido no puede crecer sin tope.
|
|
10521
10640
|
chunk = decompressor.decompress(chunk, max_bytes + 1 - len(data))
|
|
10522
10641
|
data += chunk
|
|
10523
|
-
|
|
10642
|
+
if raw_read > max_raw:
|
|
10643
|
+
truncated = True
|
|
10644
|
+
break
|
|
10645
|
+
truncated = truncated or len(data) > max_bytes
|
|
10524
10646
|
return bytes(data[:max_bytes]), truncated
|
|
10525
10647
|
|
|
10526
10648
|
|
|
@@ -10614,6 +10736,8 @@ def _fetch_web_resource_unpaced(url: str, params: dict, hostname: str, parsed, t
|
|
|
10614
10736
|
err_body = he.read(2048).decode("utf-8", errors="replace")
|
|
10615
10737
|
except OSError:
|
|
10616
10738
|
pass
|
|
10739
|
+
finally:
|
|
10740
|
+
he.close()
|
|
10617
10741
|
return {
|
|
10618
10742
|
"ok": False,
|
|
10619
10743
|
"status": he.code,
|
|
@@ -10895,6 +11019,8 @@ def browser_url_error(url: str) -> str | None:
|
|
|
10895
11019
|
"""Por qué browser_action no abre la URL, o None: solo http(s), y nunca metadatos cloud ni enlace local.
|
|
10896
11020
|
localhost y la red privada sí, para probar webs en desarrollo. Solo se valida la URL pedida: lo que la
|
|
10897
11021
|
página abra después queda fuera."""
|
|
11022
|
+
if "\\" in url:
|
|
11023
|
+
return "The URL must not contain backslashes."
|
|
10898
11024
|
parsed = urllib.parse.urlparse(url)
|
|
10899
11025
|
if parsed.scheme not in ("http", "https"):
|
|
10900
11026
|
return f"browser_action only opens http:// and https:// URLs, not '{parsed.scheme or url}'."
|
|
@@ -11103,10 +11229,10 @@ def _rereads_runs(state: dict) -> bool:
|
|
|
11103
11229
|
|
|
11104
11230
|
def stop_zerochat_server(server: ThreadingHTTPServer):
|
|
11105
11231
|
"""Detiene limpiamente el servidor y todos los subsistemas evitando reentradas."""
|
|
11106
|
-
if _SERVER_SHUTTING_DOWN.is_set():
|
|
11107
|
-
return
|
|
11108
|
-
_SERVER_SHUTTING_DOWN.set()
|
|
11109
11232
|
with _SHUTDOWN_LOCK:
|
|
11233
|
+
if _SERVER_SHUTTING_DOWN.is_set():
|
|
11234
|
+
return
|
|
11235
|
+
_SERVER_SHUTTING_DOWN.set()
|
|
11110
11236
|
for listener in list(_SHUTDOWN_LISTENERS):
|
|
11111
11237
|
listener.set()
|
|
11112
11238
|
HEARTBEAT_WATCHDOG_STOP.set()
|
|
@@ -11315,8 +11441,8 @@ def run_supervisor(server: ThreadingHTTPServer, session: RunSession, runner_proc
|
|
|
11315
11441
|
proc_done.set()
|
|
11316
11442
|
wake.set()
|
|
11317
11443
|
threading.Thread(target=_watch_proc, name="run-proc-wait", daemon=True).start()
|
|
11318
|
-
deadline = None if session.timeout_seconds is None else session.
|
|
11319
|
-
woken = wake.wait(None if deadline is None else max(0.0, deadline - time.
|
|
11444
|
+
deadline = None if session.timeout_seconds is None else session.started_monotonic + session.timeout_seconds
|
|
11445
|
+
woken = wake.wait(None if deadline is None else max(0.0, deadline - time.monotonic()))
|
|
11320
11446
|
# El latido o una señal ya detienen el servidor: el resultado queda vacío y el runner no sigue por su cuenta.
|
|
11321
11447
|
if _SERVER_SHUTTING_DOWN.is_set():
|
|
11322
11448
|
if runner_proc is not None:
|
|
@@ -11374,7 +11500,8 @@ def launch_node_runner(url: str) -> tuple[subprocess.Popen, IO[bytes]] | None:
|
|
|
11374
11500
|
# En desarrollo los módulos cambian sin subir la versión: se descargan siempre.
|
|
11375
11501
|
cache_policy = RUNNER_CACHE_ALWAYS_DOWNLOAD if get_dev_root() is not None else RUNNER_CACHE_BY_VERSION
|
|
11376
11502
|
cmd = [node, "--permission", f"--allow-fs-read={cache_dir}", f"--allow-fs-write={cache_dir}",
|
|
11377
|
-
"-e", RUNNER_LOADER_SCRIPT, str(cache_file),
|
|
11503
|
+
"-e", RUNNER_LOADER_SCRIPT, str(cache_file), cache_policy]
|
|
11504
|
+
env = {**os.environ, RUNNER_URL_ENV: url}
|
|
11378
11505
|
try:
|
|
11379
11506
|
stderr_log = tempfile.TemporaryFile() # noqa: SIM115 - vive lo que la ejecución; se cierra al salir
|
|
11380
11507
|
proc = subprocess.Popen(
|
|
@@ -11382,6 +11509,7 @@ def launch_node_runner(url: str) -> tuple[subprocess.Popen, IO[bytes]] | None:
|
|
|
11382
11509
|
stdin=subprocess.PIPE, # Nunca se escribe: al cerrarse porque este proceso muere, el runner termina.
|
|
11383
11510
|
stdout=subprocess.DEVNULL,
|
|
11384
11511
|
stderr=stderr_log,
|
|
11512
|
+
env=env,
|
|
11385
11513
|
start_new_session=True,
|
|
11386
11514
|
)
|
|
11387
11515
|
return proc, stderr_log
|
|
@@ -11408,7 +11536,7 @@ LOCAL_TOOLS_DEFINITIONS = [
|
|
|
11408
11536
|
},
|
|
11409
11537
|
{
|
|
11410
11538
|
"name": "read_file",
|
|
11411
|
-
"description": "Read a text file
|
|
11539
|
+
"description": "Read a text file (whole, by line range, or last lines with tail_lines) or a raster image (PNG, JPEG, WebP, GIF up to 6 MB, delivered as visual evidence).",
|
|
11412
11540
|
"inputSchema": {
|
|
11413
11541
|
"type": "object",
|
|
11414
11542
|
"properties": {
|
|
@@ -11569,21 +11697,46 @@ LOCAL_TOOLS_DEFINITIONS = [
|
|
|
11569
11697
|
{
|
|
11570
11698
|
"name": "browser_fill_secret",
|
|
11571
11699
|
"description": (
|
|
11572
|
-
"Fill a saved project secret into
|
|
11573
|
-
"
|
|
11574
|
-
"mapping each character (e.g. '0'..'9') to its button ref or [x, y] coordinates for virtual keypads."
|
|
11700
|
+
"Fill a saved project secret into a text/password input in Playwright MCP via browser_type "
|
|
11701
|
+
"using its snapshot element ref, without exposing the secret value to the model or chat history."
|
|
11575
11702
|
),
|
|
11576
11703
|
"inputSchema": {
|
|
11577
11704
|
"type": "object",
|
|
11578
11705
|
"properties": {
|
|
11579
11706
|
"secret": {"type": "string", "maxLength": 64, "description": "Name of the saved project secret"},
|
|
11580
|
-
"
|
|
11581
|
-
"ref": {"type": "string", "maxLength": 128, "description": "Playwright snapshot element ref for mode='input'"},
|
|
11707
|
+
"ref": {"type": "string", "maxLength": 128, "description": "Playwright snapshot element ref for the input field"},
|
|
11582
11708
|
"element": {"type": "string", "maxLength": 256, "description": "Human-readable description of the input element"},
|
|
11583
|
-
"submit": {"type": "boolean", "description": "Press Enter after typing
|
|
11584
|
-
|
|
11709
|
+
"submit": {"type": "boolean", "description": "Press Enter after typing", "default": False},
|
|
11710
|
+
},
|
|
11711
|
+
"required": ["secret", "ref"]
|
|
11712
|
+
}
|
|
11713
|
+
},
|
|
11714
|
+
{
|
|
11715
|
+
"name": "browser_save_state",
|
|
11716
|
+
"description": (
|
|
11717
|
+
"Save the current Playwright browser session state (cookies and localStorage) under a name scoped to this project "
|
|
11718
|
+
"so later runs can reuse an authenticated session without repeating 2FA."
|
|
11719
|
+
),
|
|
11720
|
+
"inputSchema": {
|
|
11721
|
+
"type": "object",
|
|
11722
|
+
"properties": {
|
|
11723
|
+
"name": {"type": "string", "maxLength": 64, "description": "State name (letters, digits, '-' or '_')"}
|
|
11585
11724
|
},
|
|
11586
|
-
"required": ["
|
|
11725
|
+
"required": ["name"]
|
|
11726
|
+
}
|
|
11727
|
+
},
|
|
11728
|
+
{
|
|
11729
|
+
"name": "browser_load_state",
|
|
11730
|
+
"description": (
|
|
11731
|
+
"Restore a previously saved Playwright browser session state (cookies and localStorage) for this project. "
|
|
11732
|
+
"Clears current cookies and localStorage before restoring."
|
|
11733
|
+
),
|
|
11734
|
+
"inputSchema": {
|
|
11735
|
+
"type": "object",
|
|
11736
|
+
"properties": {
|
|
11737
|
+
"name": {"type": "string", "maxLength": 64, "description": "Name of the saved browser state to restore"}
|
|
11738
|
+
},
|
|
11739
|
+
"required": ["name"]
|
|
11587
11740
|
}
|
|
11588
11741
|
}
|
|
11589
11742
|
]
|
|
@@ -11693,6 +11846,8 @@ LOCAL_TOOL_HANDLERS = {
|
|
|
11693
11846
|
"get_diagnostics": get_diagnostics,
|
|
11694
11847
|
"browser_action": browser_action,
|
|
11695
11848
|
"browser_fill_secret": browser_fill_secret,
|
|
11849
|
+
"browser_save_state": browser_save_state,
|
|
11850
|
+
"browser_load_state": browser_load_state,
|
|
11696
11851
|
AGENTS_TOOL: check_agents,
|
|
11697
11852
|
LAUNCH_AGENT_TOOL: launch_agent,
|
|
11698
11853
|
STOP_AGENT_TOOL: stop_agent,
|
|
@@ -11739,9 +11894,6 @@ def validate_local_tool_arguments(tool_name: str, arguments: dict) -> str | None
|
|
|
11739
11894
|
if tool_name == "browser_action":
|
|
11740
11895
|
if arguments.get("action") not in BROWSER_ACTIONS:
|
|
11741
11896
|
return f"Acción de navegador no permitida: {arguments.get('action')}"
|
|
11742
|
-
if tool_name == "browser_fill_secret":
|
|
11743
|
-
if arguments.get("mode") not in BROWSER_SECRET_MODES:
|
|
11744
|
-
return f"Modalidad no permitida: {arguments.get('mode')}"
|
|
11745
11897
|
|
|
11746
11898
|
return None
|
|
11747
11899
|
|
|
@@ -11771,7 +11923,7 @@ def execute_tool(origin: str, tool_name: str, args: dict, ctx: SecurityContext,
|
|
|
11771
11923
|
if origin == "local":
|
|
11772
11924
|
if tool_name == "browser_action":
|
|
11773
11925
|
browser = tool_name
|
|
11774
|
-
elif tool_name
|
|
11926
|
+
elif tool_name in PLAYWRIGHT_LOCAL_TOOLS:
|
|
11775
11927
|
browser = PLAYWRIGHT_SERVER_ID
|
|
11776
11928
|
else:
|
|
11777
11929
|
browser = None
|
|
@@ -11911,6 +12063,16 @@ def call_tool(params: dict, ctx: SecurityContext) -> tuple[dict | None, dict | N
|
|
|
11911
12063
|
origin = "external"
|
|
11912
12064
|
else:
|
|
11913
12065
|
return None, {"code": -32601, "message": f"Herramienta local '{tool_name}' no encontrada."}, ""
|
|
12066
|
+
session = current_run_session()
|
|
12067
|
+
if session is not None and session.disabled_tools:
|
|
12068
|
+
disabled = set(session.disabled_tools)
|
|
12069
|
+
server_id = GLOBAL_MCP_MANAGER.server_of(tool_name) if origin == "external" else None
|
|
12070
|
+
if (tool_name in disabled or (server_id and server_id in disabled)
|
|
12071
|
+
or (origin == "local" and tool_name in PLAYWRIGHT_LOCAL_TOOLS and PLAYWRIGHT_SERVER_ID in disabled)):
|
|
12072
|
+
return {
|
|
12073
|
+
"content": [{"type": "text", "text": _tool_error(f"Herramienta '{tool_name}' desactivada en esta ejecución.")}],
|
|
12074
|
+
"isError": True,
|
|
12075
|
+
}, None, ""
|
|
11914
12076
|
raw_args = params.get("arguments")
|
|
11915
12077
|
args = dict(raw_args) if isinstance(raw_args, dict) else {}
|
|
11916
12078
|
meta = params.get("_meta") if isinstance(params.get("_meta"), dict) else {}
|
|
@@ -12233,13 +12395,13 @@ def static_file_target(root: Path, rel_path: str) -> Path | None:
|
|
|
12233
12395
|
salvo ficheros ocultos (.git, .env, .zerochat) y rutas que al resolverse salen de ella (enlaces simbólicos).
|
|
12234
12396
|
"""
|
|
12235
12397
|
clean_rel = rel_path.split("?", 1)[0].lstrip("/")
|
|
12236
|
-
if not clean_rel:
|
|
12398
|
+
if not clean_rel or "\x00" in clean_rel:
|
|
12237
12399
|
return None
|
|
12238
12400
|
base = root.resolve()
|
|
12239
|
-
target = (base / clean_rel).resolve()
|
|
12240
12401
|
try:
|
|
12402
|
+
target = (base / clean_rel).resolve()
|
|
12241
12403
|
parts = target.relative_to(base).parts
|
|
12242
|
-
except ValueError:
|
|
12404
|
+
except (OSError, ValueError):
|
|
12243
12405
|
return None
|
|
12244
12406
|
if any(part.startswith(".") for part in parts) or not target.is_file():
|
|
12245
12407
|
return None
|
|
@@ -12840,8 +13002,9 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
|
|
|
12840
13002
|
launch = None
|
|
12841
13003
|
if args.run_file is not None and request.get("agent"):
|
|
12842
13004
|
launch = {"profile": profile_name, **{key: request[key] for key in RUN_LAUNCH_KEYS if key in request}}
|
|
12843
|
-
|
|
12844
|
-
|
|
13005
|
+
subagents_env = os.environ.pop(ZEROCHAT_RUN_SUBAGENTS_ENV, None)
|
|
13006
|
+
subagents = (args.run_file is None and conversation_id is not None and not (conv and conv.get("agent"))
|
|
13007
|
+
and subagents_env == "1")
|
|
12845
13008
|
return RunSession(prompt, profile_name, export_path, conversation_id=conversation_id, profile_data=profile_data,
|
|
12846
13009
|
new_conversation_id=new_conversation_id, system_data_prompt=options.get("systemDataPrompt"),
|
|
12847
13010
|
max_steps=options.get("maxSteps"), timeout_seconds=options.get("timeout"),
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|