asilo-core 0.1.0a1__py3-none-any.whl
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.
- asilo/__init__.py +31 -0
- asilo/cli/__init__.py +4 -0
- asilo/cli/__main__.py +72 -0
- asilo/decorators/__init__.py +15 -0
- asilo/decorators/guardrail.py +38 -0
- asilo/decorators/hitl.py +39 -0
- asilo/decorators/schema.py +63 -0
- asilo/errors.py +38 -0
- asilo/templates/.gitkeep +0 -0
- asilo/templates/__init__.py +7 -0
- asilo_core-0.1.0a1.dist-info/METADATA +168 -0
- asilo_core-0.1.0a1.dist-info/RECORD +16 -0
- asilo_core-0.1.0a1.dist-info/WHEEL +4 -0
- asilo_core-0.1.0a1.dist-info/entry_points.txt +2 -0
- asilo_core-0.1.0a1.dist-info/licenses/LICENSE +201 -0
- asilo_core-0.1.0a1.dist-info/licenses/NOTICE +26 -0
asilo/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""asilo-core — SDK de gobernanza para sistemas multi-agente.
|
|
2
|
+
|
|
3
|
+
La API pública de este paquete es exactamente lo que aparece en ``__all__``.
|
|
4
|
+
Todo lo demás es privado y puede cambiar sin bump mayor de versión.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from asilo.decorators import enforce_schema, guardrail, hitl
|
|
8
|
+
from asilo.errors import AxiomViolation, HumanReviewRequired, SchemaViolation
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _resolve_version() -> str:
|
|
12
|
+
"""Versión del paquete instalado, derivada del tag git en tiempo de build."""
|
|
13
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
return version("asilo-core")
|
|
17
|
+
except PackageNotFoundError:
|
|
18
|
+
# Ejecutando desde el árbol de fuentes sin instalar.
|
|
19
|
+
return "0.0.0.dev0"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
__version__ = _resolve_version()
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"AxiomViolation",
|
|
26
|
+
"HumanReviewRequired",
|
|
27
|
+
"SchemaViolation",
|
|
28
|
+
"enforce_schema",
|
|
29
|
+
"guardrail",
|
|
30
|
+
"hitl",
|
|
31
|
+
]
|
asilo/cli/__init__.py
ADDED
asilo/cli/__main__.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""CLI honesto de estado; las capacidades no implementadas fallan en lenguaje llano."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _parser() -> argparse.ArgumentParser:
|
|
12
|
+
parser = argparse.ArgumentParser(prog="asilo")
|
|
13
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
14
|
+
for name in ("status", "doctor"):
|
|
15
|
+
status = subparsers.add_parser(name)
|
|
16
|
+
status.add_argument("--json", action="store_true", dest="as_json")
|
|
17
|
+
for name in ("init", "explain", "run"):
|
|
18
|
+
blocked = subparsers.add_parser(name)
|
|
19
|
+
blocked.add_argument("arguments", nargs="*")
|
|
20
|
+
return parser
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _status() -> dict[str, object]:
|
|
24
|
+
return {
|
|
25
|
+
"ok": True,
|
|
26
|
+
"release_ready": False,
|
|
27
|
+
"network_called": False,
|
|
28
|
+
"capabilities": {
|
|
29
|
+
"errors": "ready",
|
|
30
|
+
"schema_validation": "ready",
|
|
31
|
+
"guardrail_policy": "stub",
|
|
32
|
+
"hitl_resume": "stub",
|
|
33
|
+
"audit_sink": "unavailable",
|
|
34
|
+
"project_scaffolding": "external:kasai-crew",
|
|
35
|
+
},
|
|
36
|
+
"next": (
|
|
37
|
+
"Use kasai-crew scaffold para el plano de control. "
|
|
38
|
+
"No use este paquete para proteger operaciones reales."
|
|
39
|
+
),
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def app(argv: Sequence[str] | None = None) -> int:
|
|
44
|
+
args = _parser().parse_args(argv)
|
|
45
|
+
if args.command in {"status", "doctor"}:
|
|
46
|
+
payload = _status()
|
|
47
|
+
if args.as_json:
|
|
48
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
49
|
+
else:
|
|
50
|
+
print("asilo-core · estado de capacidades")
|
|
51
|
+
for name, state in payload["capabilities"].items():
|
|
52
|
+
print(f" {name}: {state}")
|
|
53
|
+
print(f" release_ready: {str(payload['release_ready']).lower()}")
|
|
54
|
+
print(f" siguiente: {payload['next']}")
|
|
55
|
+
return 0
|
|
56
|
+
|
|
57
|
+
print(
|
|
58
|
+
f"asilo {args.command}: comando reservado y bloqueado; "
|
|
59
|
+
"consulta `asilo status` y docs/PLAN_IMPLEMENTACION.md",
|
|
60
|
+
file=sys.stderr,
|
|
61
|
+
)
|
|
62
|
+
if args.command == "init":
|
|
63
|
+
print(
|
|
64
|
+
"Para crear el plano de control de un repo usa "
|
|
65
|
+
"`kasai-crew scaffold --repo RUTA`.",
|
|
66
|
+
file=sys.stderr,
|
|
67
|
+
)
|
|
68
|
+
return 2
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
if __name__ == "__main__":
|
|
72
|
+
raise SystemExit(app())
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Decoradores de gobernanza.
|
|
2
|
+
|
|
3
|
+
Se aplican en este orden (de fuera hacia dentro), porque cada capa protege a la siguiente::
|
|
4
|
+
|
|
5
|
+
@guardrail(...) # 1. ¿está permitida la acción?
|
|
6
|
+
@hitl(...) # 2. ¿necesita aprobación humana?
|
|
7
|
+
@enforce_schema(...) # 3. ¿la salida tiene la forma esperada?
|
|
8
|
+
def accion(...): ...
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from asilo.decorators.guardrail import guardrail
|
|
12
|
+
from asilo.decorators.hitl import hitl
|
|
13
|
+
from asilo.decorators.schema import enforce_schema
|
|
14
|
+
|
|
15
|
+
__all__ = ["enforce_schema", "guardrail", "hitl"]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Guardrail axiomático: bloquea acciones que violan un axioma declarado."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, TypeVar
|
|
8
|
+
|
|
9
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
10
|
+
|
|
11
|
+
DEFAULT_AXIOMS_FILE = Path(".asilo/axioms.yaml")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def guardrail(
|
|
15
|
+
axioms_file: str | Path = DEFAULT_AXIOMS_FILE,
|
|
16
|
+
*,
|
|
17
|
+
fail_closed: bool = True,
|
|
18
|
+
) -> Callable[[F], F]:
|
|
19
|
+
"""Evalúa la acción contra los axiomas antes de ejecutarla.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
axioms_file: ruta al registro de axiomas del proyecto.
|
|
23
|
+
fail_closed: si el archivo de axiomas no existe o no parsea, ``True`` bloquea la
|
|
24
|
+
ejecución y ``False`` la permite. El valor por defecto es ``True`` porque un
|
|
25
|
+
control que se desactiva solo cuando falla no es un control.
|
|
26
|
+
|
|
27
|
+
Raises:
|
|
28
|
+
AxiomViolation: cuando la acción viola un axioma.
|
|
29
|
+
|
|
30
|
+
Contrato de implementación (pendiente):
|
|
31
|
+
1. Cargar y cachear los axiomas del archivo.
|
|
32
|
+
2. Resolver el contexto de la llamada (nombre de la acción, argumentos, rol activo).
|
|
33
|
+
3. Evaluar cada axioma aplicable; el primero que falle interrumpe.
|
|
34
|
+
4. Emitir un evento de auditoría con ``trace_id``, tanto si permite como si bloquea.
|
|
35
|
+
"""
|
|
36
|
+
raise NotImplementedError(
|
|
37
|
+
"guardrail: pendiente de implementar — ver docs/asilo/arquitectura/ADR-001-asilo.md"
|
|
38
|
+
)
|
asilo/decorators/hitl.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Human-in-the-Loop: pausa la ejecución y espera decisión humana."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, TypeVar
|
|
8
|
+
|
|
9
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
10
|
+
|
|
11
|
+
DEFAULT_THRESHOLDS_FILE = Path(".asilo/thresholds.yaml")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def hitl(
|
|
15
|
+
*,
|
|
16
|
+
threshold: float | None = None,
|
|
17
|
+
thresholds_file: str | Path = DEFAULT_THRESHOLDS_FILE,
|
|
18
|
+
reason: str = "",
|
|
19
|
+
) -> Callable[[F], F]:
|
|
20
|
+
"""Interrumpe antes de ejecutar si la confianza cae bajo el umbral.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
threshold: umbral explícito (0.0–1.0). Si es ``None``, se lee de ``thresholds_file``.
|
|
24
|
+
thresholds_file: registro de umbrales por tipo de acción.
|
|
25
|
+
reason: texto que se le muestra al humano para que decida con contexto.
|
|
26
|
+
|
|
27
|
+
Raises:
|
|
28
|
+
HumanReviewRequired: cuando la acción queda pendiente de aprobación.
|
|
29
|
+
|
|
30
|
+
Contrato de implementación (pendiente):
|
|
31
|
+
1. Resolver el umbral aplicable a esta acción.
|
|
32
|
+
2. Si la confianza lo supera, ejecutar sin interrumpir.
|
|
33
|
+
3. Si no, serializar el estado pendiente para que pueda reanudarse después de la
|
|
34
|
+
decisión — una pausa que pierde el estado obliga a rehacer el trabajo.
|
|
35
|
+
4. Notificar por el canal configurado (consola o dashboard).
|
|
36
|
+
"""
|
|
37
|
+
raise NotImplementedError(
|
|
38
|
+
"hitl: pendiente de implementar — ver docs/asilo/arquitectura/ADR-001-asilo.md"
|
|
39
|
+
)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Validación de salida: obliga a que el modelo devuelva la forma esperada."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from functools import wraps
|
|
7
|
+
from inspect import iscoroutinefunction
|
|
8
|
+
from typing import Any, TypeVar, cast
|
|
9
|
+
|
|
10
|
+
from pydantic import ValidationError
|
|
11
|
+
|
|
12
|
+
from asilo.errors import SchemaViolation
|
|
13
|
+
|
|
14
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def enforce_schema(model: type, *, max_repairs: int = 0) -> Callable[[F], F]:
|
|
18
|
+
"""Valida la salida contra un modelo Pydantic antes de devolverla.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
model: modelo Pydantic que describe la salida esperada.
|
|
22
|
+
max_repairs: se conserva para detectar configuración antigua; sólo se acepta cero.
|
|
23
|
+
Reejecutar aquí podría duplicar efectos y requiere otro contrato.
|
|
24
|
+
|
|
25
|
+
Raises:
|
|
26
|
+
SchemaViolation: si la salida no valida.
|
|
27
|
+
|
|
28
|
+
La función envuelta se ejecuta exactamente una vez. Una reparación, retry o nueva llamada
|
|
29
|
+
al modelo debe vivir fuera de este decorador y declarar idempotencia, coste y auditoría.
|
|
30
|
+
"""
|
|
31
|
+
if not isinstance(model, type) or not callable(getattr(model, "model_validate", None)):
|
|
32
|
+
raise TypeError("model debe ser una clase Pydantic con model_validate")
|
|
33
|
+
if max_repairs != 0:
|
|
34
|
+
raise ValueError("max_repairs debe ser 0; la reejecución automática no está autorizada")
|
|
35
|
+
|
|
36
|
+
def decorator(function: F) -> F:
|
|
37
|
+
if iscoroutinefunction(function):
|
|
38
|
+
|
|
39
|
+
@wraps(function)
|
|
40
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
41
|
+
result = await function(*args, **kwargs)
|
|
42
|
+
return _validate(model, result)
|
|
43
|
+
|
|
44
|
+
return cast(F, async_wrapper)
|
|
45
|
+
|
|
46
|
+
@wraps(function)
|
|
47
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
48
|
+
result = function(*args, **kwargs)
|
|
49
|
+
return _validate(model, result)
|
|
50
|
+
|
|
51
|
+
return cast(F, wrapper)
|
|
52
|
+
|
|
53
|
+
return decorator
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _validate(model: type, result: Any) -> Any:
|
|
57
|
+
try:
|
|
58
|
+
return model.model_validate(result)
|
|
59
|
+
except ValidationError:
|
|
60
|
+
# No encadenar el error de Pydantic: puede incluir el valor rechazado.
|
|
61
|
+
raise SchemaViolation(
|
|
62
|
+
f"la salida no cumple el esquema {model.__name__}; contenido omitido"
|
|
63
|
+
) from None
|
asilo/errors.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Jerarquía de errores de ASILO.
|
|
2
|
+
|
|
3
|
+
Todo error de gobernanza hereda de :class:`AsiloError` para que un consumidor pueda
|
|
4
|
+
capturar la familia completa sin enumerar cada caso.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AsiloError(Exception):
|
|
11
|
+
"""Base de todos los errores de gobernanza."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AxiomViolation(AsiloError):
|
|
15
|
+
"""La acción viola un axioma declarado en ``.asilo/axioms.yaml``.
|
|
16
|
+
|
|
17
|
+
No se reintenta: un axioma es una regla dura, no una condición transitoria.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, axiom_id: str, message: str) -> None:
|
|
21
|
+
self.axiom_id = axiom_id
|
|
22
|
+
super().__init__(f"[{axiom_id}] {message}")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SchemaViolation(AsiloError):
|
|
26
|
+
"""La salida del modelo no valida contra el esquema esperado."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class HumanReviewRequired(AsiloError):
|
|
30
|
+
"""La ejecución se detuvo esperando aprobación humana (Human-in-the-Loop)."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, action: str, confidence: float, threshold: float) -> None:
|
|
33
|
+
self.action = action
|
|
34
|
+
self.confidence = confidence
|
|
35
|
+
self.threshold = threshold
|
|
36
|
+
super().__init__(
|
|
37
|
+
f"'{action}' requiere revisión humana: confianza {confidence:.2f} < umbral {threshold:.2f}"
|
|
38
|
+
)
|
asilo/templates/.gitkeep
ADDED
|
File without changes
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Motor de plantillas.
|
|
2
|
+
|
|
3
|
+
El Agente Cero no escribe código Python libre: llena variables validadas y las inyecta en
|
|
4
|
+
plantillas Jinja2 prefabricadas. Así la salida no puede tener errores de sintaxis.
|
|
5
|
+
|
|
6
|
+
Las plantillas ``.jinja`` viven junto a este módulo y se empaquetan con la distribución.
|
|
7
|
+
"""
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: asilo-core
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: SDK de gobernanza para sistemas multi-agente: guardrails, validación de esquemas y Agente Cero
|
|
5
|
+
Project-URL: Homepage, https://codeberg.org/kasailabs/asilo-core
|
|
6
|
+
Project-URL: Documentation, https://codeberg.org/kasailabs/asilo-core/src/branch/main/docs/INDEX.md
|
|
7
|
+
Project-URL: Repository, https://codeberg.org/kasailabs/asilo-core
|
|
8
|
+
Project-URL: Changelog, https://codeberg.org/kasailabs/asilo-core/src/branch/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Issues, https://codeberg.org/kasailabs/asilo-core/issues
|
|
10
|
+
Author: Kasai Labs
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
License-File: NOTICE
|
|
14
|
+
Keywords: agents,ai,governance,guardrails,llm,security
|
|
15
|
+
Classifier: Development Status :: 3 - Alpha
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: pydantic>=2.7
|
|
23
|
+
Requires-Dist: pyyaml>=6.0
|
|
24
|
+
Provides-Extra: cli
|
|
25
|
+
Requires-Dist: jinja2>=3.1; extra == 'cli'
|
|
26
|
+
Requires-Dist: litellm>=1.40; extra == 'cli'
|
|
27
|
+
Requires-Dist: rich>=13.7; extra == 'cli'
|
|
28
|
+
Requires-Dist: typer>=0.12; extra == 'cli'
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
32
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# asilo-core
|
|
36
|
+
|
|
37
|
+
> Implementación Python de referencia **candidata** para controles de sistemas multiagente.
|
|
38
|
+
> Aspira a traducir una revisión identificable de ASILO a contratos, decisiones de política,
|
|
39
|
+
> auditoría y revisión humana sin definir la metodología dentro del paquete.
|
|
40
|
+
|
|
41
|
+
**Perfil Milpa:** `library` (P5) · **Distribución prevista:** PyPI `asilo-core` · **Estado:** alpha parcial no publicable
|
|
42
|
+
|
|
43
|
+
## TL;DR
|
|
44
|
+
|
|
45
|
+
- `enforce_schema` ya valida resultados Pydantic sync/async y nunca reejecuta la función.
|
|
46
|
+
- `asilo status` y `asilo doctor` informan capacidades sin red ni secretos.
|
|
47
|
+
- `guardrail`, HITL, auditoría y comandos de dominio continúan bloqueados.
|
|
48
|
+
- El scaffolding operativo vive hoy en `kasai-crew scaffold`; no se duplica aquí.
|
|
49
|
+
- Empieza por [Quickstart](docs/QUICKSTART.md), [diagramas](docs/architecture/DIAGRAMS.md) e
|
|
50
|
+
[índice](docs/INDEX.md).
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## Documentación
|
|
55
|
+
|
|
56
|
+
Cuatro niveles, de lo general a lo particular, con ruta de lectura por perfil en
|
|
57
|
+
[`docs/INDEX.md`](docs/INDEX.md):
|
|
58
|
+
|
|
59
|
+
| Perfil | Empieza en |
|
|
60
|
+
|---|---|
|
|
61
|
+
| No técnico | [`docs/01-manifiesto/`](docs/01-manifiesto/README.md) — la aduana: el modelo propone, la librería valida la forma |
|
|
62
|
+
| Arquitecto | [`docs/02-diagramas/`](docs/02-diagramas/README.md) — contexto, capas, secuencia, escalada humana |
|
|
63
|
+
| Operador | [`docs/03-operacion/`](docs/03-operacion/README.md) — instalación, comandos, qué no está implementado |
|
|
64
|
+
| Auditor | [`docs/04-contratos/`](docs/04-contratos/README.md) — API, axiomas, errores, ADR, fuentes de verdad |
|
|
65
|
+
|
|
66
|
+
Sitio navegable (MkDocs Material, con el estándar documental de Horcón), desde la raíz del repo:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
../horcon/.venv/bin/python -m horcon audit-docs . # frontmatter, navegación, enlaces
|
|
70
|
+
../horcon/.venv/bin/python -m horcon docs build . # ensambla tmp/site-src/ y construye tmp/site/
|
|
71
|
+
../horcon/.venv/bin/python -m horcon docs serve . # sirve en 127.0.0.1
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## Diseño objetivo
|
|
77
|
+
|
|
78
|
+
Un agente autónomo puede producir información falsa, filtrar datos o solicitar acciones
|
|
79
|
+
irreversibles. El diseño objetivo interpone controles entre el modelo y el mundo:
|
|
80
|
+
|
|
81
|
+
| Control | Mecanismo objetivo | Estado actual |
|
|
82
|
+
|---------|-------------------|---------------|
|
|
83
|
+
| **Esquema** | `@enforce_schema` valida forma contra Pydantic | implementado; una ejecución, sin repairs |
|
|
84
|
+
| **Política** | `@guardrail` obtiene una decisión antes de ejecutar | stub; contrato pendiente |
|
|
85
|
+
| **Revisión humana** | `@hitl` persiste, autoriza y reanuda una decisión | stub; protocolo pendiente |
|
|
86
|
+
| **Auditoría** | eventos minimizados y trazables | inexistente |
|
|
87
|
+
|
|
88
|
+
Un decorador dentro del mismo proceso no constituye por sí solo una frontera de seguridad:
|
|
89
|
+
código con el mismo privilegio puede evitarlo. El enforcement real depende también del
|
|
90
|
+
sistema consumidor, sus herramientas, credenciales y puntos de aplicación.
|
|
91
|
+
|
|
92
|
+
### Qué protege cada pieza, y qué no
|
|
93
|
+
|
|
94
|
+
| Pieza | Qué protege hoy | Qué NO protege |
|
|
95
|
+
|---|---|---|
|
|
96
|
+
| `enforce_schema` | La **forma** del resultado contra un modelo Pydantic; una sola ejecución, sin reintentos | Que el contenido sea verdadero, que esté autorizado, o que no lleve una instrucción escondida para el siguiente agente (ver [`docs/asilo/seguridad/aduana-llm.md`](docs/asilo/seguridad/aduana-llm.md)) |
|
|
97
|
+
| `guardrail`, `hitl` | Nada: son firmas con contrato escrito que lanzan `NotImplementedError` | Cualquier cosa que su nombre sugiera; llamarlos no bloquea ni pausa nada todavía |
|
|
98
|
+
| `asilo status` / `asilo doctor` | Informar, sin red, qué existe | Que lo informado sea "seguro"; son diagnóstico, no control |
|
|
99
|
+
|
|
100
|
+
Lo que debe poner quien consume esta librería: autenticación y autorización de quien invoca la
|
|
101
|
+
acción, credenciales de mínimo privilegio, límites de red y un punto de aplicación fuera del
|
|
102
|
+
proceso que pueda de verdad impedir la acción si el decorador falla o se evade.
|
|
103
|
+
|
|
104
|
+
Una lección concreta, tomada de un hallazgo real en el framework hermano Horcón y registrada en
|
|
105
|
+
[`reports/2026-09-22-mejoras-desde-horcon.md`](reports/2026-09-22-mejoras-desde-horcon.md): cuando
|
|
106
|
+
exista una revisión humana real (`hitl` dejará de ser un stub), su aprobación **no puede
|
|
107
|
+
representarse con un booleano autodeclarado** (`approved: true`) ni con un campo de texto que
|
|
108
|
+
rellene el propio código que pide la aprobación. Ese diseño ya falló una vez en un sistema
|
|
109
|
+
relacionado: un campo que declaraba quién firmaba se verificaba con la misma firma que lo emitía,
|
|
110
|
+
así que cualquiera podía declararse revisor humano. Una aprobación debe llevar una referencia
|
|
111
|
+
verificable a quien decide y una huella de qué se revisó exactamente, no la palabra del propio
|
|
112
|
+
proceso que la solicita. Esto no está implementado hoy; es una condición que cualquier contrato
|
|
113
|
+
futuro de `hitl` debe cumplir antes de aceptarse.
|
|
114
|
+
|
|
115
|
+
## Instalación
|
|
116
|
+
|
|
117
|
+
El paquete aún no está publicado. El siguiente comando documenta la distribución prevista,
|
|
118
|
+
no un paso que funcione hoy:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
pip install asilo-core
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## API ejecutable: validación de esquema
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
from asilo.decorators import enforce_schema
|
|
128
|
+
from pydantic import BaseModel
|
|
129
|
+
|
|
130
|
+
class Reporte(BaseModel):
|
|
131
|
+
titulo: str
|
|
132
|
+
hallazgos: list[str]
|
|
133
|
+
|
|
134
|
+
@enforce_schema(Reporte)
|
|
135
|
+
def normalizar_reporte(payload: dict) -> Reporte:
|
|
136
|
+
return payload
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## CLI y Agente Cero
|
|
140
|
+
|
|
141
|
+
El diagnóstico es ejecutable y no llama red:
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
asilo status
|
|
145
|
+
asilo doctor --json
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`asilo init`, `explain` y `run` permanecen reservados y salen con código 2, sin traceback.
|
|
149
|
+
Para preparar un repo, el recorrido vigente es `kasai-crew scaffold --repo RUTA`. Esto evita
|
|
150
|
+
dos implementaciones distintas del Agente 0.
|
|
151
|
+
|
|
152
|
+
## Estructura
|
|
153
|
+
|
|
154
|
+
Sigue el perfil `library` del doc 21 de Milpa: `src/` layout (el paquete no vive en la
|
|
155
|
+
raíz), `tests/` con suite adversarial obligatoria por tratarse de un proyecto con LLM,
|
|
156
|
+
y `docs/asilo/` con los artefactos de gobernanza del propio SDK.
|
|
157
|
+
|
|
158
|
+
## Estado de implementación
|
|
159
|
+
|
|
160
|
+
Alpha parcial. Los errores, la validación de esquema y el diagnóstico existen; política,
|
|
161
|
+
auditoría, HITL durable y enforcement externo no. Ver `docs/PLAN_IMPLEMENTACION.md` para
|
|
162
|
+
puertas y criterios de release. No usar este repo para proteger operaciones reales.
|
|
163
|
+
|
|
164
|
+
## Licencia
|
|
165
|
+
|
|
166
|
+
Apache-2.0 — texto completo en [`LICENSE`](LICENSE).
|
|
167
|
+
|
|
168
|
+
La marca ASILO **no** se licencia con el código (sección 6 de Apache-2.0); ver [`NOTICE`](NOTICE).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
asilo/__init__.py,sha256=VVajYDie8ewsAR_tW7zjfhZTGuqV5R0VV8L7PKqXgQE,881
|
|
2
|
+
asilo/errors.py,sha256=JUi7j8UBQrCoFMX3YLx28Q5iMW0CLnZ27O5EtBRVRkg,1195
|
|
3
|
+
asilo/cli/__init__.py,sha256=ZB4mppQZyug1f0it5L1C3BWfC225nTfmDmNWRajA3jo,121
|
|
4
|
+
asilo/cli/__main__.py,sha256=Zt1HhPLsxMkLrcE1Q31e9pB0fcbunrv-LlKz9h950fI,2298
|
|
5
|
+
asilo/decorators/__init__.py,sha256=h_hyFHDUO0XWeq3ewtyIqO6UnIdz4z18-4vEI2nYQhU,538
|
|
6
|
+
asilo/decorators/guardrail.py,sha256=hS6em6oXUB_IX_A4-9_-S3oW6AIDPsKdyHsaXShpLeQ,1397
|
|
7
|
+
asilo/decorators/hitl.py,sha256=O-EZO4Ntre22Tz9rHscuM_MoohB5UGqGZgHuoMfIOws,1428
|
|
8
|
+
asilo/decorators/schema.py,sha256=7hVH2Kh6YkVQccxtmISLCvqprUA_O0PSkxYpIRbZwIs,2240
|
|
9
|
+
asilo/templates/.gitkeep,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
asilo/templates/__init__.py,sha256=7TENPchTN_XbSu-KUCt9WivFtjJK4LawKSOPcTsswKI,296
|
|
11
|
+
asilo_core-0.1.0a1.dist-info/METADATA,sha256=XOjFD5lSHB3h0SI_XovFqDZXakeJNa1kbPJ3T7O1hmU,7804
|
|
12
|
+
asilo_core-0.1.0a1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
13
|
+
asilo_core-0.1.0a1.dist-info/entry_points.txt,sha256=6GpiuA0Y4iog8j1h7VepLCvnbroY_7awqMMTTzNt6Ks,49
|
|
14
|
+
asilo_core-0.1.0a1.dist-info/licenses/LICENSE,sha256=61z1CXbOqbRhjTEBfTZM6MPsUYqZVu7BD1pQEVry6xs,11340
|
|
15
|
+
asilo_core-0.1.0a1.dist-info/licenses/NOTICE,sha256=4xsb6GiQwtofPlAhp5RGEX-56m0nA6-lDkLINdsTILE,1138
|
|
16
|
+
asilo_core-0.1.0a1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Kasai Labs
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
ASILO Core
|
|
2
|
+
Copyright 2026 Kasai Labs
|
|
3
|
+
|
|
4
|
+
This product includes software developed at Kasai Labs
|
|
5
|
+
(https://codeberg.org/kasailabs).
|
|
6
|
+
|
|
7
|
+
--------------------------------------------------------------------------------
|
|
8
|
+
Marcas / Trademarks
|
|
9
|
+
--------------------------------------------------------------------------------
|
|
10
|
+
|
|
11
|
+
"ASILO", "MILPA" y "Kasai Labs" son marcas de Kasai Labs.
|
|
12
|
+
|
|
13
|
+
La Licencia Apache 2.0 concede derechos sobre el **código**, no sobre las marcas.
|
|
14
|
+
Su seccion 6 ("Trademarks") excluye expresamente los nombres comerciales, marcas
|
|
15
|
+
registradas y marcas de servicio del licenciante.
|
|
16
|
+
|
|
17
|
+
En la practica esto significa que puedes usar, modificar y redistribuir este
|
|
18
|
+
software, incluso comercialmente, pero **no** puedes dar a entender que tu
|
|
19
|
+
version derivada es ASILO oficial ni esta avalada por Kasai Labs.
|
|
20
|
+
|
|
21
|
+
--------------------------------------------------------------------------------
|
|
22
|
+
Metodologia
|
|
23
|
+
--------------------------------------------------------------------------------
|
|
24
|
+
|
|
25
|
+
Este repositorio es una implementacion de referencia. La metodologia ASILO en si
|
|
26
|
+
se documenta en el plano de planeacion (ver SOURCE.md) y no se licencia aqui.
|