zerochat 10.26.0__tar.gz → 10.28.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.26.0
3
+ Version: 10.28.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "zerochat"
7
- version = "10.26.0"
7
+ version = "10.28.0"
8
8
  description = "Private local web client for AI models, tools and MCP services"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.26.0
3
+ Version: 10.28.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -1575,7 +1575,7 @@ def dispatch_browser(method: str, params: dict) -> RpcOutcome:
1575
1575
 
1576
1576
 
1577
1577
 
1578
- SOURCE_BACKEND_VERSION = "10.26.0"
1578
+ SOURCE_BACKEND_VERSION = "10.28.0"
1579
1579
 
1580
1580
 
1581
1581
  def _read_source_version(filename: str) -> str | None:
@@ -2422,6 +2422,8 @@ WORKSPACE_TRUST_PIPE_FILTERS = frozenset([
2422
2422
  ])
2423
2423
  WORKSPACE_TRUST_GLOBAL_COMMANDS = re.compile(r"(?:^|\s)(?:sudo|su|doas|mkfs|reboot|shutdown|systemctl)\b")
2424
2424
  WORKSPACE_TRUST_OUTSIDE_REFERENCE = re.compile(r"(?:^|[\s=:'\"])(?:[\\/~]|[A-Za-z]:[\\/])|\$|(?:^|[\s=:'\"\\/])\.\.(?=[\s\\/'\"]|$)")
2425
+ _COMMAND_PATH_START = re.compile(r"^(?:[/\\]|(?:\.\.(?:$|[/\\]))|[A-Za-z]:[\\/])")
2426
+ _COMMAND_INTERNAL_OUTSIDE_REF = re.compile(r"[\s:'\"](?:[\\/~]|[A-Za-z]:[\\/]|\.\.(?:$|[\s\\/]))")
2425
2427
 
2426
2428
 
2427
2429
  def parse_directory_rule(raw_rule: str) -> dict | None:
@@ -2543,6 +2545,34 @@ def is_workspace_local_command(segment: str) -> bool:
2543
2545
  return not WORKSPACE_TRUST_GLOBAL_COMMANDS.search(segment) and not WORKSPACE_TRUST_OUTSIDE_REFERENCE.search(segment)
2544
2546
 
2545
2547
 
2548
+ def command_outside_references(segment: str) -> list[str] | None:
2549
+ """
2550
+ Rutas externas o con '..' que aparecen como argumentos del subcomando para validarlas frente a
2551
+ directoryRules; [] si es local al proyecto, o None si lleva órdenes globales, $, ~ o texto con
2552
+ rutas incrustadas no validables como argumento de ruta.
2553
+ """
2554
+ if is_workspace_local_command(segment):
2555
+ return []
2556
+ if WORKSPACE_TRUST_GLOBAL_COMMANDS.search(segment) or "$" in segment or "~" in segment:
2557
+ return None
2558
+ try:
2559
+ tokens = shlex.split(segment)
2560
+ except ValueError:
2561
+ return None
2562
+ if not tokens:
2563
+ return None
2564
+ refs = []
2565
+ for token in tokens:
2566
+ if not WORKSPACE_TRUST_OUTSIDE_REFERENCE.search(token):
2567
+ continue
2568
+ candidate = token.split("=", 1)[1] if ("=" in token and not _COMMAND_PATH_START.match(token)) else token
2569
+ tail = candidate[2:] if re.match(r"^[A-Za-z]:[\\/]", candidate) else candidate[1:]
2570
+ if not _COMMAND_PATH_START.match(candidate) or _COMMAND_INTERNAL_OUTSIDE_REF.search(tail):
2571
+ return None
2572
+ refs.append(candidate)
2573
+ return refs
2574
+
2575
+
2546
2576
  @functools.lru_cache(maxsize=512)
2547
2577
  def compile_command_pattern(pattern: str) -> tuple[tuple[tuple[re.Pattern, bool], ...], bool]:
