zerochat 10.30.0__tar.gz → 10.32.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.30.0/zerochat.egg-info → zerochat-10.32.0}/PKG-INFO +1 -1
- {zerochat-10.30.0 → zerochat-10.32.0}/pyproject.toml +1 -1
- {zerochat-10.30.0 → zerochat-10.32.0/zerochat.egg-info}/PKG-INFO +1 -1
- {zerochat-10.30.0 → zerochat-10.32.0}/zerochat.py +248 -34
- {zerochat-10.30.0 → zerochat-10.32.0}/LICENSE +0 -0
- {zerochat-10.30.0 → zerochat-10.32.0}/README.md +0 -0
- {zerochat-10.30.0 → zerochat-10.32.0}/setup.cfg +0 -0
- {zerochat-10.30.0 → zerochat-10.32.0}/zerochat.egg-info/SOURCES.txt +0 -0
- {zerochat-10.30.0 → zerochat-10.32.0}/zerochat.egg-info/dependency_links.txt +0 -0
- {zerochat-10.30.0 → zerochat-10.32.0}/zerochat.egg-info/entry_points.txt +0 -0
- {zerochat-10.30.0 → zerochat-10.32.0}/zerochat.egg-info/top_level.txt +0 -0
|
@@ -337,6 +337,8 @@ class TokenGrant:
|
|
|
337
337
|
if method == "zerochat/conversations/save":
|
|
338
338
|
conv = params.get("conversation")
|
|
339
339
|
return isinstance(conv, dict) and conv.get("id") == self.conversation_id
|
|
340
|
+
if method == "zerochat/conversations/save_chunk":
|
|
341
|
+
return params.get("conversationId") == self.conversation_id
|
|
340
342
|
return False
|
|
341
343
|
|
|
342
344
|
|
|
@@ -1575,7 +1577,7 @@ def dispatch_browser(method: str, params: dict) -> RpcOutcome:
|
|
|
1575
1577
|
|
|
1576
1578
|
|
|
1577
1579
|
|
|
1578
|
-
SOURCE_BACKEND_VERSION = "10.
|
|
1580
|
+
SOURCE_BACKEND_VERSION = "10.32.0"
|
|
1579
1581
|
|
|
1580
1582
|
|
|
1581
1583
|
def _read_source_version(filename: str) -> str | None:
|
|
@@ -2390,8 +2392,7 @@ def normalize_directory_path(value: str) -> str:
|
|
|
2390
2392
|
|
|
2391
2393
|
GLOBAL_POLICY_ASK = "ask"
|
|
2392
2394
|
GLOBAL_POLICY_ALLOW_ALL = "allow_all"
|
|
2393
|
-
|
|
2394
|
-
GLOBAL_POLICIES = (GLOBAL_POLICY_ASK, GLOBAL_POLICY_ALLOW_ALL, GLOBAL_POLICY_WORKSPACE_TRUST)
|
|
2395
|
+
GLOBAL_POLICIES = (GLOBAL_POLICY_ASK, GLOBAL_POLICY_ALLOW_ALL)
|
|
2395
2396
|
POLICY_ALLOW = "allow"
|
|
2396
2397
|
POLICY_DENY = "deny"
|
|
2397
2398
|
POLICY_ASK = "ask"
|
|
@@ -2658,7 +2659,7 @@ def normalize_command_patterns(raw) -> dict:
|
|
|
2658
2659
|
MAX_COMMAND_PATTERNS en total. Los de sesión nunca forman parte del estado guardado.
|
|
2659
2660
|
"""
|
|
2660
2661
|
if not isinstance(raw, dict):
|
|
2661
|
-
raise ValueError("commandPatterns debe ser un diccionario con global y
|
|
2662
|
+
raise ValueError("commandPatterns debe ser un diccionario con global y project.")
|
|
2662
2663
|
raw_projects = raw.get("projects") or {}
|
|
2663
2664
|
if not isinstance(raw_projects, dict):
|
|
2664
2665
|
raise ValueError("commandPatterns.projects debe ser un diccionario de proyecto a patrones.")
|
|
@@ -2802,6 +2803,12 @@ MAX_CONVERSATION_ID_LENGTH = 128
|
|
|
2802
2803
|
MAX_CONVERSATION_TITLE_LENGTH = 256
|
|
2803
2804
|
MAX_BLOB_SIZE = 50 * 1024 * 1024
|
|
2804
2805
|
MAX_BLOB_HTTP_BYTES = 72 * 1024 * 1024
|
|
2806
|
+
CONVERSATION_UPLOAD_TTL_SECONDS = 300
|
|
2807
|
+
MAX_PENDING_CONVERSATION_UPLOADS = 16
|
|
2808
|
+
MAX_STAGED_CONVERSATION_BYTES = 64 * 1024 * 1024
|
|
2809
|
+
MAX_CONVERSATION_UPLOAD_CHUNKS = 512
|
|
2810
|
+
_UPLOAD_ID_PATTERN = re.compile(r"^[A-Za-z0-9_.:-]{1,128}$")
|
|
2811
|
+
_PENDING_CONVERSATION_UPLOADS: dict[str, dict] = {}
|
|
2805
2812
|
def _obfuscate_saved_api_keys(conn: sqlite3.Connection):
|
|
2806
2813
|
"""Las API keys de los perfiles del servidor, guardadas en claro hasta ahora, pasan a guardarse ofuscadas."""
|
|
2807
2814
|
rows = conn.execute("SELECT id, api_key FROM profiles WHERE api_key != '';").fetchall()
|
|
@@ -3346,6 +3353,166 @@ def save_conversation(session_meta: dict, messages: list[dict] | None = None) ->
|
|
|
3346
3353
|
return _row_to_conversation_header(row)
|
|
3347
3354
|
|
|
3348
3355
|
|
|
3356
|
+
def _validate_int_in_range(value, name: str, min_value: int, max_value: int) -> int:
|
|
3357
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
3358
|
+
raise ValueError(f"{name} debe ser un entero")
|
|
3359
|
+
if value < min_value or value > max_value:
|
|
3360
|
+
raise ValueError(f"{name} fuera de rango ({min_value}..{max_value})")
|
|
3361
|
+
return value
|
|
3362
|
+
|
|
3363
|
+
|
|
3364
|
+
def _validate_upload_id(upload_id) -> str:
|
|
3365
|
+
if not isinstance(upload_id, str) or not _UPLOAD_ID_PATTERN.fullmatch(upload_id):
|
|
3366
|
+
raise ValueError("uploadId no válido")
|
|
3367
|
+
return upload_id
|
|
3368
|
+
|
|
3369
|
+
|
|
3370
|
+
def _purge_expired_conversation_uploads(now: float):
|
|
3371
|
+
expired = [
|
|
3372
|
+
uid for uid, entry in _PENDING_CONVERSATION_UPLOADS.items()
|
|
3373
|
+
if now - entry["updated_at"] > CONVERSATION_UPLOAD_TTL_SECONDS
|
|
3374
|
+
]
|
|
3375
|
+
for uid in expired:
|
|
3376
|
+
del _PENDING_CONVERSATION_UPLOADS[uid]
|
|
3377
|
+
|
|
3378
|
+
|
|
3379
|
+
def _parse_chunk_payload(messages, message_part) -> tuple[int, list[dict] | None, tuple | None]:
|
|
3380
|
+
if messages is not None and message_part is not None:
|
|
3381
|
+
raise ValueError("No se puede combinar messages y messagePart")
|
|
3382
|
+
if messages is None and message_part is None:
|
|
3383
|
+
raise ValueError("Cada tramo debe incluir messages o messagePart")
|
|
3384
|
+
if messages is not None:
|
|
3385
|
+
if not isinstance(messages, list) or not all(isinstance(msg, dict) for msg in messages):
|
|
3386
|
+
raise ValueError("Los mensajes del tramo deben ser una lista de objetos")
|
|
3387
|
+
return len(json.dumps(messages, ensure_ascii=False).encode("utf-8")), messages, None
|
|
3388
|
+
if not isinstance(message_part, dict):
|
|
3389
|
+
raise ValueError("messagePart debe ser un objeto")
|
|
3390
|
+
total_parts = _validate_int_in_range(message_part.get("totalParts"), "totalParts", 1, MAX_CONVERSATION_UPLOAD_CHUNKS)
|
|
3391
|
+
part_index = _validate_int_in_range(message_part.get("partIndex"), "partIndex", 0, total_parts - 1)
|
|
3392
|
+
content = message_part.get("content")
|
|
3393
|
+
if not isinstance(content, str):
|
|
3394
|
+
raise ValueError("content de messagePart debe ser texto")
|
|
3395
|
+
msg_shell = message_part.get("message")
|
|
3396
|
+
if part_index == 0 and not isinstance(msg_shell, dict):
|
|
3397
|
+
raise ValueError("El primer fragmento debe incluir message")
|
|
3398
|
+
if part_index > 0 and msg_shell is not None:
|
|
3399
|
+
raise ValueError("Solo el primer fragmento debe incluir message")
|
|
3400
|
+
shell_bytes = len(json.dumps(msg_shell, ensure_ascii=False).encode("utf-8")) if part_index == 0 else 0
|
|
3401
|
+
return len(content.encode("utf-8")) + shell_bytes, None, (part_index, total_parts, content, msg_shell)
|
|
3402
|
+
|
|
3403
|
+
|
|
3404
|
+
def _acquire_conversation_upload_entry(
|
|
3405
|
+
upload_id: str,
|
|
3406
|
+
conv_id: str,
|
|
3407
|
+
chunk_index: int,
|
|
3408
|
+
total_chunks: int,
|
|
3409
|
+
chunk_bytes: int,
|
|
3410
|
+
part_info: tuple | None,
|
|
3411
|
+
now: float,
|
|
3412
|
+
) -> dict:
|
|
3413
|
+
staged_bytes = sum(item["bytes"] for item in _PENDING_CONVERSATION_UPLOADS.values())
|
|
3414
|
+
if staged_bytes + chunk_bytes > MAX_STAGED_CONVERSATION_BYTES:
|
|
3415
|
+
raise ValueError("Se superó el límite temporal de subida de conversaciones")
|
|
3416
|
+
if chunk_index == 0:
|
|
3417
|
+
if upload_id in _PENDING_CONVERSATION_UPLOADS:
|
|
3418
|
+
raise ValueError("uploadId ya existe")
|
|
3419
|
+
if len(_PENDING_CONVERSATION_UPLOADS) >= MAX_PENDING_CONVERSATION_UPLOADS:
|
|
3420
|
+
raise ValueError("Demasiadas subidas de conversación en curso")
|
|
3421
|
+
if part_info is not None and part_info[0] != 0:
|
|
3422
|
+
raise ValueError("El primer fragmento de un mensaje parcial debe tener partIndex 0")
|
|
3423
|
+
entry = {
|
|
3424
|
+
"conversation_id": conv_id,
|
|
3425
|
+
"total_chunks": total_chunks,
|
|
3426
|
+
"next_index": 0,
|
|
3427
|
+
"messages": [],
|
|
3428
|
+
"partial_message": None,
|
|
3429
|
+
"bytes": 0,
|
|
3430
|
+
"updated_at": now,
|
|
3431
|
+
}
|
|
3432
|
+
_PENDING_CONVERSATION_UPLOADS[upload_id] = entry
|
|
3433
|
+
return entry
|
|
3434
|
+
entry = _PENDING_CONVERSATION_UPLOADS.get(upload_id)
|
|
3435
|
+
if not entry:
|
|
3436
|
+
raise ValueError("Subida de conversación no encontrada o caducada")
|
|
3437
|
+
if entry["conversation_id"] != conv_id or entry["total_chunks"] != total_chunks:
|
|
3438
|
+
raise ValueError("La cabecera del tramo no coincide con la subida")
|
|
3439
|
+
if entry["next_index"] != chunk_index:
|
|
3440
|
+
raise ValueError("Tramo de conversación fuera de orden")
|
|
3441
|
+
return entry
|
|
3442
|
+
|
|
3443
|
+
|
|
3444
|
+
def _apply_chunk_message_part(entry: dict, part_info: tuple):
|
|
3445
|
+
part_index, total_parts, content, msg_shell = part_info
|
|
3446
|
+
if part_index == 0:
|
|
3447
|
+
if entry["partial_message"] is not None:
|
|
3448
|
+
raise ValueError("Ya hay un mensaje parcial en curso")
|
|
3449
|
+
entry["partial_message"] = {
|
|
3450
|
+
"message": dict(msg_shell),
|
|
3451
|
+
"parts": [content],
|
|
3452
|
+
"next_part": 1,
|
|
3453
|
+
"total_parts": total_parts,
|
|
3454
|
+
}
|
|
3455
|
+
else:
|
|
3456
|
+
partial = entry["partial_message"]
|
|
3457
|
+
if not partial or partial["total_parts"] != total_parts or partial["next_part"] != part_index:
|
|
3458
|
+
raise ValueError("Fragmento de mensaje fuera de orden")
|
|
3459
|
+
partial["parts"].append(content)
|
|
3460
|
+
partial["next_part"] += 1
|
|
3461
|
+
partial = entry["partial_message"]
|
|
3462
|
+
if partial and partial["next_part"] == partial["total_parts"]:
|
|
3463
|
+
full_msg = dict(partial["message"])
|
|
3464
|
+
full_msg["content"] = "".join(partial["parts"])
|
|
3465
|
+
entry["messages"].append(full_msg)
|
|
3466
|
+
entry["partial_message"] = None
|
|
3467
|
+
|
|
3468
|
+
|
|
3469
|
+
def save_conversation_chunk(params: dict) -> dict:
|
|
3470
|
+
"""Almacena temporalmente un tramo de mensajes de una conversación para su guardado atómico final."""
|
|
3471
|
+
if not isinstance(params, dict):
|
|
3472
|
+
raise ValueError("Los parámetros deben ser un objeto")
|
|
3473
|
+
upload_id = _validate_upload_id(params.get("uploadId"))
|
|
3474
|
+
conv_id = _validate_conversation_id(params.get("conversationId"))
|
|
3475
|
+
total_chunks = _validate_int_in_range(params.get("totalChunks"), "totalChunks", 1, MAX_CONVERSATION_UPLOAD_CHUNKS)
|
|
3476
|
+
chunk_index = _validate_int_in_range(params.get("chunkIndex"), "chunkIndex", 0, total_chunks - 1)
|
|
3477
|
+
chunk_bytes, messages, part_info = _parse_chunk_payload(params.get("messages"), params.get("messagePart"))
|
|
3478
|
+
|
|
3479
|
+
with _STORAGE_LOCK:
|
|
3480
|
+
now = time.monotonic()
|
|
3481
|
+
_purge_expired_conversation_uploads(now)
|
|
3482
|
+
entry = _acquire_conversation_upload_entry(
|
|
3483
|
+
upload_id, conv_id, chunk_index, total_chunks, chunk_bytes, part_info, now
|
|
3484
|
+
)
|
|
3485
|
+
if messages is not None:
|
|
3486
|
+
if entry["partial_message"] is not None:
|
|
3487
|
+
raise ValueError("Faltan fragmentos del mensaje parcial anterior")
|
|
3488
|
+
entry["messages"].extend(messages)
|
|
3489
|
+
elif part_info is not None:
|
|
3490
|
+
_apply_chunk_message_part(entry, part_info)
|
|
3491
|
+
entry["next_index"] = chunk_index + 1
|
|
3492
|
+
entry["bytes"] += chunk_bytes
|
|
3493
|
+
entry["updated_at"] = now
|
|
3494
|
+
return {"ok": True, "uploadId": upload_id, "receivedChunks": entry["next_index"]}
|
|
3495
|
+
|
|
3496
|
+
|
|
3497
|
+
def commit_conversation_upload(session_meta: dict, upload_id: str) -> dict:
|
|
3498
|
+
"""Consolida atómicamente en SQLite una conversación subida por tramos."""
|
|
3499
|
+
if not isinstance(session_meta, dict):
|
|
3500
|
+
raise ValueError("Los metadatos de la conversación deben ser un objeto")
|
|
3501
|
+
session_id = _validate_conversation_id(session_meta.get("id"))
|
|
3502
|
+
clean_upload_id = _validate_upload_id(upload_id)
|
|
3503
|
+
with _STORAGE_LOCK:
|
|
3504
|
+
_purge_expired_conversation_uploads(time.monotonic())
|
|
3505
|
+
entry = _PENDING_CONVERSATION_UPLOADS.get(clean_upload_id)
|
|
3506
|
+
if not entry:
|
|
3507
|
+
raise ValueError("Subida de conversación no encontrada o caducada")
|
|
3508
|
+
if entry["conversation_id"] != session_id:
|
|
3509
|
+
raise ValueError("La conversación no coincide con la subida")
|
|
3510
|
+
if entry["next_index"] != entry["total_chunks"] or entry["partial_message"] is not None:
|
|
3511
|
+
raise ValueError("La subida de conversación está incompleta")
|
|
3512
|
+
messages = _PENDING_CONVERSATION_UPLOADS.pop(clean_upload_id)["messages"]
|
|
3513
|
+
return save_conversation(session_meta, messages)
|
|
3514
|
+
|
|
3515
|
+
|
|
3349
3516
|
def mark_conversation_server_run(session_id: str, profile_name: str | None = None) -> bool:
|
|
3350
3517
|
"""Marca la conversación en SQLite como ejecutada en servidor asociándole el perfil."""
|
|
3351
3518
|
try:
|
|
@@ -4858,11 +5025,22 @@ def _rpc_delete_conversations(params: dict) -> RpcOutcome:
|
|
|
4858
5025
|
return rpc_result({"deleted": delete_conversation(params.get("id"))})
|
|
4859
5026
|
|
|
4860
5027
|
|
|
5028
|
+
def _rpc_save_conversation(params: dict) -> RpcOutcome:
|
|
5029
|
+
if not isinstance(params, dict):
|
|
5030
|
+
raise ValueError("Los parámetros deben ser un objeto")
|
|
5031
|
+
upload_id = params.get("uploadId")
|
|
5032
|
+
if upload_id is not None:
|
|
5033
|
+
if params.get("messages") is not None:
|
|
5034
|
+
raise ValueError("No se puede combinar uploadId y messages")
|
|
5035
|
+
return rpc_result({"conversation": commit_conversation_upload(params.get("conversation"), upload_id)})
|
|
5036
|
+
return rpc_result({"conversation": save_conversation(params.get("conversation"), params.get("messages"))})
|
|
5037
|
+
|
|
5038
|
+
|
|
4861
5039
|
CONVERSATION_METHODS = {
|
|
4862
5040
|
"zerochat/conversations/list": lambda _params: rpc_result({"conversations": list_conversations()}),
|
|
4863
5041
|
"zerochat/conversations/get": lambda params: rpc_result({"conversation": get_conversation(params.get("id"))}),
|
|
4864
|
-
"zerochat/conversations/save":
|
|
4865
|
-
|
|
5042
|
+
"zerochat/conversations/save": _rpc_save_conversation,
|
|
5043
|
+
"zerochat/conversations/save_chunk": lambda params: rpc_result(save_conversation_chunk(params)),
|
|
4866
5044
|
"zerochat/conversations/rename": lambda params: rpc_result(
|
|
4867
5045
|
{"renamed": rename_conversation(params.get("id"), params.get("title"))}),
|
|
4868
5046
|
"zerochat/conversations/delete": _rpc_delete_conversations,
|
|
@@ -6688,9 +6866,11 @@ class AccessController:
|
|
|
6688
6866
|
# run_command nunca se guarda autorizado entero: sus permisos permanentes son patrones.
|
|
6689
6867
|
tools = {tid: entry for tid, entry in dict(data.get("tools") or {}).items()
|
|
6690
6868
|
if not (tid == COMMAND_TOOL and isinstance(entry, dict) and entry.get("policy") == POLICY_ALLOW)}
|
|
6869
|
+
raw_global = data.get("globalMcpPolicy")
|
|
6870
|
+
global_policy = GLOBAL_POLICY_ASK if raw_global in (None, "", "workspace_trust") else raw_global
|
|
6691
6871
|
return {
|
|
6692
6872
|
"version": POLICY_STATE_VERSION,
|
|
6693
|
-
"globalMcpPolicy":
|
|
6873
|
+
"globalMcpPolicy": global_policy,
|
|
6694
6874
|
"directoryRules": dir_rules,
|
|
6695
6875
|
"tools": tools,
|
|
6696
6876
|
"servers": dict(data.get("servers") or {}),
|
|
@@ -6717,18 +6897,23 @@ class AccessController:
|
|
|
6717
6897
|
dir_rules = list(state["directoryRules"][context.key])
|
|
6718
6898
|
else:
|
|
6719
6899
|
dir_rules = [default_rule]
|
|
6900
|
+
saved_patterns = state["commandPatterns"]
|
|
6720
6901
|
return {
|
|
6721
6902
|
"globalMcpPolicy": session.global_policy if session.global_policy is not None else state["globalMcpPolicy"],
|
|
6722
6903
|
"directoryRules": dir_rules,
|
|
6723
6904
|
"tools": {**state["tools"], **session.tools},
|
|
6724
6905
|
"servers": {**state["servers"], **session.servers},
|
|
6725
|
-
"commandPatterns": {
|
|
6906
|
+
"commandPatterns": {
|
|
6907
|
+
"global": list(saved_patterns["global"]),
|
|
6908
|
+
"project": list(saved_patterns["projects"].get(context.key) or []),
|
|
6909
|
+
"session": list(session.command_patterns)
|
|
6910
|
+
}
|
|
6726
6911
|
}
|
|
6727
6912
|
|
|
6728
|
-
def _command_patterns(self, view: dict
|
|
6913
|
+
def _command_patterns(self, view: dict) -> list[str]:
|
|
6729
6914
|
"""Patrones que rigen en el proyecto: los de todos los proyectos, los de este y los de la sesión."""
|
|
6730
6915
|
patterns = view["commandPatterns"]
|
|
6731
|
-
return [*patterns["global"], *
|
|
6916
|
+
return [*patterns["global"], *patterns["project"], *patterns["session"]]
|
|
6732
6917
|
|
|
6733
6918
|
def export_state(self, context: SecurityContext) -> dict:
|
|
6734
6919
|
return {
|
|
@@ -6805,7 +6990,7 @@ class AccessController:
|
|
|
6805
6990
|
|
|
6806
6991
|
clean_global = None
|
|
6807
6992
|
if "globalMcpPolicy" in state:
|
|
6808
|
-
pol = state["globalMcpPolicy"]
|
|
6993
|
+
pol = GLOBAL_POLICY_ASK if state["globalMcpPolicy"] == "workspace_trust" else state["globalMcpPolicy"]
|
|
6809
6994
|
if pol not in GLOBAL_POLICIES:
|
|
6810
6995
|
raise ValueError(f"Política global no válida: '{pol}'. Válidas: {GLOBAL_POLICIES}")
|
|
6811
6996
|
clean_global = pol
|
|
@@ -6815,15 +7000,33 @@ class AccessController:
|
|
|
6815
7000
|
clean_servers = self._validate_policy_entries(state["servers"], "servers", scope) if "servers" in state else None
|
|
6816
7001
|
return clean_global, clean_rules, clean_tools, clean_servers
|
|
6817
7002
|
|
|
7003
|
+
@staticmethod
|
|
7004
|
+
def _validate_command_patterns_patch(raw) -> dict:
|
|
7005
|
+
"""Valida un parche de commandPatterns: {global, project} o legado {global, projects}."""
|
|
7006
|
+
if not isinstance(raw, dict):
|
|
7007
|
+
raise ValueError("commandPatterns debe ser un diccionario con global y project.")
|
|
7008
|
+
has_projects = "projects" in raw
|
|
7009
|
+
if has_projects and "project" not in raw:
|
|
7010
|
+
return {"mode": "full", "patterns": normalize_command_patterns(raw)}
|
|
7011
|
+
global_patterns = clean_pattern_list(raw.get("global") or [], "commandPatterns.global")
|
|
7012
|
+
project_patterns = clean_pattern_list(raw.get("project") or [], "commandPatterns.project")
|
|
7013
|
+
base = normalize_command_patterns({"global": global_patterns, "projects": raw["projects"]}) if has_projects else None
|
|
7014
|
+
return {
|
|
7015
|
+
"mode": "scoped",
|
|
7016
|
+
"global": global_patterns,
|
|
7017
|
+
"project": project_patterns,
|
|
7018
|
+
"projects": base["projects"] if base is not None else None,
|
|
7019
|
+
}
|
|
7020
|
+
|
|
6818
7021
|
def import_state(self, state: dict, context: SecurityContext):
|
|
6819
7022
|
"""
|
|
6820
7023
|
Aplica un parche parcial persistente (None revoca) y devuelve el estado exportado.
|
|
6821
7024
|
`addDirectoryRules` añade reglas a las guardadas dentro de la misma transacción y
|
|
6822
|
-
`commandPatterns` sustituye los patrones
|
|
7025
|
+
`commandPatterns` sustituye los patrones globales y del proyecto actual sin tocar otros proyectos.
|
|
6823
7026
|
"""
|
|
6824
7027
|
clean_global, clean_rules, clean_tools, clean_servers = self._validate_state_payload(state, SCOPE_PERMANENT)
|
|
6825
7028
|
added_rules = self._validate_directory_rules(state["addDirectoryRules"]) if "addDirectoryRules" in state else []
|
|
6826
|
-
clean_patterns =
|
|
7029
|
+
clean_patterns = self._validate_command_patterns_patch(state["commandPatterns"]) if "commandPatterns" in state else None
|
|
6827
7030
|
|
|
6828
7031
|
project = context.key
|
|
6829
7032
|
default_rule = self.get_default_directory_rule(context)
|
|
@@ -6853,7 +7056,18 @@ class AccessController:
|
|
|
6853
7056
|
if clean_servers is not None:
|
|
6854
7057
|
current["servers"] = self._apply_entry_patch(current.get("servers"), clean_servers)
|
|
6855
7058
|
if clean_patterns is not None:
|
|
6856
|
-
current["commandPatterns"] = clean_patterns
|
|
7059
|
+
current["commandPatterns"] = self._merge_command_patterns(current["commandPatterns"], clean_patterns, project)
|
|
7060
|
+
|
|
7061
|
+
@staticmethod
|
|
7062
|
+
def _merge_command_patterns(current_patterns: dict, patch: dict, project: str) -> dict:
|
|
7063
|
+
if patch["mode"] == "full":
|
|
7064
|
+
return patch["patterns"]
|
|
7065
|
+
projects = dict(patch["projects"] if patch["projects"] is not None else current_patterns["projects"])
|
|
7066
|
+
if patch["project"]:
|
|
7067
|
+
projects[project] = patch["project"]
|
|
7068
|
+
else:
|
|
7069
|
+
projects.pop(project, None)
|
|
7070
|
+
return normalize_command_patterns({"global": patch["global"], "projects": projects})
|
|
6857
7071
|
|
|
6858
7072
|
def _forget_session_overrides(self, project: str, clean_global, clean_rules, added_rules, clean_tools, clean_servers):
|
|
6859
7073
|
"""Lo guardado sustituye o revoca lo equivalente en la sesión (las reglas de carpeta, solo en su proyecto)."""
|
|
@@ -7142,8 +7356,8 @@ class AccessController:
|
|
|
7142
7356
|
3. Política global allow_all -> allow incondicional.
|
|
7143
7357
|
4. Política granular de herramienta -> allow.
|
|
7144
7358
|
5. Política de servidor completo -> allow incondicional para sus herramientas.
|
|
7145
|
-
6. run_command:
|
|
7146
|
-
7. Herramientas con ruta: reglas de directorio
|
|
7359
|
+
6. run_command: reglas de directorio (RWX:/** permite todo; X habilita la carpeta) y patrones de comando.
|
|
7360
|
+
7. Herramientas con ruta: reglas de directorio.
|
|
7147
7361
|
8. Por defecto -> ask (solicitar confirmación), con la regla sugerida si la hay.
|
|
7148
7362
|
"""
|
|
7149
7363
|
status, reason, details, offer = self._evaluate(tool_name, dict(raw_args or {}), context, server_id)
|
|
@@ -7194,7 +7408,7 @@ class AccessController:
|
|
|
7194
7408
|
return raw_path if re.match(r"^(/|[A-Za-z]:[\\/])", raw_path) else str(cwd / raw_path)
|
|
7195
7409
|
|
|
7196
7410
|
def _is_allowed_trust_segment(self, segment: str, cwd: Path, directory_rules: list[str], ctx: SecurityContext) -> bool:
|
|
7197
|
-
"""Subcomando permitido por
|
|
7411
|
+
"""Subcomando permitido por las reglas del proyecto: local o con rutas dentro de reglas RW."""
|
|
7198
7412
|
refs = command_outside_references(segment)
|
|
7199
7413
|
if refs is None:
|
|
7200
7414
|
return False
|
|
@@ -7205,14 +7419,13 @@ class AccessController:
|
|
|
7205
7419
|
|
|
7206
7420
|
def _evaluate_command(self, raw_command: str, view: dict, ctx: SecurityContext) -> tuple[str, str, str, dict | None]:
|
|
7207
7421
|
"""
|
|
7208
|
-
Valida cada subcomando por separado:
|
|
7209
|
-
|
|
7210
|
-
|
|
7211
|
-
reglas RW del proyecto (tras una tubería, solo
|
|
7212
|
-
|
|
7422
|
+
Valida cada subcomando por separado: con RWX:/** el proyecto queda sin restricción de comandos.
|
|
7423
|
+
En otro caso, la carpeta donde se ejecuta (inicial y tras cada cd) requiere permiso X en directoryRules;
|
|
7424
|
+
cada cd debe llevar a una carpeta cubierta por las reglas de directorio, y el resto tiene que estar
|
|
7425
|
+
cubierto por un patrón o quedarse en el proyecto o en reglas RW del proyecto (tras una tubería, solo
|
|
7426
|
+
un filtro).
|
|
7213
7427
|
"""
|
|
7214
|
-
|
|
7215
|
-
if trust and self._has_full_directory_access(view["directoryRules"]):
|
|
7428
|
+
if self._has_full_directory_access(view["directoryRules"]):
|
|
7216
7429
|
return POLICY_ALLOW, "directory_rule_allow", "", None
|
|
7217
7430
|
if not self.evaluate_directory_rule("X", str(ctx.workspace_dir), view["directoryRules"], ctx)["allowed"]:
|
|
7218
7431
|
return (POLICY_ASK, "command_directory_without_execute",
|
|
@@ -7221,8 +7434,8 @@ class AccessController:
|
|
|
7221
7434
|
if segments is None:
|
|
7222
7435
|
return (POLICY_ASK, "command_chaining_requires_approval",
|
|
7223
7436
|
f"El comando usa sintaxis de shell que no se puede validar por partes: {raw_command}", None)
|
|
7224
|
-
patterns = self._command_patterns(view
|
|
7225
|
-
cwd,
|
|
7437
|
+
patterns = self._command_patterns(view)
|
|
7438
|
+
cwd, by_rule, uncovered = ctx.workspace_dir, False, []
|
|
7226
7439
|
for operator, segment in segments:
|
|
7227
7440
|
directory = cd_target(segment)
|
|
7228
7441
|
if directory is not None:
|
|
@@ -7236,17 +7449,18 @@ class AccessController:
|
|
|
7236
7449
|
f"La carpeta no tiene permiso de ejecución (X): {cwd}", None)
|
|
7237
7450
|
elif any(matches_command_pattern(segment, p) for p in patterns):
|
|
7238
7451
|
continue
|
|
7239
|
-
elif
|
|
7452
|
+
elif self._is_allowed_trust_segment(segment, cwd, view["directoryRules"], ctx) and (
|
|
7240
7453
|
operator != "|" or segment.split()[0] in WORKSPACE_TRUST_PIPE_FILTERS):
|
|
7241
|
-
|
|
7454
|
+
by_rule = True
|
|
7242
7455
|
else:
|
|
7243
7456
|
uncovered.append(segment)
|
|
7244
7457
|
if not uncovered:
|
|
7245
|
-
return POLICY_ALLOW, "
|
|
7246
|
-
|
|
7247
|
-
|
|
7248
|
-
|
|
7249
|
-
|
|
7458
|
+
return POLICY_ALLOW, "directory_rule_allow" if by_rule else "command_pattern_allow", "", None
|
|
7459
|
+
reason, details = (
|
|
7460
|
+
("command_outside_allowed_patterns", f"Comando fuera de los patrones autorizados: {'; '.join(uncovered)}")
|
|
7461
|
+
if patterns
|
|
7462
|
+
else ("command_outside_directory_rules", "El comando accede a recursos globales o rutas fuera de las reglas de directorio.")
|
|
7463
|
+
)
|
|
7250
7464
|
return POLICY_ASK, reason, details, command_rule_offer(uncovered)
|
|
7251
7465
|
|
|
7252
7466
|
def _evaluate_path(self, tool_name: str, access: str, path: str, view: dict, ctx: SecurityContext) -> tuple[str, str, str, dict | None]:
|
|
@@ -9903,7 +10117,7 @@ def reset_session_authorizations():
|
|
|
9903
10117
|
ACCESS_CONTROLLER.apply_tool_decision(tool_decision, ctx, server_id=server_id)
|
|
9904
10118
|
permanent_tools = ACCESS_CONTROLLER.export_state(ctx).get("tools") or {}
|
|
9905
10119
|
ACCESS_CONTROLLER.apply_session_overlay({
|
|
9906
|
-
"globalMcpPolicy":
|
|
10120
|
+
"globalMcpPolicy": GLOBAL_POLICY_ASK,
|
|
9907
10121
|
"tools": {
|
|
9908
10122
|
name: {"policy": POLICY_ALLOW}
|
|
9909
10123
|
for name in LOCAL_TOOL_HANDLERS
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|