zerochat 10.12.0__tar.gz → 10.13.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.12.0/zerochat.egg-info → zerochat-10.13.0}/PKG-INFO +1 -1
- {zerochat-10.12.0 → zerochat-10.13.0}/pyproject.toml +1 -1
- {zerochat-10.12.0 → zerochat-10.13.0/zerochat.egg-info}/PKG-INFO +1 -1
- {zerochat-10.12.0 → zerochat-10.13.0}/zerochat.py +336 -193
- {zerochat-10.12.0 → zerochat-10.13.0}/LICENSE +0 -0
- {zerochat-10.12.0 → zerochat-10.13.0}/README.md +0 -0
- {zerochat-10.12.0 → zerochat-10.13.0}/setup.cfg +0 -0
- {zerochat-10.12.0 → zerochat-10.13.0}/zerochat.egg-info/SOURCES.txt +0 -0
- {zerochat-10.12.0 → zerochat-10.13.0}/zerochat.egg-info/dependency_links.txt +0 -0
- {zerochat-10.12.0 → zerochat-10.13.0}/zerochat.egg-info/entry_points.txt +0 -0
- {zerochat-10.12.0 → zerochat-10.13.0}/zerochat.egg-info/top_level.txt +0 -0
|
@@ -26,6 +26,7 @@ import hashlib
|
|
|
26
26
|
import hmac
|
|
27
27
|
import html
|
|
28
28
|
import importlib.metadata
|
|
29
|
+
import inspect
|
|
29
30
|
import ipaddress
|
|
30
31
|
import itertools
|
|
31
32
|
import json
|
|
@@ -55,7 +56,7 @@ import zlib
|
|
|
55
56
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
56
57
|
from pathlib import Path
|
|
57
58
|
|
|
58
|
-
SOURCE_BACKEND_VERSION = "10.
|
|
59
|
+
SOURCE_BACKEND_VERSION = "10.13.0"
|
|
59
60
|
|
|
60
61
|
def _read_source_version(filename: str) -> str | None:
|
|
61
62
|
"""Lee la versión de un archivo del repositorio cuando se ejecuta desde fuentes."""
|
|
@@ -224,7 +225,7 @@ def get_dev_root() -> Path | None:
|
|
|
224
225
|
"""
|
|
225
226
|
Detecta si zerochat.py se está ejecutando en el directorio de desarrollo del repositorio.
|
|
226
227
|
Comprueba si existen zerochat.html, js/ y css/ en el directorio del script o en cwd.
|
|
227
|
-
Se calcula una vez:
|
|
228
|
+
Se calcula una vez, al arrancar: la interfaz servida no depende del proyecto de cada pestaña.
|
|
228
229
|
"""
|
|
229
230
|
script_dir = Path(__file__).resolve().parent
|
|
230
231
|
cwd = Path.cwd().resolve()
|
|
@@ -675,11 +676,12 @@ def _powershell_runner(command: str) -> str:
|
|
|
675
676
|
class CommandJob:
|
|
676
677
|
"""Un comando lanzado por run_command: su proceso, su log y su estado."""
|
|
677
678
|
|
|
678
|
-
def __init__(self, job_id: int, key: str | None, command: str,
|
|
679
|
+
def __init__(self, job_id: int, key: str | None, command: str, project: SecurityContext, background: bool, log_path: Path):
|
|
679
680
|
self.id = job_id
|
|
680
681
|
self.key = key
|
|
681
682
|
self.command = command
|
|
682
|
-
self.cwd =
|
|
683
|
+
self.cwd = str(project.workspace_dir)
|
|
684
|
+
self.project = project.key
|
|
683
685
|
self.background = background
|
|
684
686
|
self.log_path = log_path
|
|
685
687
|
self.started_at = time.time()
|
|
@@ -838,7 +840,10 @@ class CommandJob:
|
|
|
838
840
|
|
|
839
841
|
|
|
840
842
|
class JobManager:
|
|
841
|
-
"""
|
|
843
|
+
"""
|
|
844
|
+
Registro de los comandos lanzados en esta sesión del servidor. Cada comando es del proyecto en el que
|
|
845
|
+
arrancó (su cwd): las consultas indican el proyecto y solo ven los suyos; None (al apagar) los ve todos.
|
|
846
|
+
"""
|
|
842
847
|
|
|
843
848
|
def __init__(self):
|
|
844
849
|
self._jobs: dict[int, CommandJob] = {}
|
|
@@ -880,12 +885,11 @@ class JobManager:
|
|
|
880
885
|
except OSError:
|
|
881
886
|
pass
|
|
882
887
|
|
|
883
|
-
def start(self, command: str, background: bool, key: str | None = None) -> CommandJob:
|
|
888
|
+
def start(self, command: str, background: bool, project: SecurityContext, key: str | None = None) -> CommandJob:
|
|
884
889
|
if not isinstance(command, str) or not command.strip():
|
|
885
890
|
raise ValueError("The command is empty.")
|
|
886
891
|
if key is not None and not (isinstance(key, str) and JOB_KEY_PATTERN.fullmatch(key)):
|
|
887
892
|
key = None
|
|
888
|
-
cwd = str(Path.cwd().resolve())
|
|
889
893
|
with self._lock:
|
|
890
894
|
if sum(1 for job in self._jobs.values() if job.status == "running") >= MAX_RUNNING_JOBS:
|
|
891
895
|
raise ValueError(
|
|
@@ -895,7 +899,7 @@ class JobManager:
|
|
|
895
899
|
self._prune()
|
|
896
900
|
job_id = self._next_id
|
|
897
901
|
self._next_id += 1
|
|
898
|
-
job = CommandJob(job_id, key, command,
|
|
902
|
+
job = CommandJob(job_id, key, command, project, background, self._session_dir() / f"job-{job_id}.log")
|
|
899
903
|
self._jobs[job_id] = job
|
|
900
904
|
try:
|
|
901
905
|
self._launch(job)
|
|
@@ -964,17 +968,18 @@ class JobManager:
|
|
|
964
968
|
self._write_registry()
|
|
965
969
|
job.done.set()
|
|
966
970
|
|
|
967
|
-
def get(self, job_id=None, key=None) -> CommandJob | None:
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
971
|
+
def get(self, project: str, job_id=None, key=None) -> CommandJob | None:
|
|
972
|
+
jobs = self.list(project)
|
|
973
|
+
if isinstance(job_id, int) and not isinstance(job_id, bool):
|
|
974
|
+
return next((job for job in jobs if job.id == job_id), None)
|
|
975
|
+
if isinstance(key, str) and key:
|
|
976
|
+
return next((job for job in jobs if job.key == key), None)
|
|
973
977
|
return None
|
|
974
978
|
|
|
975
|
-
def list(self) -> list[CommandJob]:
|
|
979
|
+
def list(self, project: str | None) -> list[CommandJob]:
|
|
980
|
+
"""Comandos del proyecto con esa clave (SecurityContext.key); None, los de todos."""
|
|
976
981
|
with self._lock:
|
|
977
|
-
return
|
|
982
|
+
return [job for job in self._jobs.values() if project is None or job.project == project]
|
|
978
983
|
|
|
979
984
|
def stop(self, job: CommandJob, reason: str) -> CommandJob:
|
|
980
985
|
"""Termina el grupo del comando: primero con cortesía y, si no basta, a la fuerza."""
|
|
@@ -999,14 +1004,14 @@ class JobManager:
|
|
|
999
1004
|
job.done.wait(JOB_STOP_GRACE_SECONDS)
|
|
1000
1005
|
return job
|
|
1001
1006
|
|
|
1002
|
-
def report_finished(self, ids: list[int]) -> list[dict]:
|
|
1007
|
+
def report_finished(self, ids: list[int], project: str) -> list[dict]:
|
|
1003
1008
|
"""Final de los comandos indicados que han terminado sin que el modelo lo haya visto.
|
|
1004
1009
|
|
|
1005
1010
|
Cada final se entrega una sola vez: queda marcado como visto.
|
|
1006
1011
|
"""
|
|
1007
1012
|
reports = []
|
|
1008
1013
|
for job_id in dict.fromkeys(ids):
|
|
1009
|
-
job = self.get(job_id=job_id)
|
|
1014
|
+
job = self.get(project, job_id=job_id)
|
|
1010
1015
|
if job is None or not job.done.is_set() or job.reported:
|
|
1011
1016
|
continue
|
|
1012
1017
|
job.reported = True
|
|
@@ -1015,11 +1020,11 @@ class JobManager:
|
|
|
1015
1020
|
reports.append({**job.summary(), "tail": tail, "log_file": str(job.log_path)})
|
|
1016
1021
|
return reports
|
|
1017
1022
|
|
|
1018
|
-
def running(self) -> list[CommandJob]:
|
|
1019
|
-
return [job for job in self.list() if not job.done.is_set()]
|
|
1023
|
+
def running(self, project: str | None) -> list[CommandJob]:
|
|
1024
|
+
return [job for job in self.list(project) if not job.done.is_set()]
|
|
1020
1025
|
|
|
1021
1026
|
def stop_all(self, reason: str = "shutdown"):
|
|
1022
|
-
threads = [threading.Thread(target=self.stop, args=(job, reason), daemon=True) for job in self.running()]
|
|
1027
|
+
threads = [threading.Thread(target=self.stop, args=(job, reason), daemon=True) for job in self.running(None)]
|
|
1023
1028
|
for thread in threads:
|
|
1024
1029
|
thread.start()
|
|
1025
1030
|
for thread in threads:
|
|
@@ -1070,10 +1075,10 @@ def _job_result(job: CommandJob, note: str | None = None, output_field: str = "o
|
|
|
1070
1075
|
return json.dumps(result, ensure_ascii=False, indent=2)
|
|
1071
1076
|
|
|
1072
1077
|
|
|
1073
|
-
def run_command(command: str, timeout_seconds: int = COMMAND_DEFAULT_TIMEOUT, background: bool = False, job_key: str | None = None) -> str:
|
|
1078
|
+
def run_command(command: str, timeout_seconds: int = COMMAND_DEFAULT_TIMEOUT, background: bool = False, job_key: str | None = None, *, ctx: SecurityContext) -> str:
|
|
1074
1079
|
"""Ejecuta un comando en una shell nueva en el directorio del proyecto."""
|
|
1075
1080
|
try:
|
|
1076
|
-
job = JOBS.start(command, background=bool(background), key=job_key)
|
|
1081
|
+
job = JOBS.start(command, background=bool(background), project=ctx, key=job_key)
|
|
1077
1082
|
except (ValueError, OSError) as exc:
|
|
1078
1083
|
return _tool_error(str(exc), os=DETECTED_OS)
|
|
1079
1084
|
if background:
|
|
@@ -1094,11 +1099,11 @@ def run_command(command: str, timeout_seconds: int = COMMAND_DEFAULT_TIMEOUT, ba
|
|
|
1094
1099
|
return _job_result(job)
|
|
1095
1100
|
|
|
1096
1101
|
|
|
1097
|
-
def check_command(job_id: int, wait_seconds: int = 0, stop: bool = False) -> str:
|
|
1102
|
+
def check_command(job_id: int, wait_seconds: int = 0, stop: bool = False, *, ctx: SecurityContext) -> str:
|
|
1098
1103
|
"""Estado y salida nueva de un comando lanzado por run_command; puede esperarlo o detenerlo."""
|
|
1099
|
-
job = JOBS.get(job_id=job_id)
|
|
1104
|
+
job = JOBS.get(ctx.key, job_id=job_id)
|
|
1100
1105
|
if job is None:
|
|
1101
|
-
return _tool_error(f"Unknown job_id {job_id}. It may belong to a previous ZeroChat session.", os=DETECTED_OS)
|
|
1106
|
+
return _tool_error(f"Unknown job_id {job_id}. It may belong to a previous ZeroChat session or to another project.", os=DETECTED_OS)
|
|
1102
1107
|
if stop:
|
|
1103
1108
|
JOBS.stop(job, "model")
|
|
1104
1109
|
else:
|
|
@@ -1214,14 +1219,14 @@ def _configured_gui_diff_tool(git_bin: str, repo_root: Path) -> str:
|
|
|
1214
1219
|
return ""
|
|
1215
1220
|
|
|
1216
1221
|
|
|
1217
|
-
def _open_gui_file_diff(path: str, commit_fallback: bool = False) -> dict:
|
|
1222
|
+
def _open_gui_file_diff(path: str, ctx: SecurityContext, commit_fallback: bool = False) -> dict:
|
|
1218
1223
|
"""Abre un visor externo de diffs (git difftool) en una ventana del sistema operativo."""
|
|
1219
1224
|
if not isinstance(path, str) or not path.strip():
|
|
1220
1225
|
raise ValueError("La ruta del archivo está vacía.")
|
|
1221
1226
|
if len(path) > MAX_PATH_LENGTH:
|
|
1222
1227
|
raise ValueError("La ruta del archivo excede el tamaño máximo permitido.")
|
|
1223
1228
|
|
|
1224
|
-
target =
|
|
1229
|
+
target = ctx.absolute(path)
|
|
1225
1230
|
if not target.exists():
|
|
1226
1231
|
raise ValueError(f"El archivo '{path}' no existe.")
|
|
1227
1232
|
if not target.is_file():
|
|
@@ -1681,14 +1686,14 @@ def render_diff_html(
|
|
|
1681
1686
|
</html>"""
|
|
1682
1687
|
|
|
1683
1688
|
|
|
1684
|
-
def generate_file_diff(path: str, commit_fallback: bool = False, context_lines: int = DIFF_CONTEXT_LINES) -> dict:
|
|
1689
|
+
def generate_file_diff(path: str, ctx: SecurityContext, commit_fallback: bool = False, context_lines: int = DIFF_CONTEXT_LINES) -> dict:
|
|
1685
1690
|
"""Calcula y devuelve el diff de un archivo frente a Git HEAD o su último commit, incluyendo HTML."""
|
|
1686
1691
|
if not isinstance(path, str) or not path.strip():
|
|
1687
1692
|
raise ValueError("La ruta del archivo está vacía.")
|
|
1688
1693
|
if len(path) > MAX_PATH_LENGTH:
|
|
1689
1694
|
raise ValueError("La ruta del archivo excede el tamaño máximo permitido.")
|
|
1690
1695
|
|
|
1691
|
-
target =
|
|
1696
|
+
target = ctx.absolute(path)
|
|
1692
1697
|
if not target.exists():
|
|
1693
1698
|
raise ValueError(f"El archivo '{path}' no existe.")
|
|
1694
1699
|
if not target.is_file():
|
|
@@ -1849,7 +1854,7 @@ def generate_file_diff(path: str, commit_fallback: bool = False, context_lines:
|
|
|
1849
1854
|
}
|
|
1850
1855
|
|
|
1851
1856
|
|
|
1852
|
-
def open_file_diff(path: str, commit_fallback: bool = False, gui: bool = False, context_lines: int = DIFF_CONTEXT_LINES) -> dict:
|
|
1857
|
+
def open_file_diff(path: str, ctx: SecurityContext, commit_fallback: bool = False, gui: bool = False, context_lines: int = DIFF_CONTEXT_LINES) -> dict:
|
|
1853
1858
|
"""Obtiene el diff de un archivo asociado a Git.
|
|
1854
1859
|
|
|
1855
1860
|
Por defecto genera el diff con el visor propio de ZeroChat (HTML y texto), apto para
|
|
@@ -1857,8 +1862,8 @@ def open_file_diff(path: str, commit_fallback: bool = False, gui: bool = False,
|
|
|
1857
1862
|
Con `gui=True` lanza el visor gráfico externo configurado en Git (difftool).
|
|
1858
1863
|
"""
|
|
1859
1864
|
if gui:
|
|
1860
|
-
return _open_gui_file_diff(path, commit_fallback)
|
|
1861
|
-
return generate_file_diff(path, commit_fallback, context_lines=context_lines)
|
|
1865
|
+
return _open_gui_file_diff(path, ctx, commit_fallback)
|
|
1866
|
+
return generate_file_diff(path, ctx, commit_fallback, context_lines=context_lines)
|
|
1862
1867
|
# ==============================================================================
|
|
1863
1868
|
# Generated from services/ by scripts/build-managed-services.mjs. Do not edit.
|
|
1864
1869
|
# ==============================================================================
|
|
@@ -1895,6 +1900,8 @@ POLICY_STATE_VERSION = 6
|
|
|
1895
1900
|
CHALLENGE_TTL_MS = 600_000
|
|
1896
1901
|
AUTHORIZE_DECISIONS = ("allow_once", "allow_session", "allow_project", "allow_always", "allow_server_always")
|
|
1897
1902
|
MAX_POLICY_ENTRIES = 500
|
|
1903
|
+
# Proyectos con sesión en memoria: al pasar del tope se olvida la del usado hace más tiempo sin comandos en marcha.
|
|
1904
|
+
MAX_PROJECT_SESSIONS = 16
|
|
1898
1905
|
|
|
1899
1906
|
DIRECTORY_RULE_PATTERN = re.compile(r"^(R|W|RW):(.+)$")
|
|
1900
1907
|
COMMAND_TOOL = "run_command"
|
|
@@ -1931,25 +1938,69 @@ WORKSPACE_TRUST_GLOBAL_COMMANDS = re.compile(r"(?:^|\s)(?:sudo|su|doas|mkfs|rebo
|
|
|
1931
1938
|
WORKSPACE_TRUST_OUTSIDE_REFERENCE = re.compile(r"(?:^|[\s=:'\"])(?:[\\/~]|[A-Za-z]:[\\/])|\$|(?:^|[\s=:'\"\\/])\.\.(?=[\s\\/'\"]|$)")
|
|
1932
1939
|
|
|
1933
1940
|
|
|
1941
|
+
# Proyecto por defecto: la carpeta de arranque, para las peticiones que no indican el suyo (la primera
|
|
1942
|
+
# conexión de una pestaña, las ejecuciones en servidor). El proceso nunca cambia de directorio: cada
|
|
1943
|
+
# petición recibe su proyecto en un SecurityContext.
|
|
1944
|
+
PROJECT_DIR = Path.cwd().resolve()
|
|
1945
|
+
|
|
1946
|
+
|
|
1947
|
+
def project_context() -> "SecurityContext":
|
|
1948
|
+
"""Contexto del proyecto por defecto del servidor."""
|
|
1949
|
+
return SecurityContext(PROJECT_DIR)
|
|
1950
|
+
|
|
1951
|
+
|
|
1952
|
+
# Código JSON-RPC de una petición cuyo proyecto (cabecera X-ZeroChat-Project) ya no existe.
|
|
1953
|
+
PROJECT_GONE_CODE = -32003
|
|
1954
|
+
|
|
1955
|
+
|
|
1956
|
+
class ProjectGoneError(ValueError):
|
|
1957
|
+
"""La carpeta del proyecto de la pestaña ya no existe."""
|
|
1958
|
+
|
|
1959
|
+
|
|
1960
|
+
def request_project_context(raw: str | None, *, fallback: bool) -> "SecurityContext":
|
|
1961
|
+
"""
|
|
1962
|
+
Proyecto de una petición: la carpeta absoluta de la cabecera X-ZeroChat-Project (codificada como en
|
|
1963
|
+
una URL) o, sin cabecera, el proyecto por defecto. Una carpeta que ya no existe es un error, salvo con
|
|
1964
|
+
fallback (initialize), que devuelve el proyecto por defecto para que la pestaña sepa dónde está.
|
|
1965
|
+
"""
|
|
1966
|
+
if not raw:
|
|
1967
|
+
return project_context()
|
|
1968
|
+
path = Path(urllib.parse.unquote(raw))
|
|
1969
|
+
if path.is_absolute() and path.is_dir():
|
|
1970
|
+
return SecurityContext(path.resolve())
|
|
1971
|
+
if fallback:
|
|
1972
|
+
return project_context()
|
|
1973
|
+
raise ProjectGoneError(f"La carpeta del proyecto de la pestaña ya no existe: {path}")
|
|
1974
|
+
|
|
1975
|
+
|
|
1934
1976
|
@dataclasses.dataclass
|
|
1935
1977
|
class SecurityContext:
|
|
1936
|
-
"""
|
|
1937
|
-
workspace_dir: Path
|
|
1978
|
+
"""Proyecto en el que actúa una petición: base de sus rutas relativas, de sus comandos y de sus permisos."""
|
|
1979
|
+
workspace_dir: Path
|
|
1980
|
+
|
|
1981
|
+
@property
|
|
1982
|
+
def key(self) -> str:
|
|
1983
|
+
"""Identificador estable del proyecto: la clave de sus sesiones, de sus patrones guardados y de sus comandos."""
|
|
1984
|
+
return normalize_directory_path(str(self.workspace_dir))
|
|
1985
|
+
|
|
1986
|
+
def absolute(self, path: str) -> Path:
|
|
1987
|
+
"""
|
|
1988
|
+
Ruta que una herramienta abre: la resuelta contra la carpeta del proyecto ('~' es la del usuario).
|
|
1989
|
+
Es la misma que evalúan los permisos (resolve_path): colapsa los '..' antes de seguir enlaces
|
|
1990
|
+
simbólicos, así 'enlace/../x' no se permite como una ruta y se abre como otra. ValueError si no es válida.
|
|
1991
|
+
"""
|
|
1992
|
+
norm = normalize_directory_path(str(Path(str(path).strip()).expanduser()))
|
|
1993
|
+
if not norm:
|
|
1994
|
+
raise ValueError(f"Ruta no válida: '{path}'.")
|
|
1995
|
+
target = Path(norm)
|
|
1996
|
+
return (target if target.is_absolute() else self.workspace_dir / target).resolve()
|
|
1938
1997
|
|
|
1939
1998
|
def resolve_path(self, path_str: str) -> Path | None:
|
|
1940
|
-
"""
|
|
1999
|
+
"""La ruta de absolute() para evaluar permisos; None si no es válida o lleva referencias sin resolver ('~', '$VAR')."""
|
|
1941
2000
|
if not isinstance(path_str, str) or contains_unresolved_reference(path_str):
|
|
1942
2001
|
return None
|
|
1943
|
-
norm = normalize_directory_path(path_str)
|
|
1944
|
-
if not norm:
|
|
1945
|
-
return None
|
|
1946
2002
|
try:
|
|
1947
|
-
|
|
1948
|
-
if not target.is_absolute():
|
|
1949
|
-
target = (self.workspace_dir / target).resolve(strict=False)
|
|
1950
|
-
else:
|
|
1951
|
-
target = target.resolve(strict=False)
|
|
1952
|
-
return target
|
|
2003
|
+
return self.absolute(path_str)
|
|
1953
2004
|
except (ValueError, RuntimeError, OSError):
|
|
1954
2005
|
return None
|
|
1955
2006
|
|
|
@@ -2279,17 +2330,46 @@ class AccessDecision:
|
|
|
2279
2330
|
}
|
|
2280
2331
|
|
|
2281
2332
|
|
|
2333
|
+
@dataclasses.dataclass
|
|
2334
|
+
class ProjectSession:
|
|
2335
|
+
"""
|
|
2336
|
+
Lo autorizado en la sesión para un proyecto y sus retos pendientes, en memoria mientras dure el servidor.
|
|
2337
|
+
Lo comparten todas las pestañas y dispositivos que trabajan en ese proyecto.
|
|
2338
|
+
"""
|
|
2339
|
+
last_used: float = 0.0
|
|
2340
|
+
global_policy: str | None = None
|
|
2341
|
+
directory_rules: list[str] | None = None
|
|
2342
|
+
tools: dict[str, dict] = dataclasses.field(default_factory=dict)
|
|
2343
|
+
servers: dict[str, dict] = dataclasses.field(default_factory=dict)
|
|
2344
|
+
command_patterns: list[str] = dataclasses.field(default_factory=list)
|
|
2345
|
+
challenges: dict[str, dict] = dataclasses.field(default_factory=dict)
|
|
2346
|
+
|
|
2347
|
+
def entries(self, kind: str) -> dict[str, dict]:
|
|
2348
|
+
return self.tools if kind == "tools" else self.servers
|
|
2349
|
+
|
|
2350
|
+
|
|
2282
2351
|
class AccessController:
|
|
2283
2352
|
"""Motor de control de acceso y autorización del backend (PDP/PEP)."""
|
|
2284
2353
|
|
|
2285
2354
|
def __init__(self):
|
|
2286
2355
|
self._lock = threading.RLock()
|
|
2287
|
-
self.
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2356
|
+
self.sessions: dict[str, ProjectSession] = {}
|
|
2357
|
+
|
|
2358
|
+
def _session(self, context: SecurityContext) -> ProjectSession:
|
|
2359
|
+
"""
|
|
2360
|
+
Sesión del proyecto de la petición, creada vacía la primera vez. Con MAX_PROJECT_SESSIONS proyectos
|
|
2361
|
+
en memoria, olvida la del usado hace más tiempo que no tenga comandos en marcha (como mucho hay 8
|
|
2362
|
+
comandos a la vez, así que siempre queda alguno sin ellos).
|
|
2363
|
+
"""
|
|
2364
|
+
with self._lock:
|
|
2365
|
+
session = self.sessions.get(context.key)
|
|
2366
|
+
if session is None:
|
|
2367
|
+
if len(self.sessions) >= MAX_PROJECT_SESSIONS:
|
|
2368
|
+
idle = [k for k in self.sessions if not JOBS.running(k)]
|
|
2369
|
+
del self.sessions[min(idle, key=lambda k: self.sessions[k].last_used)]
|
|
2370
|
+
session = self.sessions[context.key] = ProjectSession()
|
|
2371
|
+
session.last_used = time.monotonic()
|
|
2372
|
+
return session
|
|
2293
2373
|
|
|
2294
2374
|
@staticmethod
|
|
2295
2375
|
def _normalize_state(raw: dict | None) -> dict:
|
|
@@ -2316,31 +2396,28 @@ class AccessController:
|
|
|
2316
2396
|
"""Lectura-modificación-escritura transaccional sobre el estado permanente normalizado."""
|
|
2317
2397
|
return update_security_policy_data(lambda raw: mutator(self._normalize_state(raw)))
|
|
2318
2398
|
|
|
2319
|
-
def _effective_state(self) -> dict:
|
|
2320
|
-
"""Una sola lectura del estado permanente combinada con la capa de sesión
|
|
2399
|
+
def _effective_state(self, context: SecurityContext) -> dict:
|
|
2400
|
+
"""Una sola lectura del estado permanente combinada con la capa de sesión del proyecto."""
|
|
2321
2401
|
state = self._read_permanent_state()
|
|
2322
2402
|
with self._lock:
|
|
2403
|
+
session = self._session(context)
|
|
2323
2404
|
return {
|
|
2324
|
-
"globalMcpPolicy":
|
|
2325
|
-
"directoryRules": list(
|
|
2326
|
-
"tools": {**state["tools"], **
|
|
2327
|
-
"servers": {**state["servers"], **
|
|
2328
|
-
"commandPatterns": {**state["commandPatterns"], "session": list(
|
|
2405
|
+
"globalMcpPolicy": session.global_policy if session.global_policy is not None else state["globalMcpPolicy"],
|
|
2406
|
+
"directoryRules": list(session.directory_rules) if session.directory_rules is not None else state["directoryRules"],
|
|
2407
|
+
"tools": {**state["tools"], **session.tools},
|
|
2408
|
+
"servers": {**state["servers"], **session.servers},
|
|
2409
|
+
"commandPatterns": {**state["commandPatterns"], "session": list(session.command_patterns)}
|
|
2329
2410
|
}
|
|
2330
2411
|
|
|
2331
|
-
@staticmethod
|
|
2332
|
-
def _project_key(context: SecurityContext) -> str:
|
|
2333
|
-
return normalize_directory_path(str(context.workspace_dir))
|
|
2334
|
-
|
|
2335
2412
|
def _command_patterns(self, view: dict, context: SecurityContext) -> list[str]:
|
|
2336
2413
|
"""Patrones que rigen en el proyecto: los de todos los proyectos, los de este y los de la sesión."""
|
|
2337
2414
|
patterns = view["commandPatterns"]
|
|
2338
|
-
return [*patterns["global"], *(patterns["projects"].get(
|
|
2415
|
+
return [*patterns["global"], *(patterns["projects"].get(context.key) or []), *patterns["session"]]
|
|
2339
2416
|
|
|
2340
2417
|
def export_state(self, context: SecurityContext) -> dict:
|
|
2341
2418
|
return {
|
|
2342
2419
|
"version": POLICY_STATE_VERSION,
|
|
2343
|
-
**self._effective_state(),
|
|
2420
|
+
**self._effective_state(context),
|
|
2344
2421
|
"defaultDirectoryRule": self.get_default_directory_rule(context)
|
|
2345
2422
|
}
|
|
2346
2423
|
|
|
@@ -2399,9 +2476,6 @@ class AccessController:
|
|
|
2399
2476
|
entry["originalName"] = original_name
|
|
2400
2477
|
return entry
|
|
2401
2478
|
|
|
2402
|
-
def _session_map(self, kind: str) -> dict[str, dict]:
|
|
2403
|
-
return self.session_tools if kind == "tools" else self.session_servers
|
|
2404
|
-
|
|
2405
2479
|
@staticmethod
|
|
2406
2480
|
def _check_entry_limit(state: dict):
|
|
2407
2481
|
"""Único tope de entradas, sobre el estado resultante (guardado o capa de sesión)."""
|
|
@@ -2451,17 +2525,18 @@ class AccessController:
|
|
|
2451
2525
|
self._check_entry_limit(current)
|
|
2452
2526
|
return current
|
|
2453
2527
|
self._update_permanent(mutator)
|
|
2528
|
+
# Lo guardado vale para todos los proyectos: sustituye o revoca lo equivalente en la sesión de cada uno.
|
|
2454
2529
|
with self._lock:
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2530
|
+
for session in self.sessions.values():
|
|
2531
|
+
if clean_global is not None:
|
|
2532
|
+
session.global_policy = None
|
|
2533
|
+
if clean_rules is not None:
|
|
2534
|
+
session.directory_rules = None
|
|
2535
|
+
elif added_rules and session.directory_rules is not None:
|
|
2536
|
+
session.directory_rules = self._append_rules(session.directory_rules, added_rules)
|
|
2537
|
+
for kind, patch in (("tools", clean_tools), ("servers", clean_servers)):
|
|
2538
|
+
for item_id in patch or {}:
|
|
2539
|
+
session.entries(kind).pop(item_id, None)
|
|
2465
2540
|
return self.export_state(context)
|
|
2466
2541
|
|
|
2467
2542
|
@staticmethod
|
|
@@ -2492,15 +2567,16 @@ class AccessController:
|
|
|
2492
2567
|
if isinstance(raw_patterns, dict) else None
|
|
2493
2568
|
|
|
2494
2569
|
with self._lock:
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2570
|
+
session = self._session(context)
|
|
2571
|
+
rules = clean_rules if clean_rules is not None else session.directory_rules
|
|
2572
|
+
tools = self._apply_entry_patch(session.tools, clean_tools or {})
|
|
2573
|
+
servers = self._apply_entry_patch(session.servers, clean_servers or {})
|
|
2498
2574
|
self._check_entry_limit({"directoryRules": rules, "tools": tools, "servers": servers})
|
|
2499
2575
|
if clean_global is not None:
|
|
2500
|
-
|
|
2501
|
-
|
|
2576
|
+
session.global_policy = clean_global
|
|
2577
|
+
session.directory_rules, session.tools, session.servers = rules, tools, servers
|
|
2502
2578
|
if session_patterns is not None:
|
|
2503
|
-
|
|
2579
|
+
session.command_patterns = session_patterns
|
|
2504
2580
|
return self.export_state(context)
|
|
2505
2581
|
|
|
2506
2582
|
@staticmethod
|
|
@@ -2561,26 +2637,21 @@ class AccessController:
|
|
|
2561
2637
|
return {"allowed": False, "rule": None, "path": normalized_dest}
|
|
2562
2638
|
|
|
2563
2639
|
def clear_session(self):
|
|
2564
|
-
"""
|
|
2640
|
+
"""Olvida lo autorizado en la sesión y los retos pendientes de todos los proyectos."""
|
|
2565
2641
|
with self._lock:
|
|
2566
|
-
self.
|
|
2567
|
-
self.session_directory_rules = None
|
|
2568
|
-
self.session_tools.clear()
|
|
2569
|
-
self.session_servers.clear()
|
|
2570
|
-
self.session_command_patterns = []
|
|
2571
|
-
self.pending_challenges.clear()
|
|
2642
|
+
self.sessions.clear()
|
|
2572
2643
|
|
|
2573
2644
|
def create_challenge(self, tool_name: str, args: dict, decision: AccessDecision, *, context: SecurityContext,
|
|
2574
2645
|
server_name: str = "", server_id: str = "", origin: str = "local",
|
|
2575
|
-
job_key: str | None = None) -> dict:
|
|
2646
|
+
job_key: str | None = None, conversation_id: str = "") -> dict:
|
|
2576
2647
|
"""Genera un reto estructurado para solicitar confirmación interactiva al usuario."""
|
|
2577
2648
|
challenge_id = f"auth_{secrets.token_urlsafe(16)}"
|
|
2578
2649
|
now = int(time.time() * 1000)
|
|
2579
|
-
cwd = str(context.workspace_dir.resolve())
|
|
2580
2650
|
with self._lock:
|
|
2581
|
-
|
|
2651
|
+
challenges = self._session(context).challenges
|
|
2652
|
+
expired = [cid for cid, c in challenges.items() if now - c.get("createdAt", 0) > CHALLENGE_TTL_MS]
|
|
2582
2653
|
for cid in expired:
|
|
2583
|
-
|
|
2654
|
+
challenges.pop(cid, None)
|
|
2584
2655
|
|
|
2585
2656
|
challenge_data = {
|
|
2586
2657
|
"id": challenge_id,
|
|
@@ -2590,27 +2661,27 @@ class AccessController:
|
|
|
2590
2661
|
"serverId": server_id or decision.server_id,
|
|
2591
2662
|
"origin": origin,
|
|
2592
2663
|
"jobKey": job_key,
|
|
2593
|
-
"
|
|
2664
|
+
"conversationId": conversation_id,
|
|
2594
2665
|
"createdAt": now
|
|
2595
2666
|
}
|
|
2596
|
-
|
|
2667
|
+
challenges[challenge_id] = challenge_data
|
|
2597
2668
|
return challenge_data
|
|
2598
2669
|
|
|
2599
2670
|
def authorize_challenge(self, challenge_id: str, decision: str, *, context: SecurityContext,
|
|
2600
2671
|
command_pattern: str | None = None, directory_rule: str | None = None) -> dict | None:
|
|
2601
2672
|
"""
|
|
2602
2673
|
Valida la decisión, consume el reto (una única ejecución) y registra la decisión.
|
|
2603
|
-
Devuelve el reto consumido, o None si no existe
|
|
2604
|
-
Una decisión mal formada lanza ValueError y deja el reto pendiente.
|
|
2674
|
+
Devuelve el reto consumido, o None si no existe en el proyecto de la petición, caducó o la decisión
|
|
2675
|
+
no aplica. Una decisión mal formada lanza ValueError y deja el reto pendiente.
|
|
2605
2676
|
"""
|
|
2606
2677
|
now = int(time.time() * 1000)
|
|
2607
|
-
current_cwd = str(context.workspace_dir.resolve())
|
|
2608
2678
|
with self._lock:
|
|
2609
|
-
|
|
2679
|
+
challenges = self._session(context).challenges
|
|
2680
|
+
challenge = challenges.get(challenge_id)
|
|
2610
2681
|
if not challenge:
|
|
2611
2682
|
return None
|
|
2612
|
-
if now - challenge.get("createdAt", 0) > CHALLENGE_TTL_MS
|
|
2613
|
-
|
|
2683
|
+
if now - challenge.get("createdAt", 0) > CHALLENGE_TTL_MS:
|
|
2684
|
+
challenges.pop(challenge_id, None)
|
|
2614
2685
|
return None
|
|
2615
2686
|
if decision not in AUTHORIZE_DECISIONS:
|
|
2616
2687
|
return None
|
|
@@ -2618,13 +2689,13 @@ class AccessController:
|
|
|
2618
2689
|
return None
|
|
2619
2690
|
pattern = self._validate_command_pattern(decision, command_pattern, challenge)
|
|
2620
2691
|
rules = self._validate_directory_rules([directory_rule], context) if directory_rule else []
|
|
2621
|
-
|
|
2692
|
+
challenges.pop(challenge_id)
|
|
2622
2693
|
self._record_decision(challenge, decision, pattern, rules, context)
|
|
2623
2694
|
return challenge
|
|
2624
2695
|
|
|
2625
|
-
def revoke_challenge(self, challenge_id: str) -> bool:
|
|
2696
|
+
def revoke_challenge(self, challenge_id: str, *, context: SecurityContext) -> bool:
|
|
2626
2697
|
with self._lock:
|
|
2627
|
-
return self.
|
|
2698
|
+
return self._session(context).challenges.pop(challenge_id, None) is not None
|
|
2628
2699
|
|
|
2629
2700
|
@staticmethod
|
|
2630
2701
|
def _validate_command_pattern(decision: str, raw_pattern: str | None, challenge: dict) -> str | None:
|
|
@@ -2653,15 +2724,16 @@ class AccessController:
|
|
|
2653
2724
|
tool, server_name, server_id = challenge["toolName"], challenge["serverName"], challenge["serverId"]
|
|
2654
2725
|
if decision == "allow_session":
|
|
2655
2726
|
with self._lock:
|
|
2727
|
+
session = self._session(context)
|
|
2656
2728
|
if pattern:
|
|
2657
|
-
|
|
2658
|
-
clean_pattern_list(
|
|
2729
|
+
session.command_patterns = self._limit_patterns(
|
|
2730
|
+
clean_pattern_list(session.command_patterns + [pattern], "commandPatterns.session"))
|
|
2659
2731
|
else:
|
|
2660
|
-
|
|
2732
|
+
session.tools[tool] = self._make_entry("tools", POLICY_ALLOW, SCOPE_SESSION, server_name, tool)
|
|
2661
2733
|
permanent = decision in ("allow_project", "allow_always", "allow_server_always")
|
|
2662
2734
|
if not permanent and not rules:
|
|
2663
2735
|
return
|
|
2664
|
-
project =
|
|
2736
|
+
project = context.key
|
|
2665
2737
|
|
|
2666
2738
|
def mutator(state: dict) -> dict:
|
|
2667
2739
|
saved = state["commandPatterns"]
|
|
@@ -2680,12 +2752,13 @@ class AccessController:
|
|
|
2680
2752
|
return state
|
|
2681
2753
|
self._update_permanent(mutator)
|
|
2682
2754
|
with self._lock:
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2755
|
+
for session in self.sessions.values():
|
|
2756
|
+
if decision == "allow_always" and not pattern:
|
|
2757
|
+
session.tools.pop(tool, None)
|
|
2758
|
+
elif decision == "allow_server_always":
|
|
2759
|
+
session.servers.pop(server_id, None)
|
|
2760
|
+
if rules and session.directory_rules is not None:
|
|
2761
|
+
session.directory_rules = self._append_rules(session.directory_rules, rules)
|
|
2689
2762
|
|
|
2690
2763
|
def evaluate_authorization(self, tool_name: str, raw_args: dict | None, context: SecurityContext,
|
|
2691
2764
|
server_name: str = "", server_id: str = "") -> AccessDecision:
|
|
@@ -2707,7 +2780,7 @@ class AccessController:
|
|
|
2707
2780
|
server_id=server_id, details=details, rule_offer=offer)
|
|
2708
2781
|
|
|
2709
2782
|
def _evaluate(self, tool_name: str, args: dict, ctx: SecurityContext, server_id: str) -> tuple[str, str, str, dict | None]:
|
|
2710
|
-
view = self._effective_state()
|
|
2783
|
+
view = self._effective_state(ctx)
|
|
2711
2784
|
tool_policy = (view["tools"].get(tool_name) or {}).get("policy")
|
|
2712
2785
|
server_policy = (view["servers"].get(server_id) or {}).get("policy") if server_id else None
|
|
2713
2786
|
if tool_policy == POLICY_DENY:
|
|
@@ -2808,10 +2881,10 @@ IGNORED_WORKSPACE_DIRS = {
|
|
|
2808
2881
|
}
|
|
2809
2882
|
|
|
2810
2883
|
|
|
2811
|
-
def list_directory(path: str = ".", recursive: bool = False) -> str:
|
|
2884
|
+
def list_directory(path: str = ".", recursive: bool = False, *, ctx: SecurityContext) -> str:
|
|
2812
2885
|
"""List files and directories in a local directory with safe bounded recursive traversal."""
|
|
2813
2886
|
try:
|
|
2814
|
-
target =
|
|
2887
|
+
target = ctx.absolute(path)
|
|
2815
2888
|
if not target.exists():
|
|
2816
2889
|
return _tool_error(f"Path '{path}' does not exist.")
|
|
2817
2890
|
if not target.is_dir():
|
|
@@ -2870,10 +2943,10 @@ def list_directory(path: str = ".", recursive: bool = False) -> str:
|
|
|
2870
2943
|
return _tool_error(str(e))
|
|
2871
2944
|
|
|
2872
2945
|
|
|
2873
|
-
def read_file(path: str, start_line: int = 1, end_line: int = None, max_lines: int = 500, max_bytes: int = 100000) -> str:
|
|
2946
|
+
def read_file(path: str, start_line: int = 1, end_line: int = None, max_lines: int = 500, max_bytes: int = 100000, *, ctx: SecurityContext) -> str:
|
|
2874
2947
|
"""Read text content from a local file in streaming mode with safe ranges and bounds."""
|
|
2875
2948
|
try:
|
|
2876
|
-
target =
|
|
2949
|
+
target = ctx.absolute(path)
|
|
2877
2950
|
if not target.exists():
|
|
2878
2951
|
return _tool_error(f"File '{path}' does not exist.")
|
|
2879
2952
|
if not target.is_file():
|
|
@@ -2947,10 +3020,10 @@ def read_file(path: str, start_line: int = 1, end_line: int = None, max_lines: i
|
|
|
2947
3020
|
return _tool_error(str(e))
|
|
2948
3021
|
|
|
2949
3022
|
|
|
2950
|
-
def write_file(path: str, content: str) -> str:
|
|
3023
|
+
def write_file(path: str, content: str, *, ctx: SecurityContext) -> str:
|
|
2951
3024
|
"""Create or overwrite a file completely and atomically."""
|
|
2952
3025
|
try:
|
|
2953
|
-
target =
|
|
3026
|
+
target = ctx.absolute(path)
|
|
2954
3027
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
2955
3028
|
_atomic_write_text(target, content)
|
|
2956
3029
|
bytes_written = len(content.encode("utf-8"))
|
|
@@ -2963,10 +3036,10 @@ def write_file(path: str, content: str) -> str:
|
|
|
2963
3036
|
return _tool_error(str(e))
|
|
2964
3037
|
|
|
2965
3038
|
|
|
2966
|
-
def edit_file(path: str, old_str: str, new_str: str, replace_all: bool = False) -> str:
|
|
3039
|
+
def edit_file(path: str, old_str: str, new_str: str, replace_all: bool = False, *, ctx: SecurityContext) -> str:
|
|
2967
3040
|
"""Replace old_str with new_str in an existing file: its single occurrence, or all of them with replace_all."""
|
|
2968
3041
|
try:
|
|
2969
|
-
target =
|
|
3042
|
+
target = ctx.absolute(path)
|
|
2970
3043
|
if not target.exists():
|
|
2971
3044
|
return _tool_error(f"File '{path}' does not exist. Use read_file to verify existing paths.")
|
|
2972
3045
|
if not target.is_file():
|
|
@@ -2995,28 +3068,26 @@ def edit_file(path: str, old_str: str, new_str: str, replace_all: bool = False)
|
|
|
2995
3068
|
return _tool_error(str(e))
|
|
2996
3069
|
|
|
2997
3070
|
|
|
2998
|
-
def
|
|
2999
|
-
"""
|
|
3071
|
+
def resolve_project_directory(path, ctx: SecurityContext) -> dict:
|
|
3072
|
+
"""
|
|
3073
|
+
Valida la carpeta que elige una pestaña como proyecto (relativa al suyo actual). El servidor no la
|
|
3074
|
+
guarda: la pestaña la envía en cada petición (X-ZeroChat-Project) y otras pestañas siguen en la suya.
|
|
3075
|
+
"""
|
|
3000
3076
|
if not isinstance(path, str) or not path.strip():
|
|
3001
3077
|
raise ValueError("La ruta del directorio está vacía.")
|
|
3002
3078
|
if len(path) > MAX_PATH_LENGTH:
|
|
3003
3079
|
raise ValueError("La ruta del directorio excede el tamaño máximo permitido.")
|
|
3004
|
-
target =
|
|
3080
|
+
target = ctx.absolute(path)
|
|
3005
3081
|
if not target.is_dir():
|
|
3006
3082
|
raise ValueError(f"'{path}' no existe o no es un directorio.")
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
os.chdir(target)
|
|
3010
|
-
# Lo autorizado en la sesión valía para el proyecto anterior.
|
|
3011
|
-
if str(target) != previous:
|
|
3012
|
-
reset_session_authorizations()
|
|
3013
|
-
return {"cwd": str(target), "previous_cwd": previous}
|
|
3083
|
+
# Cambiar de proyecto no borra nada: cada proyecto conserva su propia sesión.
|
|
3084
|
+
return {"cwd": str(target)}
|
|
3014
3085
|
|
|
3015
3086
|
|
|
3016
|
-
def search_files(query: str, path: str = ".", file_pattern: str = None, max_results: int = 100) -> str:
|
|
3087
|
+
def search_files(query: str, path: str = ".", file_pattern: str = None, max_results: int = 100, *, ctx: SecurityContext) -> str:
|
|
3017
3088
|
"""Recursively search for plain text or regular expressions across project files."""
|
|
3018
3089
|
try:
|
|
3019
|
-
target =
|
|
3090
|
+
target = ctx.absolute(path)
|
|
3020
3091
|
if not target.exists():
|
|
3021
3092
|
return _tool_error(f"Path '{path}' does not exist.")
|
|
3022
3093
|
if not target.is_dir():
|
|
@@ -3104,13 +3175,10 @@ def search_files(query: str, path: str = ".", file_pattern: str = None, max_resu
|
|
|
3104
3175
|
return _tool_error(str(e))
|
|
3105
3176
|
|
|
3106
3177
|
|
|
3107
|
-
def get_diagnostics(path: str | None = None) -> str:
|
|
3178
|
+
def get_diagnostics(path: str | None = None, *, ctx: SecurityContext) -> str:
|
|
3108
3179
|
"""Retrieve syntax diagnostics and code errors for a file or the entire workspace."""
|
|
3109
3180
|
try:
|
|
3110
|
-
if path is not None and str(path).strip()
|
|
3111
|
-
target = Path(str(path).strip()).expanduser().resolve()
|
|
3112
|
-
else:
|
|
3113
|
-
target = Path.cwd().resolve()
|
|
3181
|
+
target = ctx.absolute(path) if path is not None and str(path).strip() else ctx.workspace_dir
|
|
3114
3182
|
|
|
3115
3183
|
if not target.exists():
|
|
3116
3184
|
return _tool_error(f"Path '{path}' does not exist.")
|
|
@@ -3122,7 +3190,7 @@ def get_diagnostics(path: str | None = None) -> str:
|
|
|
3122
3190
|
ext = fpath.suffix.lower()
|
|
3123
3191
|
file_diags: list[dict] = []
|
|
3124
3192
|
try:
|
|
3125
|
-
rel_display = str(fpath.relative_to(
|
|
3193
|
+
rel_display = str(fpath.relative_to(ctx.workspace_dir))
|
|
3126
3194
|
except ValueError:
|
|
3127
3195
|
rel_display = str(fpath)
|
|
3128
3196
|
|
|
@@ -3610,6 +3678,7 @@ OWN_BROWSER_ENGINES = ("chromium", "firefox", "webkit")
|
|
|
3610
3678
|
USER_BROWSERS = ("chrome", "msedge", "chromium")
|
|
3611
3679
|
BROWSER_CONFIG_DEFAULTS = {"mode": "own", "engine": "chromium", "userBrowser": "chrome", "headless": True, "extensionToken": ""}
|
|
3612
3680
|
# Identificador de la extensión de Playwright en la tienda de Chrome, que también usa Edge.
|
|
3681
|
+
PLAYWRIGHT_SERVER_ID = "playwright"
|
|
3613
3682
|
PLAYWRIGHT_EXTENSION_ID = "mmlmfjhmonkocbjadbfplnigmagldckm"
|
|
3614
3683
|
# Token que muestra la extensión: con él la conexión no pide aceptarla en el navegador.
|
|
3615
3684
|
_EXTENSION_TOKEN = re.compile(r"^[A-Za-z0-9_-]{0,256}$")
|
|
@@ -3664,7 +3733,7 @@ def save_browser_config(raw) -> dict:
|
|
|
3664
3733
|
|
|
3665
3734
|
|
|
3666
3735
|
def _playwright_active() -> bool:
|
|
3667
|
-
return any(server["id"] ==
|
|
3736
|
+
return any(server["id"] == PLAYWRIGHT_SERVER_ID and server["status"] in ("running", "starting", "installing")
|
|
3668
3737
|
for server in GLOBAL_MCP_MANAGER.list_servers())
|
|
3669
3738
|
|
|
3670
3739
|
|
|
@@ -3785,7 +3854,7 @@ def set_service_user_agent(user_agent: str | None) -> None:
|
|
|
3785
3854
|
|
|
3786
3855
|
# Argumentos, entorno y navegador elegido que añade ZeroChat al arrancar un servicio gestionado,
|
|
3787
3856
|
# calculados en cada arranque.
|
|
3788
|
-
SERVICE_LAUNCH = {
|
|
3857
|
+
SERVICE_LAUNCH = {PLAYWRIGHT_SERVER_ID: lambda browser: _playwright_launch(browser, SERVICE_USER_AGENT)}
|
|
3789
3858
|
|
|
3790
3859
|
|
|
3791
3860
|
# Motores propios de Playwright: cada uno se compone de las entradas de la caché que instala
|
|
@@ -5175,6 +5244,8 @@ def _row_to_conversation_header(row: sqlite3.Row) -> dict:
|
|
|
5175
5244
|
header["profileId"] = extra["profile_id"]
|
|
5176
5245
|
if "server_run" in extra:
|
|
5177
5246
|
header["serverRun"] = bool(extra["server_run"])
|
|
5247
|
+
if extra.get("project"):
|
|
5248
|
+
header["project"] = extra["project"]
|
|
5178
5249
|
return header
|
|
5179
5250
|
|
|
5180
5251
|
|
|
@@ -5238,6 +5309,12 @@ def save_conversation(session_meta: dict, messages: list[dict] | None = None) ->
|
|
|
5238
5309
|
extra["profile_id"] = profile_id.strip()
|
|
5239
5310
|
if session_meta.get("serverRun") is not None:
|
|
5240
5311
|
extra["server_run"] = bool(session_meta.get("serverRun"))
|
|
5312
|
+
project = session_meta.get("project")
|
|
5313
|
+
if project is not None:
|
|
5314
|
+
if not isinstance(project, str) or len(project) > MAX_PATH_LENGTH:
|
|
5315
|
+
raise ValueError("El proyecto de la conversación debe ser una ruta")
|
|
5316
|
+
if project.strip():
|
|
5317
|
+
extra["project"] = project.strip()
|
|
5241
5318
|
|
|
5242
5319
|
with open_storage() as conn:
|
|
5243
5320
|
existing = conn.execute("SELECT created_at, extra_json, title FROM conversations WHERE id = ?;", (session_id,)).fetchone()
|
|
@@ -5249,6 +5326,9 @@ def save_conversation(session_meta: dict, messages: list[dict] | None = None) ->
|
|
|
5249
5326
|
existing_extra = json.loads(existing["extra_json"]) if existing["extra_json"] else {}
|
|
5250
5327
|
merged_extra = dict(existing_extra)
|
|
5251
5328
|
merged_extra.update(extra)
|
|
5329
|
+
# El proyecto se fija al crear la conversación y no cambia después.
|
|
5330
|
+
if existing_extra.get("project"):
|
|
5331
|
+
merged_extra["project"] = existing_extra["project"]
|
|
5252
5332
|
extra = merged_extra
|
|
5253
5333
|
|
|
5254
5334
|
extra_json = json.dumps(extra, ensure_ascii=False) if extra else "{}"
|
|
@@ -5466,6 +5546,34 @@ _SERVER_SHUTTING_DOWN = threading.Event()
|
|
|
5466
5546
|
# Si el servidor se detiene al cerrar el navegador, cerrar la pestaña detiene también los comandos.
|
|
5467
5547
|
EXIT_ON_CLOSE = False
|
|
5468
5548
|
# zerochat/run/progress ya se registra con su propio texto en dispatch_run.
|
|
5549
|
+
# Un navegador lo usa una conversación cada vez; queda libre tras este tiempo sin que lo use. Cubre lo que
|
|
5550
|
+
# el modelo tarda en razonar entre dos acciones, no la espera a otra petición del usuario.
|
|
5551
|
+
BROWSER_LEASE_IDLE_SECONDS = 60.0
|
|
5552
|
+
|
|
5553
|
+
|
|
5554
|
+
class BrowserLease:
|
|
5555
|
+
"""
|
|
5556
|
+
Reserva de los navegadores (browser_action y Playwright MCP): la conversación que los usa los conserva
|
|
5557
|
+
mientras siga usándolos; otra recibe un error claro hasta que pasen BROWSER_LEASE_IDLE_SECONDS sin uso.
|
|
5558
|
+
Sin cola: compartir la página haría que una conversación actuase sobre la de otra.
|
|
5559
|
+
"""
|
|
5560
|
+
|
|
5561
|
+
def __init__(self):
|
|
5562
|
+
self._lock = threading.Lock()
|
|
5563
|
+
self._holders: dict[str, tuple[str, float]] = {}
|
|
5564
|
+
|
|
5565
|
+
def acquire(self, resource: str, conversation_id: str) -> bool:
|
|
5566
|
+
now = time.monotonic()
|
|
5567
|
+
with self._lock:
|
|
5568
|
+
holder = self._holders.get(resource)
|
|
5569
|
+
if holder and holder[0] != conversation_id and now - holder[1] < BROWSER_LEASE_IDLE_SECONDS:
|
|
5570
|
+
return False
|
|
5571
|
+
self._holders[resource] = (conversation_id, now)
|
|
5572
|
+
return True
|
|
5573
|
+
|
|
5574
|
+
|
|
5575
|
+
BROWSER_LEASES = BrowserLease()
|
|
5576
|
+
|
|
5469
5577
|
QUIET_RPC_METHODS = frozenset({"zerochat/heartbeat", "zerochat/jobs/get", "zerochat/jobs/log", "zerochat/jobs/list", "zerochat/run/progress"})
|
|
5470
5578
|
|
|
5471
5579
|
|
|
@@ -5477,10 +5585,10 @@ def mark_browser_active():
|
|
|
5477
5585
|
HEARTBEAT_INITIALIZED = True
|
|
5478
5586
|
|
|
5479
5587
|
|
|
5480
|
-
def live_state(focus_conversation_id: str | None = None) -> dict:
|
|
5588
|
+
def live_state(ctx: SecurityContext, focus_conversation_id: str | None = None) -> dict:
|
|
5481
5589
|
"""
|
|
5482
5590
|
Estado del servidor que la interfaz sigue en vivo, en initialize y en cada zerochat/heartbeat:
|
|
5483
|
-
cwd,
|
|
5591
|
+
cwd, el proyecto de la pestaña que pregunta (su cabecera X-ZeroChat-Project); jobs, los comandos en
|
|
5484
5592
|
marcha, para mostrarlos y avisar antes de cerrar si se detendrían; exit_on_close; playwright, si
|
|
5485
5593
|
se puede navegar aunque se haya instalado o quitado durante la sesión; servers, los servicios
|
|
5486
5594
|
MCP externos aunque otra pestaña los cambie o su proceso muera; runs, lista ligera de ejecuciones
|
|
@@ -5488,8 +5596,8 @@ def live_state(focus_conversation_id: str | None = None) -> dict:
|
|
|
5488
5596
|
"""
|
|
5489
5597
|
runs, focus_run = list_server_runs(focus_conversation_id)
|
|
5490
5598
|
return {
|
|
5491
|
-
"cwd": str(
|
|
5492
|
-
"jobs": [job.summary() for job in JOBS.running()],
|
|
5599
|
+
"cwd": str(ctx.workspace_dir),
|
|
5600
|
+
"jobs": [job.summary() for job in JOBS.running(ctx.key)],
|
|
5493
5601
|
"exit_on_close": EXIT_ON_CLOSE,
|
|
5494
5602
|
"playwright": playwright_status(),
|
|
5495
5603
|
"servers": GLOBAL_MCP_MANAGER.list_servers(),
|
|
@@ -5504,7 +5612,7 @@ def stop_zerochat_server(server: ThreadingHTTPServer):
|
|
|
5504
5612
|
return
|
|
5505
5613
|
_SERVER_SHUTTING_DOWN.set()
|
|
5506
5614
|
HEARTBEAT_WATCHDOG_STOP.set()
|
|
5507
|
-
running = JOBS.running()
|
|
5615
|
+
running = JOBS.running(None)
|
|
5508
5616
|
if running:
|
|
5509
5617
|
console_log(timestamp_message(f"Deteniendo {len(running)} comando(s) en marcha: " + ", ".join(job.command[:60] for job in running)))
|
|
5510
5618
|
JOBS.stop_all("shutdown")
|
|
@@ -5864,7 +5972,7 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
5864
5972
|
return
|
|
5865
5973
|
self.send_header("Access-Control-Allow-Origin", origin if origin else "*")
|
|
5866
5974
|
self.send_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
|
|
5867
|
-
self.send_header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-ZeroChat-Token, X-ZeroChat-Client, X-ZeroChat-Proxy, X-ZeroChat-Tool-Session, X-ZeroChat-Tool-Expires, X-ZeroChat-Tool-Nonce, X-ZeroChat-Tool-Signature, X-ZeroChat-Blob")
|
|
5975
|
+
self.send_header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-ZeroChat-Token, X-ZeroChat-Client, X-ZeroChat-Proxy, X-ZeroChat-Tool-Session, X-ZeroChat-Tool-Expires, X-ZeroChat-Tool-Nonce, X-ZeroChat-Tool-Signature, X-ZeroChat-Blob, X-ZeroChat-Project")
|
|
5868
5976
|
self.send_header("Access-Control-Allow-Private-Network", "true")
|
|
5869
5977
|
|
|
5870
5978
|
def verify_token(self) -> bool:
|
|
@@ -6035,8 +6143,30 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
6035
6143
|
return {"content": [{"type": "text", "text": _tool_error(str(ex))}], "isError": True}
|
|
6036
6144
|
|
|
6037
6145
|
@classmethod
|
|
6038
|
-
def _execute_tool(cls, origin: str, tool_name: str, args: dict
|
|
6039
|
-
|
|
6146
|
+
def _execute_tool(cls, origin: str, tool_name: str, args: dict, ctx: SecurityContext,
|
|
6147
|
+
conversation_id: str = "") -> tuple[dict | None, dict | None, str]:
|
|
6148
|
+
"""
|
|
6149
|
+
Punto único de ejecución de herramientas locales y externas. Un navegador se reserva aquí, al
|
|
6150
|
+
ejecutar, para la conversación que lo usa: pedirlo sin llegar a ejecutar no lo ocupa.
|
|
6151
|
+
"""
|
|
6152
|
+
if origin == "local":
|
|
6153
|
+
browser = tool_name if tool_name == "browser_action" else None
|
|
6154
|
+
else:
|
|
6155
|
+
browser = PLAYWRIGHT_SERVER_ID if GLOBAL_MCP_MANAGER.server_of(tool_name) == PLAYWRIGHT_SERVER_ID else None
|
|
6156
|
+
if browser and not BROWSER_LEASES.acquire(browser, conversation_id):
|
|
6157
|
+
message = (f"The browser is in use by another conversation. It is released after {int(BROWSER_LEASE_IDLE_SECONDS)} "
|
|
6158
|
+
"seconds without use; tell the user or try again later.")
|
|
6159
|
+
return {"content": [{"type": "text", "text": _tool_error(message)}], "isError": True}, None, message
|
|
6160
|
+
try:
|
|
6161
|
+
return cls._run_tool(origin, tool_name, args, ctx)
|
|
6162
|
+
finally:
|
|
6163
|
+
# El plazo cuenta desde que la acción termina: lo que tarde no acorta lo que el modelo puede razonar después.
|
|
6164
|
+
if browser:
|
|
6165
|
+
BROWSER_LEASES.acquire(browser, conversation_id)
|
|
6166
|
+
|
|
6167
|
+
@classmethod
|
|
6168
|
+
def _run_tool(cls, origin: str, tool_name: str, args: dict, ctx: SecurityContext) -> tuple[dict | None, dict | None, str]:
|
|
6169
|
+
"""Ejecuta la herramienta y normaliza su resultado: (result, error JSON-RPC, detalle de error)."""
|
|
6040
6170
|
if origin == "external":
|
|
6041
6171
|
try:
|
|
6042
6172
|
result = GLOBAL_MCP_MANAGER.call(tool_name, args)
|
|
@@ -6055,7 +6185,9 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
6055
6185
|
if not handler:
|
|
6056
6186
|
return None, {"code": -32601, "message": f"Herramienta local '{tool_name}' no encontrada."}, ""
|
|
6057
6187
|
try:
|
|
6058
|
-
|
|
6188
|
+
# Solo las herramientas que actúan en el proyecto declaran ctx.
|
|
6189
|
+
takes_project = "ctx" in inspect.signature(handler).parameters
|
|
6190
|
+
tool_output_json = handler(**dict(args), **({"ctx": ctx} if takes_project else {}))
|
|
6059
6191
|
except Exception as ex:
|
|
6060
6192
|
return cls._tool_exception_result(ex), None, str(ex)
|
|
6061
6193
|
tool_error_info = ""
|
|
@@ -6073,7 +6205,7 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
6073
6205
|
|
|
6074
6206
|
@staticmethod
|
|
6075
6207
|
def _authorize_or_challenge(origin: str, tool_name: str, args: dict, ctx: SecurityContext,
|
|
6076
|
-
job_key: str | None = None) -> tuple[dict | None, dict | None, str] | None:
|
|
6208
|
+
job_key: str | None = None, conversation_id: str = "") -> tuple[dict | None, dict | None, str] | None:
|
|
6077
6209
|
"""Evalúa la política de seguridad y devuelve respuesta de denegación o reto si procede."""
|
|
6078
6210
|
if origin == "external":
|
|
6079
6211
|
server_id = GLOBAL_MCP_MANAGER.server_of(tool_name) or ""
|
|
@@ -6090,7 +6222,7 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
6090
6222
|
if decision.status == POLICY_ASK:
|
|
6091
6223
|
ch = ACCESS_CONTROLLER.create_challenge(
|
|
6092
6224
|
tool_name, args, decision, server_name=server_name, server_id=server_id, origin=origin,
|
|
6093
|
-
context=ctx, job_key=job_key
|
|
6225
|
+
context=ctx, job_key=job_key, conversation_id=conversation_id
|
|
6094
6226
|
)
|
|
6095
6227
|
return {
|
|
6096
6228
|
"requiresAuthorization": True,
|
|
@@ -6107,57 +6239,58 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
6107
6239
|
return None
|
|
6108
6240
|
|
|
6109
6241
|
@classmethod
|
|
6110
|
-
def _call_tool(cls, origin: str, params: dict) -> tuple[dict | None, dict | None, str]:
|
|
6242
|
+
def _call_tool(cls, origin: str, params: dict, ctx: SecurityContext) -> tuple[dict | None, dict | None, str]:
|
|
6111
6243
|
"""tools/call de los dos endpoints: evalúa, emite un reto o ejecuta por el punto único."""
|
|
6112
6244
|
tool_name = params.get("name", "")
|
|
6113
6245
|
if origin == "local" and tool_name not in LOCAL_TOOL_HANDLERS:
|
|
6114
6246
|
return None, {"code": -32601, "message": f"Herramienta local '{tool_name}' no encontrada."}, ""
|
|
6115
6247
|
raw_args = params.get("arguments")
|
|
6116
6248
|
args = dict(raw_args) if isinstance(raw_args, dict) else {}
|
|
6117
|
-
meta = params.get("_meta")
|
|
6118
|
-
#
|
|
6119
|
-
job_key = meta.get("zerochatJobKey") if origin == "local" and tool_name == COMMAND_TOOL
|
|
6120
|
-
|
|
6121
|
-
|
|
6122
|
-
|
|
6123
|
-
|
|
6249
|
+
meta = params.get("_meta") if isinstance(params.get("_meta"), dict) else {}
|
|
6250
|
+
# Ni la clave del trabajo ni la conversación son argumentos del modelo: no se evalúan ni se muestran en el reto.
|
|
6251
|
+
job_key = meta.get("zerochatJobKey") if origin == "local" and tool_name == COMMAND_TOOL else None
|
|
6252
|
+
conversation_id = str(meta.get("zerochatConversationId") or "")
|
|
6253
|
+
gate = cls._authorize_or_challenge(origin, tool_name, args, ctx, job_key, conversation_id)
|
|
6254
|
+
return gate if gate is not None else cls._execute_tool(origin, tool_name, cls._with_job_key(args, job_key), ctx, conversation_id)
|
|
6255
|
+
|
|
6256
|
+
def _dispatch_external(self, method: str, params: dict, ctx: SecurityContext) -> tuple[dict | None, dict | None, str]:
|
|
6124
6257
|
"""Atiende /mcp/external. Devuelve (result, error JSON-RPC, detalle de error de herramienta)."""
|
|
6125
6258
|
if method == "initialize":
|
|
6126
6259
|
return self._initialize_result({"name": "ZeroChat External MCP Host", "version": VERSION}), None, ""
|
|
6127
6260
|
if method == "tools/list":
|
|
6128
6261
|
return {"tools": GLOBAL_MCP_MANAGER.tools()}, None, ""
|
|
6129
6262
|
if method == "tools/call":
|
|
6130
|
-
return self._call_tool("external", params)
|
|
6263
|
+
return self._call_tool("external", params, ctx)
|
|
6131
6264
|
return None, {"code": -32601, "message": f"Método '{method}' no soportado en /mcp/external."}, ""
|
|
6132
6265
|
|
|
6133
|
-
def _dispatch_local(self, method: str, params: dict) -> tuple[dict | None, dict | None, str]:
|
|
6266
|
+
def _dispatch_local(self, method: str, params: dict, ctx: SecurityContext) -> tuple[dict | None, dict | None, str]:
|
|
6134
6267
|
"""Atiende el endpoint local. Devuelve (result, error JSON-RPC, detalle de error de herramienta)."""
|
|
6135
6268
|
if method == "initialize":
|
|
6136
6269
|
server_info = {
|
|
6137
6270
|
"name": "ZeroChat Local Server",
|
|
6138
6271
|
"version": VERSION,
|
|
6139
|
-
"cwd": str(
|
|
6272
|
+
"cwd": str(ctx.workspace_dir),
|
|
6140
6273
|
"os": DETECTED_OS
|
|
6141
6274
|
}
|
|
6142
|
-
return {**self._initialize_result(server_info), "liveState": live_state()}, None, ""
|
|
6275
|
+
return {**self._initialize_result(server_info), "liveState": live_state(ctx)}, None, ""
|
|
6143
6276
|
if method == "zerochat/heartbeat":
|
|
6144
6277
|
focus_id = params.get("focus_conversation_id") if isinstance(params, dict) else None
|
|
6145
|
-
return live_state(focus_id), None, ""
|
|
6278
|
+
return live_state(ctx, focus_id), None, ""
|
|
6146
6279
|
if method == "zerochat/login":
|
|
6147
6280
|
return self._login(params)
|
|
6148
6281
|
if method == "tools/list":
|
|
6149
6282
|
return {"tools": [dict(definition) for definition in LOCAL_TOOLS_DEFINITIONS]}, None, ""
|
|
6150
6283
|
if method == "tools/call":
|
|
6151
|
-
return self._call_tool("local", params)
|
|
6284
|
+
return self._call_tool("local", params, ctx)
|
|
6152
6285
|
if method == "zerochat/project/set_directory":
|
|
6153
6286
|
# Lo invoca la interfaz a petición del usuario: no es una herramienta del modelo.
|
|
6154
6287
|
try:
|
|
6155
|
-
return
|
|
6288
|
+
return resolve_project_directory(params.get("path"), ctx), None, ""
|
|
6156
6289
|
except (ValueError, OSError) as exc:
|
|
6157
6290
|
return None, {"code": -32602, "message": str(exc)}, ""
|
|
6158
6291
|
if method == "zerochat/diff/open":
|
|
6159
6292
|
try:
|
|
6160
|
-
return open_file_diff(params.get("path"), bool(params.get("commit_fallback")), bool(params.get("gui"))), None, ""
|
|
6293
|
+
return open_file_diff(params.get("path"), ctx, bool(params.get("commit_fallback")), bool(params.get("gui"))), None, ""
|
|
6161
6294
|
except (ValueError, RuntimeError) as exc:
|
|
6162
6295
|
return None, {"code": -32602, "message": str(exc)}, ""
|
|
6163
6296
|
except Exception as exc:
|
|
@@ -6177,9 +6310,9 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
6177
6310
|
except Exception as exc:
|
|
6178
6311
|
return None, {"code": -32603, "message": f"Error en transporte web: {exc}"}, str(exc)
|
|
6179
6312
|
if method.startswith("zerochat/jobs/"):
|
|
6180
|
-
return self._dispatch_jobs(method, params)
|
|
6313
|
+
return self._dispatch_jobs(method, params, ctx)
|
|
6181
6314
|
if method.startswith("zerochat/run/"):
|
|
6182
|
-
return dispatch_run(method, params)
|
|
6315
|
+
return dispatch_run(method, params, ctx)
|
|
6183
6316
|
if method in ("zerochat/external/servers/start", "zerochat/external/servers/stop", "zerochat/external/servers/configure"):
|
|
6184
6317
|
return self._dispatch_server_control(method, params)
|
|
6185
6318
|
if method.startswith("zerochat/browser/"):
|
|
@@ -6191,14 +6324,13 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
6191
6324
|
if method.startswith("zerochat/blobs/"):
|
|
6192
6325
|
return self._dispatch_blobs(method, params)
|
|
6193
6326
|
if method.startswith("zerochat/security/"):
|
|
6194
|
-
return self._dispatch_security(method, params)
|
|
6327
|
+
return self._dispatch_security(method, params, ctx)
|
|
6195
6328
|
return None, {"code": -32601, "message": f"Método '{method}' no soportado."}, ""
|
|
6196
6329
|
|
|
6197
6330
|
@classmethod
|
|
6198
|
-
def _dispatch_security(cls, method: str, params: dict) -> tuple[dict | None, dict | None, str]:
|
|
6331
|
+
def _dispatch_security(cls, method: str, params: dict, ctx: SecurityContext) -> tuple[dict | None, dict | None, str]:
|
|
6199
6332
|
"""Gestión de políticas y reglas de seguridad almacenadas en el backend local."""
|
|
6200
6333
|
params = params if isinstance(params, dict) else {}
|
|
6201
|
-
ctx = SecurityContext()
|
|
6202
6334
|
try:
|
|
6203
6335
|
if method == "zerochat/security/get":
|
|
6204
6336
|
return {"policies": ACCESS_CONTROLLER.export_state(ctx)}, None, ""
|
|
@@ -6213,7 +6345,7 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
6213
6345
|
if not isinstance(decision, str):
|
|
6214
6346
|
return None, {"code": -32602, "message": "decision debe ser un texto"}, ""
|
|
6215
6347
|
if decision == "deny":
|
|
6216
|
-
ACCESS_CONTROLLER.revoke_challenge(challenge_id)
|
|
6348
|
+
ACCESS_CONTROLLER.revoke_challenge(challenge_id, context=ctx)
|
|
6217
6349
|
return {"authorized": False, "status": "deny"}, None, ""
|
|
6218
6350
|
|
|
6219
6351
|
ch = ACCESS_CONTROLLER.authorize_challenge(
|
|
@@ -6225,7 +6357,7 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
6225
6357
|
t_origin = ch.get("origin") or "local"
|
|
6226
6358
|
t_name = ch["toolName"]
|
|
6227
6359
|
t_args = ch["arguments"] if isinstance(ch.get("arguments"), dict) else {}
|
|
6228
|
-
exec_res, exec_err, tool_err = cls._execute_tool(t_origin, t_name, cls._with_job_key(t_args, ch.get("jobKey")))
|
|
6360
|
+
exec_res, exec_err, tool_err = cls._execute_tool(t_origin, t_name, cls._with_job_key(t_args, ch.get("jobKey")), ctx, ch.get("conversationId") or "")
|
|
6229
6361
|
if exec_err:
|
|
6230
6362
|
return None, exec_err, tool_err
|
|
6231
6363
|
return {"authorized": True, "result": exec_res}, None, tool_err
|
|
@@ -6380,16 +6512,17 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
6380
6512
|
self._log_res(200, log_detail, (time.monotonic() - t0) * 1000, error_info=error_info)
|
|
6381
6513
|
|
|
6382
6514
|
@staticmethod
|
|
6383
|
-
def _dispatch_jobs(method: str, params: dict) -> tuple[dict | None, dict | None, str]:
|
|
6384
|
-
"""Control de los comandos desde la interfaz: tarjetas, log y botón de detener."""
|
|
6515
|
+
def _dispatch_jobs(method: str, params: dict, ctx: SecurityContext) -> tuple[dict | None, dict | None, str]:
|
|
6516
|
+
"""Control de los comandos del proyecto de la petición desde la interfaz: tarjetas, log y botón de detener."""
|
|
6517
|
+
project = ctx.key
|
|
6385
6518
|
if method == "zerochat/jobs/list":
|
|
6386
|
-
return {"jobs": [job.summary() for job in JOBS.list()]}, None, ""
|
|
6519
|
+
return {"jobs": [job.summary() for job in JOBS.list(project)]}, None, ""
|
|
6387
6520
|
if method == "zerochat/jobs/report":
|
|
6388
6521
|
ids = params.get("ids")
|
|
6389
6522
|
if not isinstance(ids, list) or len(ids) > 100 or any(isinstance(i, bool) or not isinstance(i, int) for i in ids):
|
|
6390
6523
|
return None, {"code": -32602, "message": "ids debe ser una lista de hasta 100 enteros."}, ""
|
|
6391
|
-
return {"reports": JOBS.report_finished(ids)}, None, ""
|
|
6392
|
-
job = JOBS.get(job_id=params.get("id"), key=params.get("key"))
|
|
6524
|
+
return {"reports": JOBS.report_finished(ids, project)}, None, ""
|
|
6525
|
+
job = JOBS.get(project, job_id=params.get("id"), key=params.get("key"))
|
|
6393
6526
|
if method in ("zerochat/jobs/get", "zerochat/jobs/log", "zerochat/jobs/stop") and job is None:
|
|
6394
6527
|
return None, {"code": -32602, "message": "Comando no encontrado: puede pertenecer a una sesión anterior de ZeroChat."}, ""
|
|
6395
6528
|
if method == "zerochat/jobs/get":
|
|
@@ -6509,11 +6642,16 @@ class ZeroChatServerHandler(BaseHTTPRequestHandler):
|
|
|
6509
6642
|
self._log_res(204, log_detail, (time.monotonic() - t0) * 1000)
|
|
6510
6643
|
return
|
|
6511
6644
|
|
|
6645
|
+
try:
|
|
6646
|
+
ctx = request_project_context(self.headers.get("X-ZeroChat-Project"), fallback=method == "initialize")
|
|
6647
|
+
except ProjectGoneError as ex:
|
|
6648
|
+
self._send_rpc_response(req_id, (None, {"code": PROJECT_GONE_CODE, "message": str(ex)}, ""), log_detail, t0, quiet)
|
|
6649
|
+
return
|
|
6512
6650
|
try:
|
|
6513
6651
|
if "/mcp/external" in req_path:
|
|
6514
|
-
outcome = self._dispatch_external(method, params)
|
|
6652
|
+
outcome = self._dispatch_external(method, params, ctx)
|
|
6515
6653
|
else:
|
|
6516
|
-
outcome = self._dispatch_local(method, params)
|
|
6654
|
+
outcome = self._dispatch_local(method, params, ctx)
|
|
6517
6655
|
except Exception as ex:
|
|
6518
6656
|
outcome = None, {"code": -32603, "message": f"Error interno: {ex}"}, ""
|
|
6519
6657
|
self._send_rpc_response(req_id, outcome, log_detail, t0, quiet)
|
|
@@ -6970,8 +7108,8 @@ def list_server_runs(focus_conversation_id: str | None = None) -> tuple[list[dic
|
|
|
6970
7108
|
return runs, focus_run
|
|
6971
7109
|
|
|
6972
7110
|
|
|
6973
|
-
def start_server_run(params: dict) -> dict:
|
|
6974
|
-
"""Inicia una ejecución en segundo plano para una conversación."""
|
|
7111
|
+
def start_server_run(params: dict, ctx: SecurityContext) -> dict:
|
|
7112
|
+
"""Inicia una ejecución en segundo plano para una conversación, en su proyecto o, si no tiene, en el de la petición."""
|
|
6975
7113
|
if not isinstance(params, dict):
|
|
6976
7114
|
raise ValueError("Parámetros no válidos.")
|
|
6977
7115
|
conv_id = params.get("conversation_id")
|
|
@@ -7014,6 +7152,10 @@ def start_server_run(params: dict) -> dict:
|
|
|
7014
7152
|
if not find_node_executable():
|
|
7015
7153
|
raise ValueError("Node.js 18+ es necesario para ejecutar tareas en segundo plano en el servidor (instala Node.js 18+).")
|
|
7016
7154
|
|
|
7155
|
+
project = conv.get("project")
|
|
7156
|
+
if project and not Path(project).is_dir():
|
|
7157
|
+
raise ValueError(f"La carpeta del proyecto de la conversación ya no existe: {project}")
|
|
7158
|
+
|
|
7017
7159
|
run_id = secrets.token_urlsafe(24)
|
|
7018
7160
|
cmd = [sys.executable, str(Path(__file__).resolve()), "--conversation", clean_conv_id, "--profile", profile_name]
|
|
7019
7161
|
if prompt:
|
|
@@ -7033,7 +7175,8 @@ def start_server_run(params: dict) -> dict:
|
|
|
7033
7175
|
stdout=subprocess.DEVNULL,
|
|
7034
7176
|
stderr=subprocess.DEVNULL,
|
|
7035
7177
|
start_new_session=DETECTED_OS != "windows" and hasattr(os, "setsid"),
|
|
7036
|
-
env=env
|
|
7178
|
+
env=env,
|
|
7179
|
+
cwd=project or str(ctx.workspace_dir)
|
|
7037
7180
|
)
|
|
7038
7181
|
|
|
7039
7182
|
payload = {
|
|
@@ -7141,7 +7284,7 @@ def http_body_limit() -> int:
|
|
|
7141
7284
|
return MAX_HTTP_BODY_BYTES
|
|
7142
7285
|
|
|
7143
7286
|
|
|
7144
|
-
def dispatch_run(method: str, params: dict) -> tuple[dict | None, dict | None, str]:
|
|
7287
|
+
def dispatch_run(method: str, params: dict, ctx: SecurityContext) -> tuple[dict | None, dict | None, str]:
|
|
7145
7288
|
"""Métodos zerochat/run/* que usa la interfaz abierta por el modo ejecución."""
|
|
7146
7289
|
params = params if isinstance(params, dict) else {}
|
|
7147
7290
|
session = RUN_SESSION
|
|
@@ -7149,7 +7292,7 @@ def dispatch_run(method: str, params: dict) -> tuple[dict | None, dict | None, s
|
|
|
7149
7292
|
if session is not None:
|
|
7150
7293
|
return None, {"code": -32601, "message": "No disponible dentro de un proceso de ejecución."}, ""
|
|
7151
7294
|
try:
|
|
7152
|
-
return start_server_run(params), None, ""
|
|
7295
|
+
return start_server_run(params, ctx), None, ""
|
|
7153
7296
|
except ValueError as exc:
|
|
7154
7297
|
return None, {"code": -32602, "message": str(exc)}, ""
|
|
7155
7298
|
except OSError as exc:
|
|
@@ -7611,11 +7754,11 @@ def reset_session_authorizations():
|
|
|
7611
7754
|
ACCESS_CONTROLLER.clear_session()
|
|
7612
7755
|
if RUN_SESSION is not None:
|
|
7613
7756
|
if RUN_SESSION.tool_security:
|
|
7614
|
-
ACCESS_CONTROLLER.apply_session_overlay(RUN_SESSION.tool_security,
|
|
7757
|
+
ACCESS_CONTROLLER.apply_session_overlay(RUN_SESSION.tool_security, project_context())
|
|
7615
7758
|
if RUN_SESSION.allow_dangerous_tools:
|
|
7616
7759
|
ACCESS_CONTROLLER.apply_session_overlay({
|
|
7617
7760
|
"tools": {name: {"policy": POLICY_ALLOW} for name in ("write_file", "edit_file", "run_command")}
|
|
7618
|
-
},
|
|
7761
|
+
}, project_context())
|
|
7619
7762
|
|
|
7620
7763
|
|
|
7621
7764
|
def open_server(args, local_ui: bool) -> ThreadingHTTPServer:
|
|
@@ -7665,7 +7808,7 @@ def print_header(dev_root, ui_url: str, exposure_warning: str | None, exit_on_cl
|
|
|
7665
7808
|
"""Cabecera del servidor con su configuración (sin el token)."""
|
|
7666
7809
|
print("=" * 64)
|
|
7667
7810
|
print(f" ZeroChat Local Server v{VERSION} (UI {UI_VERSION})")
|
|
7668
|
-
print(f" Directorio de trabajo : {
|
|
7811
|
+
print(f" Directorio de trabajo : {PROJECT_DIR}")
|
|
7669
7812
|
print(f" Datos y MCP : {get_data_dir()}")
|
|
7670
7813
|
print(f" Entorno MCP : {get_venv_dir()}")
|
|
7671
7814
|
if dev_root is not None:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|