2548
2578
  """
@@ -3379,11 +3409,18 @@ def delete_conversation(session_id: str) -> bool:
3379
3409
 
3380
3410
 
3381
3411
  def delete_project_conversations(project: str) -> list[str]:
3382
- """Elimina las conversaciones de un proyecto con sus mensajes y blobs propios, y devuelve sus identificadores."""
3383
- if not isinstance(project, str) or not project.strip() or len(project) > MAX_PATH_LENGTH:
3412
+ """Elimina las conversaciones de un proyecto (o de la carpeta general si es vacío) con sus mensajes y blobs propios."""
3413
+ if not isinstance(project, str) or (project and not project.strip()) or len(project) > MAX_PATH_LENGTH:
3384
3414
  raise ValueError("El proyecto de las conversaciones debe ser una ruta")
3415
+ clean_project = project.strip()
3385
3416
  with open_storage() as conn:
3386
- return _delete_conversations(conn, "json_extract(extra_json, '$.project') = ?", (project.strip(),))
3417
+ if not clean_project:
3418
+ return _delete_conversations(
3419
+ conn,
3420
+ "json_extract(extra_json, '$.project') IS NULL OR json_extract(extra_json, '$.project') = ''",
3421
+ (),
3422
+ )
3423
+ return _delete_conversations(conn, "json_extract(extra_json, '$.project') = ?", (clean_project,))
3387
3424
 
3388
3425
 
3389
3426
  def delete_all_conversations() -> int:
@@ -4447,7 +4484,7 @@ def _approved_call(tool_security) -> tuple[str, dict] | None:
4447
4484
  class RunSession:
4448
4485
  """Estado de la ejecución: prompt, opciones, último progreso, exportación, resultado y motivo de un final sin él."""
4449
4486
  def __init__(self, prompt: str | None = None, profile: str | None = None, export_path: Path | None = None, keep_page: bool = False,
4450
- allow_dangerous_tools: bool = False, conversation_id: str | None = None, run_id: str | None = None,
4487
+ conversation_id: str | None = None, run_id: str | None = None,
4451
4488
  tool_security: dict | None = None, profile_data: dict | None = None):
4452
4489
  env_run_id = os.environ.get("ZEROCHAT_RUN_ID", "").strip()
4453
4490
  self.run_id = run_id.strip() if (run_id and isinstance(run_id, str) and run_id.strip()) else (env_run_id or secrets.token_urlsafe(24))
@@ -4465,8 +4502,6 @@ class RunSession:
4465
4502
  self.export_error: str | None = None
4466
4503
  # La interfaz no cierra la página al terminar, para ver la conversación (sin --headless).
4467
4504
  self.keep_page = keep_page
4468
- # La interfaz aprueba también write_file, edit_file y run_command, que si no deniega.
4469
- self.allow_dangerous_tools = allow_dangerous_tools
4470
4505
  if tool_security is not None:
4471
4506
  self.tool_security = tool_security
4472
4507
  elif os.environ.get("ZEROCHAT_RUN_SECURITY"):
@@ -4563,8 +4598,7 @@ def _rpc_prompt(params: dict, session: RunSession) -> RpcOutcome:
4563
4598
  # Para switch_model, que busca por nombre: el runner no puede listar los perfiles con su credencial.
4564
4599
  # El listado no lleva API keys; la del que active la pide con zerochat/run/profile.
4565
4600
  "profiles": list_general_profiles(),
4566
- "export": export_format, "keep_page": session.keep_page,
4567
- "allow_dangerous_tools": session.allow_dangerous_tools})
4601
+ "export": export_format, "keep_page": session.keep_page})
4568
4602
 
4569
4603
 
4570
4604
  def _rpc_profile(params: dict, session: RunSession) -> RpcOutcome:
@@ -6574,7 +6608,7 @@ def job_details(job: CommandJob) -> dict:
6574
6608
 
6575
6609
 
6576
6610
 
6577
- POLICY_STATE_VERSION = 6
6611
+ POLICY_STATE_VERSION = 7
6578
6612
  CHALLENGE_TTL_MS = 600_000
6579
6613
  MAX_POLICY_ENTRIES = 500
6580
6614
  # Proyectos con sesión en memoria: al pasar del tope se olvida la del usado hace más tiempo sin comandos en marcha.
@@ -6627,13 +6661,19 @@ class AccessController:
6627
6661
  """Única definición del estado permanente y de sus valores por defecto."""
6628
6662
  data = raw if isinstance(raw, dict) else {}
6629
6663
  patterns = data.get("commandPatterns") if isinstance(data.get("commandPatterns"), dict) else {}
6664
+ raw_dir_rules = data.get("directoryRules")
6665
+ dir_rules = {
6666
+ str(project): list(rules)
6667
+ for project, rules in raw_dir_rules.items()
6668
+ if isinstance(project, str) and isinstance(rules, list) and rules
6669
+ } if isinstance(raw_dir_rules, dict) else {}
6630
6670
  # run_command nunca se guarda autorizado entero: sus permisos permanentes son patrones.
6631
6671
  tools = {tid: entry for tid, entry in dict(data.get("tools") or {}).items()
6632
6672
  if not (tid == COMMAND_TOOL and isinstance(entry, dict) and entry.get("policy") == POLICY_ALLOW)}
6633
6673
  return {
6634
6674
  "version": POLICY_STATE_VERSION,
6635
6675
  "globalMcpPolicy": data.get("globalMcpPolicy") or GLOBAL_POLICY_ASK,
6636
- "directoryRules": list(data.get("directoryRules") or []),
6676
+ "directoryRules": dir_rules,
6637
6677
  "tools": tools,
6638
6678
  "servers": dict(data.get("servers") or {}),
6639
6679
  "commandPatterns": {"global": list(patterns.get("global") or []), "projects": dict(patterns.get("projects") or {})}
@@ -6654,7 +6694,11 @@ class AccessController:
6654
6694
  session = self._session(context)
6655
6695
  return {
6656
6696
  "globalMcpPolicy": session.global_policy if session.global_policy is not None else state["globalMcpPolicy"],
6657
- "directoryRules": list(session.directory_rules) if session.directory_rules is not None else state["directoryRules"],
6697
+ "directoryRules": (
6698
+ list(session.directory_rules)
6699
+ if session.directory_rules is not None
6700
+ else list(state["directoryRules"].get(context.key) or [])
6701
+ ),
6658
6702
  "tools": {**state["tools"], **session.tools},
6659
6703
  "servers": {**state["servers"], **session.servers},
6660
6704
  "commandPatterns": {**state["commandPatterns"], "session": list(session.command_patterns)}
@@ -6730,7 +6774,9 @@ class AccessController:
6730
6774
  @staticmethod
6731
6775
  def _check_entry_limit(state: dict):
6732
6776
  """Único tope de entradas, sobre el estado resultante (guardado o capa de sesión)."""
6733
- total = len(state.get("directoryRules") or []) + len(state.get("tools") or {}) + len(state.get("servers") or {})
6777
+ dir_rules = state.get("directoryRules")
6778
+ dir_count = sum(len(v) for v in dir_rules.values()) if isinstance(dir_rules, dict) else len(dir_rules or [])
6779
+ total = dir_count + len(state.get("tools") or {}) + len(state.get("servers") or {})
6734
6780
  if total > MAX_POLICY_ENTRIES:
6735
6781
  raise ValueError(f"El número total de entradas ({total}) supera el máximo permitido ({MAX_POLICY_ENTRIES}).")
6736
6782
 
@@ -6760,22 +6806,29 @@ class AccessController:
6760
6806
  added_rules = self._validate_directory_rules(state["addDirectoryRules"], context) if "addDirectoryRules" in state else []
6761
6807
  clean_patterns = normalize_command_patterns(state["commandPatterns"]) if "commandPatterns" in state else None
6762
6808
 
6809
+ project = context.key
6810
+
6763
6811
  def mutator(current: dict) -> dict:
6764
- self._apply_state_patch(current, clean_global, clean_rules, added_rules, clean_tools, clean_servers, clean_patterns)
6812
+ self._apply_state_patch(current, project, clean_global, clean_rules, added_rules, clean_tools, clean_servers, clean_patterns)
6765
6813
  self._check_entry_limit(current)
6766
6814
  return current
6767
6815
  self._update_permanent(mutator)
6768
- self._forget_session_overrides(clean_global, clean_rules, added_rules, clean_tools, clean_servers)
6816
+ self._forget_session_overrides(project, clean_global, clean_rules, added_rules, clean_tools, clean_servers)
6769
6817
  return self.export_state(context)
6770
6818
 
6771
- def _apply_state_patch(self, current: dict, clean_global, clean_rules, added_rules, clean_tools, clean_servers, clean_patterns):
6819
+ def _apply_state_patch(self, current: dict, project: str, clean_global, clean_rules, added_rules, clean_tools, clean_servers, clean_patterns):
6772
6820
  """Aplica sobre el estado guardado los apartados del parche que vienen (None es «no cambiar»)."""
6773
6821
  if clean_global is not None:
6774
6822
  current["globalMcpPolicy"] = clean_global
6775
6823
  if clean_rules is not None:
6776
- current["directoryRules"] = clean_rules
6824
+ if clean_rules:
6825
+ current["directoryRules"][project] = clean_rules
6826
+ else:
6827
+ current["directoryRules"].pop(project, None)
6777
6828
  if added_rules:
6778
- current["directoryRules"] = self._append_rules(current["directoryRules"], added_rules)
6829
+ merged = self._append_rules(current["directoryRules"].get(project) or [], added_rules)
6830
+ if merged:
6831
+ current["directoryRules"][project] = merged
6779
6832
  if clean_tools is not None:
6780
6833
  current["tools"] = self._apply_entry_patch(current.get("tools"), clean_tools)
6781
6834
  if clean_servers is not None:
@@ -6783,16 +6836,17 @@ class AccessController:
6783
6836
  if clean_patterns is not None:
6784
6837
  current["commandPatterns"] = clean_patterns
6785
6838
 
6786
- def _forget_session_overrides(self, clean_global, clean_rules, added_rules, clean_tools, clean_servers):
6787
- """Lo guardado vale para todos los proyectos: sustituye o revoca lo equivalente en la sesión de cada uno."""
6839
+ def _forget_session_overrides(self, project: str, clean_global, clean_rules, added_rules, clean_tools, clean_servers):
6840
+ """Lo guardado sustituye o revoca lo equivalente en la sesión (las reglas de carpeta, solo en su proyecto)."""
6788
6841
  with self._lock:
6789
- for session in self.sessions.values():
6842
+ for key, session in self.sessions.items():
6790
6843
  if clean_global is not None:
6791
6844
  session.global_policy = None
6792
- if clean_rules is not None:
6793
- session.directory_rules = None
6794
- elif added_rules and session.directory_rules is not None:
6795
- session.directory_rules = self._append_rules(session.directory_rules, added_rules)
6845
+ if key == project:
6846
+ if clean_rules is not None:
6847
+ session.directory_rules = None
6848
+ elif added_rules and session.directory_rules is not None:
6849
+ session.directory_rules = self._append_rules(session.directory_rules, added_rules)
6796
6850
  for kind, patch in (("tools", clean_tools), ("servers", clean_servers)):
6797
6851
  for item_id in patch or {}:
6798
6852
  session.entries(kind).pop(item_id, None)
@@ -7020,11 +7074,13 @@ class AccessController:
7020
7074
  def mutator(state: dict) -> dict:
7021
7075
  self._store_decision(state, decision, pattern, project, tool, server_name, server_id)
7022
7076
  if rules:
7023
- state["directoryRules"] = self._append_rules(state["directoryRules"], rules)
7077
+ merged = self._append_rules(state["directoryRules"].get(project) or [], rules)
7078
+ if merged:
7079
+ state["directoryRules"][project] = merged
7024
7080
  self._check_entry_limit(state)
7025
7081
  return state
7026
7082
  self._update_permanent(mutator)
7027
- self._drop_superseded_session_entries(decision, pattern, tool, server_id, rules)
7083
+ self._drop_superseded_session_entries(decision, pattern, tool, server_id, project, rules)
7028
7084
 
7029
7085
  def _allow_for_session(self, context: SecurityContext, tool: str, server_name: str, pattern: str | None):
7030
7086
  """«Permitir en la sesión»: el patrón de comando aprobado o, sin él, la herramienta."""
@@ -7050,15 +7106,16 @@ class AccessController:
7050
7106
  elif decision == "allow_server_always":
7051
7107
  state["servers"][server_id] = self._make_entry("servers", POLICY_ALLOW, SCOPE_PERMANENT, server_name or server_id)
7052
7108
 
7053
- def _drop_superseded_session_entries(self, decision: str, pattern: str | None, tool: str, server_id: str, rules: list[str]):
7054
- """Lo que se acaba de guardar sustituye a lo equivalente en la sesión de cada proyecto."""
7109
+ def _drop_superseded_session_entries(self, decision: str, pattern: str | None, tool: str, server_id: str,
7110
+ project: str, rules: list[str]):
7111
+ """Lo que se acaba de guardar sustituye a lo equivalente en la sesión (las reglas de carpeta, solo en su proyecto)."""
7055
7112
  with self._lock:
7056
- for session in self.sessions.values():
7113
+ for key, session in self.sessions.items():
7057
7114
  if decision == "allow_always" and not pattern:
7058
7115
  session.tools.pop(tool, None)
7059
7116
  elif decision == "allow_server_always":
7060
7117
  session.servers.pop(server_id, None)
7061
- if rules and session.directory_rules is not None:
7118
+ if key == project and rules and session.directory_rules is not None:
7062
7119
  session.directory_rules = self._append_rules(session.directory_rules, rules)
7063
7120
 
7064
7121
  def evaluate_authorization(self, tool_name: str, raw_args: dict | None, context: SecurityContext,
@@ -7104,31 +7161,57 @@ class AccessController:
7104
7161
  return self._evaluate_path(tool_name, access, path, view, ctx)
7105
7162
  return POLICY_ASK, "mcp_default_ask", "", None
7106
7163
 
7164
+ @staticmethod
7165
+ def _has_full_directory_access(rules: list[str]) -> bool:
7166
+ """Indica si el proyecto tiene acceso RW a todo el sistema de ficheros (RW:/** o RW:/)."""
7167
+ return any(
7168
+ (parsed := parse_directory_rule(raw)) is not None
7169
+ and parsed["access"] == "RW"
7170
+ and parsed["path"] in ("/**", "/")
7171
+ for raw in rules
7172
+ )
7173
+
7174
+ @staticmethod
7175
+ def _command_target(cwd: Path, raw_path: str) -> str:
7176
+ return raw_path if re.match(r"^(/|[A-Za-z]:[\\/])", raw_path) else str(cwd / raw_path)
7177
+
7178
+ def _is_allowed_trust_segment(self, segment: str, cwd: Path, directory_rules: list[str], ctx: SecurityContext) -> bool:
7179
+ """Subcomando permitido por Workspace Trust: local o con argumentos de ruta dentro de reglas RW del proyecto."""
7180
+ refs = command_outside_references(segment)
7181
+ if refs is None:
7182
+ return False
7183
+ return all(
7184
+ self.evaluate_directory_rule("RW", self._command_target(cwd, ref), directory_rules, ctx)["allowed"]
7185
+ for ref in refs
7186
+ )
7187
+
7107
7188
  def _evaluate_command(self, raw_command: str, view: dict, ctx: SecurityContext) -> tuple[str, str, str, dict | None]:
7108
7189
  """
7109
7190
  Valida cada subcomando por separado: un cd tiene que llevar a una carpeta cubierta por las reglas
7110
7191
  de directorio, y los subcomandos siguientes se ejecutan en ella; el resto tiene que estar cubierto
7111
- por un patrón o, con Workspace Trust, quedarse en el proyecto (tras una tubería, solo un filtro).
7112
- Un patrón es una vía más de permitir, nunca una puerta que anule Workspace Trust.
7192
+ por un patrón o, con Workspace Trust, quedarse en el proyecto o en reglas RW del proyecto (tras una
7193
+ tubería, solo un filtro). Con RW:/** en Workspace Trust, el proyecto queda sin restricción de comandos.
7113
7194
  """
7195
+ trust = view["globalMcpPolicy"] == GLOBAL_POLICY_WORKSPACE_TRUST
7196
+ if trust and self._has_full_directory_access(view["directoryRules"]):
7197
+ return POLICY_ALLOW, "directory_rule_allow", "", None
7114
7198
  segments = split_command(raw_command)
7115
7199
  if segments is None:
7116
7200
  return (POLICY_ASK, "command_chaining_requires_approval",
7117
7201
  f"El comando usa sintaxis de shell que no se puede validar por partes: {raw_command}", None)
7118
7202
  patterns = self._command_patterns(view, ctx)
7119
- trust = view["globalMcpPolicy"] == GLOBAL_POLICY_WORKSPACE_TRUST
7120
7203
  cwd, by_trust, uncovered = ctx.workspace_dir, False, []
7121
7204
  for operator, segment in segments:
7122
7205
  directory = cd_target(segment)
7123
7206
  if directory is not None:
7124
- target = directory if re.match(r"^(/|[A-Za-z]:[\\/])", directory) else str(cwd / directory)
7207
+ target = self._command_target(cwd, directory)
7125
7208
  if not any(self.evaluate_directory_rule(a, target, view["directoryRules"], ctx)["allowed"] for a in ("R", "W")):
7126
7209
  return (POLICY_ASK, "command_directory_outside_rules",
7127
7210
  f"El comando se ejecuta fuera de las reglas de directorio: {directory}", None)
7128
- cwd = ctx.resolve_path(target)
7211
+ cwd = ctx.resolve_path(target) or cwd
7129
7212
  elif any(matches_command_pattern(segment, p) for p in patterns):
7130
7213
  continue
7131
- elif trust and is_workspace_local_command(segment) and (
7214
+ elif trust and self._is_allowed_trust_segment(segment, cwd, view["directoryRules"], ctx) and (
7132
7215
  operator != "|" or segment.split()[0] in WORKSPACE_TRUST_PIPE_FILTERS):
7133
7216
  by_trust = True
7134
7217
  else:
@@ -8571,6 +8654,16 @@ def with_job_key(args: dict, job_key: str | None) -> dict:
8571
8654
  return {**args, "job_key": job_key} if job_key else args
8572
8655
 
8573
8656
 
8657
+ def _security_deny_result(reason: str, detail: str = "") -> tuple[dict, None, str]:
8658
+ err_msg = f"Bloqueado por política de seguridad: {detail or reason}"
8659
+ return {
8660
+ "content": [{"type": "text", "text": f"Error: {err_msg}"}],
8661
+ "isError": True,
8662
+ "securityStatus": "deny",
8663
+ "reason": reason
8664
+ }, None, err_msg
8665
+
8666
+
8574
8667
  def authorize_or_challenge(origin: str, tool_name: str, args: dict, ctx: SecurityContext,
8575
8668
  job_key: str | None = None, conversation_id: str = "") -> tuple[dict | None, dict | None, str] | None:
8576
8669
  """Evalúa la política de seguridad y devuelve respuesta de denegación o reto si procede."""
@@ -8584,13 +8677,16 @@ def authorize_or_challenge(origin: str, tool_name: str, args: dict, ctx: Securit
8584
8677
  tool_name, args, context=ctx, server_name=server_name, server_id=server_id
8585
8678
  )
8586
8679
  if decision.status == POLICY_DENY:
8587
- err_msg = f"Bloqueado por política de seguridad: {decision.reason}"
8588
- return {"content": [{"type": "text", "text": f"Error: {err_msg}"}], "isError": True, "securityStatus": "deny", "reason": decision.reason}, None, err_msg
8680
+ return _security_deny_result(decision.reason)
8589
8681
  if decision.status == POLICY_ASK:
8590
8682
  session = current_run_session()
8591
- if session is not None and session.take_approved_call(tool_name, args):
8592
- log_event(f"[run] {tool_name}: se ejecuta la llamada que la persona aprobó al reanudar")
8593
- return None
8683
+ if session is not None:
8684
+ if session.take_approved_call(tool_name, args):
8685
+ log_event(f"[run] {tool_name}: se ejecuta la llamada que la persona aprobó al reanudar")
8686
+ return None
8687
+ if origin == "external":
8688
+ return None
8689
+ return _security_deny_result(decision.reason, decision.details)
8594
8690
  ch =ACCESS_CONTROLLER.create_challenge(
8595
8691
  tool_name, args, decision, server_name=server_name, server_id=server_id, origin=origin,
8596
8692
  context=ctx, job_key=job_key, conversation_id=conversation_id
@@ -9618,7 +9714,6 @@ def build_parser() -> ZeroChatArgumentParser:
9618
9714
  parser.add_argument("--export", default=None, metavar="FICHERO", help=f"Con --prompt o --conversation, guardar la conversación en FICHERO; el formato sale de la extensión ({', '.join(RUN_EXPORT_FORMATS)})")
9619
9715
  parser.add_argument("--browser", action="store_true", help="Con --prompt o --conversation, abrir el navegador predeterminado del usuario en lugar del proceso Node.js sin ventana")
9620
9716
  parser.add_argument("--keep-page", action="store_true", help="Página: con --browser, no cerrar la página al terminar para ver la conversación (no se combina con --headless)")
9621
- parser.add_argument("--allow-dangerous-tools", action="store_true", help="Con --prompt sin --conversation, aprobar también las herramientas que escriben o ejecutan (write_file, edit_file, run_command); las demás se aprueban siempre para la sesión. Con --conversation nada se aprueba solo: la ejecución se pausa y pregunta")
9622
9717
  parser.add_argument("--headless", action="store_true", help="Con --browser, abrir el navegador predeterminado sin ventana (si ya está abierto puede verse la pestaña)")
9623
9718
  parser.add_argument("--version", action="version", version=f"ZeroChat {VERSION}")
9624
9719
  return parser
@@ -9626,8 +9721,6 @@ def build_parser() -> ZeroChatArgumentParser:
9626
9721
 
9627
9722
  def _check_run_flags(parser: ZeroChatArgumentParser, args):
9628
9723
  """Combinaciones de opciones que no admiten --prompt ni --conversation."""
9629
- if args.allow_dangerous_tools and args.conversation is not None:
9630
- parser.error("--conversation no aprueba nada sin preguntar: si una herramienta pide permiso, la ejecución se pausa (needs_input); --allow-dangerous-tools solo se usa con --prompt sin --conversation")
9631
9724
  if args.no_browser:
9632
9725
  parser.error("--prompt y --conversation ejecutan la interfaz de forma autónoma: no se combina con --no-browser")
9633
9726
  if args.keep_server:
@@ -9704,8 +9797,8 @@ def _run_export_path(parser: ZeroChatArgumentParser, args) -> Path | None:
9704
9797
  def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession | None:
9705
9798
  """Valida las combinaciones de opciones y devuelve la sesión de --prompt o --conversation, si la hay."""
9706
9799
  if args.prompt is None and args.conversation is None:
9707
- if args.browser or args.headless or args.keep_page or args.allow_dangerous_tools or args.profile is not None or args.export is not None:
9708
- parser.error("--browser, --headless, --keep-page, --allow-dangerous-tools, --profile y --export solo se usan con --prompt o --conversation")
9800
+ if args.browser or args.headless or args.keep_page or args.profile is not None or args.export is not None:
9801
+ parser.error("--browser, --headless, --keep-page, --profile y --export solo se usan con --prompt o --conversation")
9709
9802
  return None
9710
9803
  prompt = _run_prompt(parser, args)
9711
9804
  conversation_id, conv = _run_conversation(parser, args, prompt)
@@ -9714,7 +9807,7 @@ def run_session_from_args(parser: ZeroChatArgumentParser, args) -> RunSession |
9714
9807
  export_path = _run_export_path(parser, args)
9715
9808
  if conversation_id:
9716
9809
  mark_conversation_server_run(conversation_id, profile_name)
9717
- return RunSession(prompt, profile_name, export_path, args.keep_page, args.allow_dangerous_tools, conversation_id=conversation_id, profile_data=profile_data)
9810
+ return RunSession(prompt, profile_name, export_path, args.keep_page, conversation_id=conversation_id, profile_data=profile_data)
9718
9811
 
9719
9812
 
9720
9813
  def redirect_log(args):
@@ -9784,21 +9877,17 @@ def reset_session_authorizations():
9784
9877
  tool_name = tool_decision.get("toolName") or ""
9785
9878
  server_id = GLOBAL_MCP_MANAGER.server_of(tool_name) or ""
9786
9879
  ACCESS_CONTROLLER.apply_tool_decision(tool_decision, ctx, server_id=server_id)
9787
- if session.allow_dangerous_tools:
9788
- ACCESS_CONTROLLER.apply_session_overlay({
9789
- "globalMcpPolicy": GLOBAL_POLICY_ALLOW_ALL,
9790
- "tools": {name: {"policy": POLICY_ALLOW} for name in ("write_file", "edit_file", "run_command")}
9791
- }, ctx)
9792
- elif session.conversation_id is None:
9793
- permanent_tools = ACCESS_CONTROLLER.export_state(ctx).get("tools") or {}
9794
- ACCESS_CONTROLLER.apply_session_overlay({
9795
- "tools": {
9796
- name: {"policy": POLICY_ALLOW}
9797
- for name in LOCAL_TOOL_HANDLERS
9798
- if name not in ("write_file", "edit_file", "run_command")
9799
- and (permanent_tools.get(name) or {}).get("policy") != POLICY_DENY
9800
- }
9801
- }, ctx)
9880
+ permanent_tools = ACCESS_CONTROLLER.export_state(ctx).get("tools") or {}
9881
+ ACCESS_CONTROLLER.apply_session_overlay({
9882
+ "globalMcpPolicy": GLOBAL_POLICY_WORKSPACE_TRUST,
9883
+ "tools": {
9884
+ name: {"policy": POLICY_ALLOW}
9885
+ for name in LOCAL_TOOL_HANDLERS
9886
+ if name != COMMAND_TOOL
9887
+ and not get_integrated_path_access(name)
9888
+ and (permanent_tools.get(name) or {}).get("policy") != POLICY_DENY
9889
+ }
9890
+ }, ctx)
9802
9891
 
9803
9892
 
9804
9893
  def open_server(args, local_ui: bool) -> ThreadingHTTPServer:
File without changes
File without changes
File without changes