This is the full developer documentation for SASY # SASY > Policy enforcement for AI agents. Every tool call is checked against your Datalog policy and the history that led to it, before it runs. Your agent records each message and tool result in a dependency graph, and asks the SASY engine about each proposed tool call before it runs; the engine allows it or returns the denial reason to the agent. For LangChain, Google ADK and Langroid, `sasy.instrument()` does this automatically. Any other agent makes the same two calls with SASY’s primitives: `sasy.record` for each message and `sasy.check_tool_call` before each tool runs. Policies can follow influence through summaries, tools and interactions between agents, so you can control information flow, require approvals and enforce business rules outside the model. [![SASY instrumentation connects an agent to its tools and services, records messages and dependencies in the engine's dependency graph, and checks proposed actions against developer policies. Allowed calls execute; denied calls return a reason to the agent.](/diagrams/architecture.svg)](/diagrams/architecture.svg) SASY instrumentation records inputs, checks actions with the policy engine, and dispatches allowed calls. The policy engine evaluates developer rules over the action and its relevant history. # System architecture > How the adapter, dependency graph, reference monitor, and policy engine work together. SASY runs alongside your agent. A **framework adapter** connects the agent to SASY: it records the inputs behind each message and checks actions before their tool handlers run. The engine evaluates your policy outside the model. [![SASY instrumentation connects an agent to its tools and services, records messages and dependencies in the engine's dependency graph, and checks proposed actions against developer policies. Allowed calls execute; denied calls return a reason to the agent.](/diagrams/architecture.svg)](/diagrams/architecture.svg) SASY instrumentation records inputs, checks actions with the policy engine, and dispatches allowed calls. The policy engine evaluates developer rules over the action and its relevant history. ## Record the inputs [Section titled “Record the inputs”](#record-the-inputs) The adapter records messages, tool results, and agent handoffs, together with edges to the messages each computation used. The **observability service** stores these records in the **dependency graph**. The policy engine maintains a view of that graph so it can follow an action’s inputs through earlier events. ## Check before execution [Section titled “Check before execution”](#check-before-execution) Before dispatching a tool, the adapter sends its name, arguments, and input message IDs to the **reference monitor**. The monitor asks the **policy engine** to evaluate the action against your Datalog rules and the relevant graph facts. An allow rule must match; a deny rule takes precedence. The decision returns to the adapter. If allowed, the adapter runs the tool and records its result. If denied, it skips the tool and returns the reason to the agent, which can choose another action. ## Where the pieces run [Section titled “Where the pieces run”](#where-the-pieces-run) The adapter runs in your application. The observability service, graph store, reference monitor, and policy engine ship together in `sasy serve`. The SDK connects your application to that process over authenticated gRPC. Start it [locally](/local-engine/) or connect to your deployed engine. The diagram shows framework tool calls. For HTTP forwarding, the reference monitor can also check and forward a request itself. See [add a framework](/instrumentation/) for the recording and dispatch contract, and [the security model](/limits/) for the trust assumptions. To see an actual policy decision unfold, explore the [animated dependency graph](/get-started/#see-the-decision). # Authentication and roles Authentication establishes who called SASY; roles determine which APIs that caller may use. The policy then decides whether a particular action is permitted. Keep these three decisions distinct. ## Local engine authentication [Section titled “Local engine authentication”](#local-engine-authentication) `sasy engine start` bootstraps an authenticated TLS engine through your local Docker access. It does not require an existing SASY key and does not disable authentication. It creates independent random API keys for `client` and `admin`, with tenant `default` and trust domain `sasy.local`. The client receives `reference-monitor-user`, `observability-writer`, and `observability-reader` roles; the separate admin identity also receives `admin`. The command stores only the client connection settings and CA certificate in a private profile under `~/.sasy/profiles/NAME/`. Server private keys and the admin credential remain in the Docker volume. The selected profile lets the Python SDK connect across project directories without copying keys into each project. Use `--env-file PATH` only when you want project dotenv settings as well. Use `--client-entity`, `--admin-entity`, `--tenant`, and `--trust-domain` on first initialization to choose identity settings. Restarting preserves credentials; conflicting identity requests are rejected. See [local engine](/local-engine/) and [launcher options](/cli/#local-engine-commands) for profiles and storage. An entity is an authenticated principal. Agent IDs and `sasy.session(entity=...)` label graph activity; they do not grant roles or change that principal. Applications sharing a profile share its client identity and tenant. Separate sessions distinguish executions within that identity, not security principals. Tenants are engine-controlled isolation scopes for graph, policy, and credential operations. Client-supplied labels cannot select a different tenant. Explicit SDK configuration takes precedence over environment variables, project `.env`, and the selected local profile. The profile’s key and CA are used only with its endpoint; setting another endpoint requires that server’s own credentials and TLS settings. See [client configuration](/configuration/#python-client-and-session-policy). ## Configure a server and its clients [Section titled “Configure a server and its clients”](#configure-a-server-and-its-clients) The Docker/profile launcher has a limited convenience surface. For a custom authentication provider or deployment, invoke the Rust engine directly. Set `SASY_BIN` to the path of your downloaded or built Rust executable; this avoids resolving to the Python SDK’s command, which does not implement `serve`: ```bash SASY_BIN=/path/to/engine/sasy "$SASY_BIN" serve \ --addr 127.0.0.1:10089 \ --auth-provider config/auth/apikey.json \ --auth-config config/auth_config.yaml \ --tls-cert certs/server.crt \ --tls-key certs/server.key \ --data-dir data/graph ``` `--auth-provider` selects a JSON authentication provider. `--auth-config` selects YAML mapping authenticated entities to roles and tenants. TLS authenticates the server to the client; an API key, bearer token, or verified client certificate authenticates the caller. See [CLI](/cli/) for full server options. These provider files and TLS options are not options of `sasy engine start`. ## API keys [Section titled “API keys”](#api-keys) For normal SDK use, generate a separate random API key for each principal — the identity the engine authenticates. Treat the value as opaque: the client sends it unchanged and the engine maps it to an entity name. Entity names, roles and tenants live in the engine’s configuration; they are never encoded in the key itself. The API-key provider’s JSON schema is: ```json { "type": "api_key", "metadata_key": "x-api-key", "static_keys": { "": "worker", "": "reviewer" } } ``` These placeholders are not credentials; replace each with an independent secret before loading the file with `--auth-provider`. Map `worker` and `reviewer` to their required roles and tenants in your `--auth-config` file. Store the provider configuration privately and give each client only its own key. Python sends the full key through an explicit hook: ```python import os import sasy from sasy.auth.hooks import APIKeyAuthHook sasy.configure( sasy_url=os.environ["SASY_URL"], ca_path="certs/server.crt", # Use your operator's CA for a remote engine. auth_hook=APIKeyAuthHook(api_key=os.environ["SASY_API_KEY"]), ) ``` `APIKeyAuthHook` sends the value verbatim. The TypeScript equivalent is `new ApiKeyAuthHook(key)`. Python also reads `SASY_API_KEY` from the environment or a `.env` file when no explicit hook is given; an explicit hook wins. Neither SDK builds a key out of an entity name, and neither falls back to a shipped demo key when no credential is configured. SASY’s credential-injection sources are separate from these client authentication keys. SQLite is suitable for local development; deployments can use environment-seeded memory or a read-only source in OpenBao, an open-source secrets server. Injection fails closed when the selected credential source errors. The application owns credential storage and rotation. ## JWT and OpenID Connect [Section titled “JWT and OpenID Connect”](#jwt-and-openid-connect) For OpenID Connect (OIDC), the identity layer on top of OAuth 2.0 that issues signed JSON Web Tokens (JWTs), copy `config/auth/jwt.example.json` to the ignored local `config/auth/jwt.json`, edit it with the provider’s exact JSON Web Key Set (JWKS) URL — where the provider publishes the public keys that verify its tokens — its issuer and the SASY audience, then start the engine with that file as `--auth-provider` and your `--auth-config` mapping. Obtain those URLs from your provider’s discovery document; the example domain is intentionally not usable. The JWT provider verifies signatures and configured issuer/audience. It reads the bearer token from `authorization`, resolves the entity from `sub` by default, and caches JWKS keys for the configured interval. A minimal JWKS provider configuration is: ```json { "type": "jwt", "metadata_key": "authorization", "jwks_url": "https://YOUR-OIDC-ISSUER/.well-known/jwks.json", "issuer": "https://YOUR-OIDC-ISSUER/", "audience": "sasy", "entity_claim": "sub", "roles_claim": "roles", "jwks_cache_seconds": 300, "use_central_roles": true } ``` Replace the issuer, audience and JWKS URL with your provider’s values. JWT verification also supports `hmac_secret` or `rsa_pem_file` as signing-key sources; use the key source appropriate to your issuer. Tenants always come from the engine’s entity mapping, even when roles come from JWT claims. For a token managed by your application, configure Python explicitly: ```python import os import sasy from sasy.auth.hooks import StaticTokenAuthHook sasy.configure( sasy_url=os.environ["SASY_URL"], ca_path=os.environ["TLS_CA_PATH"], auth_hook=StaticTokenAuthHook(token=os.environ["SASY_ACCESS_TOKEN"]), ) ``` The hook adds `Bearer `to the token. `OIDCAuthHook` obtains and refreshes a token from a configured `token_url` using client credentials. `BrowserAuthHook` and `DeviceAuthHook` support interactive provider flows. Configure the issuer’s client registration and grant settings before using those hooks; a local API-key profile does not supply OIDC credentials. SASY does not automatically translate an organization’s groups into its roles. Choose one approach: * With `use_central_roles: true`, map stable authenticated entity values in `config/auth_config.yaml` to SASY roles and tenants. A missing entity has no configured roles. Replace the local example entities with real subjects before enabling OIDC. * With `use_central_roles: false`, configure `roles_claim` to a claim issued by your trusted identity provider. Nested names are supported. That claim must already contain SASY role names; configure the provider’s group-to-role mapping yourself. Clients cannot assign themselves privileged roles. ## Role permissions [Section titled “Role permissions”](#role-permissions) | Role | Intended capability | | ------------------------ | --------------------------------------------------------------------------------------------------------------------- | | `observability-writer` | Register graph observations. | | `observability-reader` | Read observations within permitted scope. | | `reference-monitor-user` | Request action checks and bind permitted session policies. | | `admin` | Administrative policy operations and privileged exceptions. | | `service-proxy` | Lets one service present checks on behalf of another authenticated caller. Reserve it for infrastructure you operate. | Tenant-wide policy changes and privileged bypasses require the relevant authenticated and delegated identities to satisfy the server’s checks. Do not give every client `admin` or `service-proxy` to make a demo work. Serve remote clients over TLS and provision trust roots independently. The local example uses API keys over server-authenticated TLS; mTLS is a separate deployment choice. ## Mutual TLS identities [Section titled “Mutual TLS identities”](#mutual-tls-identities) In mutual TLS (mTLS) the client presents a certificate too, and the engine takes the caller’s identity from it. For certificate-based identity, use `{"type": "mtls"}` as the provider JSON and supply `--tls-cert`, `--tls-key`, and `--tls-ca` to the engine. The last file is the CA that may issue client certificates. The authenticated entity is the verified client certificate’s Common Name (CN); map that value to roles and a tenant in `--auth-config`. A caller-supplied identity header cannot replace the verified certificate identity. Configure Python with `ca_path` to trust the server and `cert_path`/`key_path` for its client certificate and private key. TypeScript uses `caPath`, `certPath`, and `keyPath`. API-key hooks are unnecessary when the selected provider is mTLS. Certificate issuance and access to private keys remain the operator’s responsibility. For example, a Python client using only mTLS can suppress token metadata while presenting its certificate: ```python import sasy from sasy.auth.hooks import NoAuthHook sasy.configure( sasy_url="engine.example:10089", ca_path="certs/server-ca.crt", cert_path="certs/client.crt", key_path="certs/client.key", auth_hook=NoAuthHook(), ) ``` `NoAuthHook` sends no token; authentication still occurs through the verified client certificate. It does not turn off the server’s authentication. ## Provider chains [Section titled “Provider chains”](#provider-chains) A `chain` provider tries its members in order and uses the identity, roles, and tenant from the first successful authentication. It is an alternative-provider composition, not a requirement that every provider authenticate: ```json { "type": "chain", "providers": [ {"type": "mtls"}, { "type": "api_key", "metadata_key": "x-api-key", "static_keys": {"": "worker"} } ] } ``` Configure the engine’s TLS trust for client certificates and its entity mappings for both providers. The TLS listener’s client-certificate requirement still applies before the authentication chain runs; adding an API-key member does not make client certificates optional on a listener configured to require them. If all providers fail, the request is unauthenticated. Do not add a passthrough provider to an authenticated deployment. ## Upgrading from sasy 0.4 [Section titled “Upgrading from sasy 0.4”](#upgrading-from-sasy-04) Older SDK code named a principal and let the client build its key. Replace `entity_api_key`, `entityApiKey`, `ApiKeyAuthHook.forEntity` and any entity-key constructor option with one key generated for that principal, and set `SASY_API_KEY` instead of the old suffix configuration. Neither SDK composes a key any more, and a client with no credential is simply unauthenticated. The engine still accepts the server-side `SASY_API_KEY_SUFFIX` setting so an existing deployment keeps working. Leave it unset on an engine configured with whole keys: a non-empty value is appended to every configured key, and the SDK does not append it, so the deployment has to hand each client the resulting complete key. That scheme cannot separate principals — anyone holding one key whose prefix is public can work out the suffix and construct the others — so move to independent keys and rotate the whole old family when you do. The engine refuses the key names shipped in the example files by default. # Build from source > Build SASY with Docker, Nix, or a manual toolchain. The [quick start](/get-started/) runs a prebuilt Docker image with `sasy engine start`. To build a modified engine, choose **Docker**, **Nix**, or a **manual toolchain**. **Nix** is the recommended way to build on your own machine: one command gives you the exact toolchain this repository pins, and on Linux it also builds an engine package whose policy compilation is sandboxed. A **manual toolchain** works too, if you install each tool yourself. ## Docker [Section titled “Docker”](#docker) Build from the source in this checkout, then serve the local image: ```bash make docker-build make docker-serve ``` The Docker build uses the engine package from `flake.nix` and `flake.lock`, including its pinned Soufflé, C++ compiler, Python, and runtime libraries. Nix runs inside a builder stage; you do not need Nix installed on the host. The final image contains the engine and its runtime dependencies and runs as a non-root user. Run the SDK and examples locally with uv. To run the local image with the SDK’s command instead, stop any running engine with `uv run sasy engine stop`, then run `uv run sasy engine start --image sasy`. To keep an engine running and connect an agent, follow [start a local engine](/local-engine/). The image sets `DISABLE_BWRAP=1` because ordinary Docker permissions do not provide the nested namespaces needed by Bubblewrap. Policy compilation relies on container isolation; compile only policies you trust. This setting applies only to the Docker image. The native Nix package keeps its sandbox enabled; see the Linux requirements below. ## Nix [Section titled “Nix”](#nix) Nix is the recommended way to build on your own machine. `flake.nix` and `flake.lock` pin the Rust, native, Python and JavaScript development tools. Install Nix separately, then enter the shell from the repository root: ```bash scripts/nix-dev.sh python3 scripts/nix-smoke.py ``` The launcher keeps an ignored profile under `.nix/` so Nix garbage collection cannot remove the shell’s policy compiler and headers. Keep that directory while using this checkout; remove it only after stopping its engines and shells. The smoke check compiles and runs Rust, loads libclang, processes a protobuf definition, and compares interpreted and compiled SASY policy decisions. It uses temporary files and does not start an engine. On Linux, build the engine and its runtime policy toolchain with: ```bash nix/build.sh ./result/bin/sasy --help ``` This package includes the engine’s default features, Soufflé and matching headers, the C++ compiler, Python, and the interpreted backend’s native assets. Use the installed `bin/sasy` launcher: it selects the packaged tools and assets, so policy compilation does not depend on the current source checkout. Build outputs and their dependencies remain in the Nix store. These are Nix packages, not portable standalone binaries or release wheels. The Linux launcher also selects a packaging-generated runtime manifest. This lists the Nix dependency paths that the policy sandbox may mount read-only and the tools it may execute. The engine validates the manifest and uses a controlled search path inside the sandbox. The interpreted evaluator receives the explicit directory of the selected policy’s functor library, preventing an unrelated installed library from taking precedence. Invalid configuration must fail rather than fall back to unsandboxed execution. The manifest is operator configuration; policy authors cannot supply extra filesystem paths through a policy upload. The manifest and selected store items must be root-owned and read-only. User-owned single-user Nix stores are not supported by this runtime integration. When Bubblewrap is installed and usable, policy compilation runs inside it. If it is absent, or `DISABLE_BWRAP=1` is set, compilation runs unconfined; if it is installed but cannot create namespaces, the engine refuses to compile rather than fall back. Bubblewrap is a Linux tool that runs a process in its own namespaces with a restricted view of the filesystem. Compilation is confined that way. The evaluator process can additionally run under a seccomp filter, the kernel facility that blocks system calls; the compile step does not use one. The host must permit Bubblewrap’s namespaces and mounts; container hosts can restrict those operations independently of SASY. Keep the sandbox enabled when testing a deployment: a toolchain check that ran outside the sandbox says nothing about whether the deployment can compile and evaluate policies safely. The launchers select their source inputs explicitly. `scripts/nix-dev.sh` stages the flake definitions needed for the development shell. `nix/build.sh` stages only the explicitly listed build inputs in `nix/source-files.json` and the packaging definitions. Local credentials and installed dependencies are excluded. Directly evaluating the entire checkout as a flake does not provide this source filtering. The development shell has Linux and macOS outputs for ARM64 and x86-64. The engine package builds on Linux only. A platform appearing in this list means the definition covers it, not that a build has been tested there; test the binary you intend to run. ## Manual toolchain [Section titled “Manual toolchain”](#manual-toolchain) The engine is a Rust application. Install Rust/Cargo, a C++ compiler, CMake, libclang, `protoc`, Python 3.11 or newer, and Soufflé with its development headers and `mcpp`. Local TLS setup also uses OpenSSL. The Python SDK uses uv; JavaScript SDK builds use Node/npm and SDK tests use Bun. Consult your platform’s packages for these dependencies. From the source repository with a manual toolchain, or inside the Nix shell on macOS: ```bash make build-rust # Optimized engine: target/full-release/release/sasy ``` To try the build, start it with `make init-config certs` followed by `make serve`, then run `uv run examples/message-flow/demo.py` in another terminal. The SDK setup is described in [start a local engine](/local-engine/#connect-your-agent-from-any-project). `make build-rust-dev` builds a faster-to-compile development binary at `target/debug/sasy`. `make serve` uses the optimized binary by default; to run the development build, set `SASY_BIN=target/debug/sasy`. Both builds use the committed Cargo lockfile. Override `SASY_RELEASE_TARGET_DIR` to choose another optimized build directory. `make build-rust-release` remains an alias for `make build-rust`. Raw Cargo builds and these make targets do not create the Nix runtime manifest. On Linux, entering the Nix shell alone does not make its store paths available inside the policy sandbox. Use `nix/build.sh` and the packaged `result/bin/sasy` launcher for Linux Nix operation, as described [above](#nix). The engine embeds its policy compiler source assets, but still invokes Soufflé, `mcpp`, and a C++ compiler when compiling new policies. Those tools and headers must be available on the machine running the engine. Match the Soufflé runtime and headers, including their `RamDomain` word size. Copying the executable alone does not install this toolchain. `mcpp` is the C preprocessor Soufflé runs over a policy before compiling it. Soufflé can be built with 32-bit or 64-bit values internally (its `RamDomain` word size); the headers on the machine must match the Soufflé binary, or a compiled policy will not load. ## Full and restricted engines [Section titled “Full and restricted engines”](#full-and-restricted-engines) `make build-rust` produces the **full engine**: it compiles and runs whatever policy a client binds. Everything in this documentation assumes it. A **restricted engine** is the same source built with the `SASY_POLICY_PACK` environment variable set to a directory of policies, which are compiled into the binary as its **baked profiles**. Such a build serves only those profiles; it cannot compile or load a policy sent at run time, and no command-line flag or environment variable at start-up changes that. This repository’s make targets do not build one. ## Configure a local instance [Section titled “Configure a local instance”](#configure-a-local-instance) Create the local configuration and TLS certificate before starting a native engine: ```bash make init-config certs ``` On Linux with Nix, enter `scripts/nix-dev.sh`, build with `nix/build.sh`, then start the packaged launcher explicitly: ```bash make serve SASY_BIN="$PWD/result/bin/sasy" ``` For a macOS Nix shell or a manual optimized build, use `make serve`. For a development build, use `make serve SASY_BIN=target/debug/sasy`. The native engine uses the same local configuration and TLS files, listens on `127.0.0.1:10089`, and stores the graph in `data/graph`. Leave it running and [configure your SDK terminal](/local-engine/#connect-your-agent-from-any-project). ## Preview the documentation [Section titled “Preview the documentation”](#preview-the-documentation) From the repository root, with Node.js 24 or newer: ```bash cd docs-site npm ci npm run dev ``` Open the local URL printed by Astro. For the production output, run `npm run build` and then `npx astro preview`. ## Checking your build [Section titled “Checking your build”](#checking-your-build) `make check-rust` compiles every workspace target without linking, and `make lint-rust` checks formatting and runs Clippy with warnings treated as errors. Neither runs tests. `tests/README.md` in the repository lists the test lanes, including the ones that compare the compiled and interpreted policy backends. For a deployment build, verify TLS, authentication, policy compilation, and an allowed and a denied action against the binary you will run. ## Release image verification [Section titled “Release image verification”](#release-image-verification) Release checks verify that the version tag resolves to the published image index and that it contains exactly the qualified AMD64 and ARM64 image digests. They then pull each platform digest anonymously with an empty Docker configuration. Using distinct platform digests avoids conflicts in Docker stores that cannot retain both platforms under a single index digest. These checks verify image access; they do not execute the images. If image publication succeeds but anonymous verification fails, the Python SDK release workflow can recover the existing release. Dispatch it from `main` with `recovery_run` set to the original release run ID. It requires successful original core, package and native-image checks, a successful image publication receipt, the unchanged version tag, and retained artifacts. It verifies the published image using the current checker, then publishes the original Python package artifacts through the `pypi` environment. It does not rebuild the engine or SDK, replace the image, or move the release tag. Expired artifacts or failed original qualification gates cannot be recovered this way. # Engine CLI > Local Docker engine launcher options and the core sasy serve command. ## Local engine commands [Section titled “Local engine commands”](#local-engine-commands) The Python SDK provides `sasy engine start`, `sasy engine status`, and `sasy engine stop`. These launch and manage a local Docker engine and saved client profiles. They are distinct from the Rust binary’s `sasy serve` command. See [local engine setup](/local-engine/) for the profile layout and examples. | `engine start` option | Default | Purpose | | ---------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `--profile NAME` | Selected profile, or `local` | Create/use a named profile under `~/.sasy/profiles/` and select it for SDK fallback. `SASY_ENGINE_PROFILE` also selects a profile. | | `--name NAME` | `sasy-engine` for `local`; `sasy-engine-PROFILE` otherwise | Docker container name; saved settings are reused on subsequent starts. | | `--port PORT` | `10089` initially | Host loopback port mapped to container port `10089`. | | `--volume NAME` | `CONTAINER-data` initially | Persistent Docker volume for engine credentials, certificates, and graph data. | | `--image IMAGE` | Saved image, otherwise `ghcr.io/sasy-labs/sasy:VERSION` | Override the image. For a new profile, `SASY_ENGINE_IMAGE` overrides the SDK-version default. | | `--timeout SECONDS` | `120` | Deadline for verified TLS readiness. | | `--env-file PATH` | No project file | Also write client settings to the chosen dotenv file; preserve existing values and report conflicts. | | `--client-entity NAME` | `client` on first initialization | Authenticated entity for the generated client key. | | `--admin-entity NAME` | `admin` on first initialization | Authenticated entity for the separate generated admin key. | | `--tenant NAME` | `default` on first initialization | Tenant assigned by the engine to the generated identities. | | `--trust-domain NAME` | `sasy.local` on first initialization | Trust-domain value in the generated role configuration. | Identity options initialize a new volume. Conflicting settings on an existing volume are rejected; they do not rotate keys or change roles. Profile files are private to your user, and the selected profile is available across project working directories. `engine status` and `engine stop` accept `--profile` and `--name` to choose the engine; stopping preserves its volume. The launcher does not configure arbitrary authentication providers or forward all server options. Use the Rust binary directly for JWT/JWKS, mTLS, provider chains, custom role mappings, and other deployment settings. Set `SASY_BIN` to the downloaded or built Rust executable, rather than the Python SDK command: ```bash SASY_BIN=/path/to/engine/sasy "$SASY_BIN" serve \ --addr 127.0.0.1:10089 \ --auth-provider config/auth/apikey.json \ --auth-config config/auth_config.yaml \ --tls-cert certs/server.crt \ --tls-key certs/server.key \ --data-dir data/graph ``` Use `--tls-ca certs/client-ca.crt` when verifying client certificates. See [authentication](/authentication/) and [configuration](/configuration/) for provider and SDK settings, and run `"$SASY_BIN" serve --help` for the installed binary. ## Engine server options [Section titled “Engine server options”](#engine-server-options) Run `sasy serve [OPTIONS]` to start the engine. This table covers every `sasy serve` option. `--policy` is an alias of `--policy-metadata`; they are not separate settings for logic and metadata. A flag cannot enable a backend your build left out, and a [restricted engine](/building/#full-and-restricted-engines) serves only its baked profiles. See [configuration](/configuration/) for startup examples, [authentication](/authentication/) for identities and TLS, [environment](/environment/) for process variables, and [build the engine](/building/) for backend and toolchain requirements. CLI values override the corresponding environment variables. | Flag | Default | Purpose | | --------------------------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--policy-metadata ` (alias `--policy`) | `unset` | One source-file option with two spellings. Soufflé backends compile/read this source and its annotations. With `--policy-plugin`, it supplies annotation metadata for that plugin instead. Restricted builds still serve only baked profiles. | | `--policy-plugin ` | `unset` | Trusted precompiled policy plugin (`.so`/`.dylib`); takes precedence over `--evaluator` in the full build and runs in the engine process. | | `--evaluator ` | `souffle` | `souffle`, `souffle-interpreted`, experimental external `flowlog`, or development `stub`. The stub backend allows actions; do not use it for enforcement. | | `--flowlog-bin ` | `unset` | Path to the external FlowLog evaluator IPC wrapper when selecting that backend. | | `--souffle-program ` | `policy_program` | Soufflé relation/program name answered by the evaluator. | | `--souffle-interpreted-bin ` | `souffle-interpreted` | Interpreted evaluator shim executable; required when selecting that backend. | | `--souffle-policy ` | `unset` | Policy `.dl` input for interpreted mode. | | `--souffle-functor-lib ` | `unset` | Explicit functor shared library for interpreted evaluation; otherwise the backend can compile its adapter library using the configured toolchain. | | `--auth-provider ` | `unset` | Authentication-provider JSON. Missing authentication refuses startup unless `SASY_ALLOW_NO_AUTH=1` explicitly enables local development without authentication. | | `--auth-config ` | `unset` | YAML mapping authenticated entities to roles and tenants. | | `--transforms ` | `unset` | JSON request-transform and credential-injection rules. | | `--addr ` | `127.0.0.1:10089` | gRPC listen address. | | `--proxy-port ` | `0` | Separate raw HTTP proxy port; `0` disables it. | | `--proxy-bind
` | `127.0.0.1` | Raw proxy bind address. This listener does not authenticate callers; restrict network access. | | `--proxy-tenant ` | `default` | Single tenant pinned to the raw proxy listener; this does not authenticate a caller. | | `--trust-proxy-headers` | `off` | Accept delegated `x-entity`/`x-roles` from authenticated callers without requiring their `service-proxy` role. Enable only behind a protected trusted proxy. | | `--tls-cert ` | `unset` | PEM server certificate; together with `--tls-key`, enables TLS. | | `--tls-key ` | `unset` | PEM server private key; pair with `--tls-cert`. | | `--tls-ca ` | `unset` | CA for verifying client certificates (mTLS). Configure the authentication provider to map those certificates to identities. | | `--data-dir ` | `data/graph` | Graph and engine state directory, resolved relative to the startup working directory. | | `--credential-backend ` | `sqlite` | `sqlite`, `memory`, or `openbao`. Memory seeds credentials from the environment and shares them across tenants. | | `--credentials-db ` | `/credentials.db` | SQLite credential database; other backends do not use this file. | | `--credentials-env-file ` | `unset` | Additional memory-backend credentials; file values override the environment. Other backends warn and ignore this option. | | `--openbao-addr ` | `unset` | Required OpenBao URL for the `openbao` backend; HTTPS unless loopback. | | `--openbao-mount ` | `secret` | OpenBao KV v2 mount. | | `--openbao-path-prefix ` | `sasy` | Lookup prefix; credential paths append tenant/entity/service. | | `--openbao-namespace ` | `unset` | OpenBao namespace header. | | `--openbao-token-file ` | `unset` | Token file; use this or the AppRole pair, not both. | | `--openbao-approle-role-id ` | `unset` | AppRole role identifier; pair with the secret-ID file. | | `--openbao-approle-secret-id-file ` | `unset` | AppRole secret-ID file. | | `--openbao-ca-cert ` | `unset` | PEM CA for a private OpenBao server certificate. | | `--openbao-cache-ttl-secs ` | `60` | Credential read-cache TTL in seconds. | | `--openbao-timeout-secs ` | `5` | OpenBao request timeout in seconds. | | `--query-timeout-secs ` | `10` | Fail-closed answer deadline in seconds; must be positive. The evaluator may finish in-flight work after a refused request. | | `--evaluator-stall-secs ` | `60` | Kill/restart threshold for an evaluator owing a reply; must be at least the query deadline. | | `--oracle-redaction ` | `on` | Scrub recognized secret shapes in oracle question/context strings. Does not redact stored graph data or the agent’s own model requests. | | `--neo4j-uri ` | `unset` | Enable the optional background graph mirror at this Neo4j URI. | | `--neo4j-username ` | `neo4j` | Neo4j mirror username. | | `--neo4j-password ` | `observability` | Neo4j mirror password; replace the development default when using a shared server. Command-line values can appear in process listings. | | `--neo4j-database ` | `neo4j` | Neo4j mirror database. | | `--allow-user-functors[=]` | `off` | Non-admin native functor admission: bare flag or `sandboxed` requires working confinement; `unsandboxed` explicitly permits unconfined development execution. Admin functors remain native code. | | `--help` | `—` | Print help; `-h` prints a shorter summary. | The raw proxy has a separate, limited HTTP contract described in [configuration](/configuration/#raw-forward-proxy). It does not inherit per-request gRPC authentication. An evaluator IPC failure immediately signals its process group and makes that channel unusable: later calls fail closed without another exchange. The engine retains the subprocess handle for cleanup, so a concurrent kill can await reaping even when the in-flight call discovers the failure first. Signalling the process group does not wait for the IPC mutex; awaiting the reap does. Other full-engine commands are `sasy init-credentials [--credentials-db FILE] [--env-file FILE]` to initialize/seed SQLite credentials, and `sasy install-assets DIR` to materialize the six embedded compile-chain assets. `init-credentials` defaults to `data/graph/credentials.db`, the file `serve` uses with its default `--data-dir`; see [building](/building/) before selecting an asset override. `install-assets` requires a compiler-enabled build. # Concepts > The terms used throughout this documentation, defined once. Every page here uses the words below in exactly this sense. ## Messages and the graph [Section titled “Messages and the graph”](#messages-and-the-graph) **Message**, **record**, **dependency**, **ancestry**, **evidence of a successful tool result** and **message version** are defined, with an example, on [the dependency graph](/dependency-graph/). In one line: a message is a node, a dependency says one message was computed from another, and a message’s ancestry is everything it was computed from. In a policy, `CurrentDepends(id)` is the ancestry of the action being checked. ## Decisions [Section titled “Decisions”](#decisions) **Action.** Something the agent is about to do: call a tool, send an HTTP request. **Check.** Before an action runs, the application asks the engine “may I do this?”, naming the action, its arguments and the IDs of the messages the action was computed from (its **input IDs**). **Policy.** A file of Datalog rules that answers a check. **Datalog** is a small logic language: a rule says “this fact holds if these other facts hold”. Your rules derive `IsAuthorized` (this action may run) and `Unauthorized` (it may not). Nothing is allowed unless a rule allows it, and `Unauthorized` always wins. The engine compiles policies with **Soufflé**, a Datalog compiler. The Docker image includes it; a natively built engine needs it installed. See [policy language](/policy-language/). **Reference monitor.** The part of the engine that answers checks. Everything that is checked goes through it. The word “engine” means the whole `sasy serve` process, which also records messages and stores the graph. **Decision.** Allow, deny (with a reason and an optional suggestion), or ask (the action needs a human approval, where your application offers one). **Dispatch site.** The line of your code that actually runs the tool. A check protects an action only if it sits immediately before that line. **Transform.** A policy-directed rewrite of an outgoing request, used to inject a credential the agent never sees. In the Python SDK, transforms are applied to HTTP requests, which reach the engine only when the [HTTP hooks](#integrating) are on (`sasy.instrument(http=True)`). If a decision requires a transform the adapter cannot apply, the action does not run. ## Scope and identity [Section titled “Scope and identity”](#scope-and-identity) **Session.** One conversation: its own graph and one bound policy. A new conversation is a new session. **Tenant.** One isolated customer or environment. Sessions and the default policy for new sessions belong to a tenant. **Principal.** Who the engine authenticated, derived from the API key, the JWT subject or the mutual-TLS certificate. It cannot be forged over the wire, so accountability rules use it. **Entity.** A free-form label the application attaches to a request, for example an end-user name relayed by a gateway. It is not authenticated: any caller can send any string, so do not authorize on `Entity` alone. **Agent.** A conversation role label on a recorded message, such as `"reviewer"`. Like `Entity`, it is supplied by the application. **Role.** A name bound to a principal in the engine’s role configuration, read in a policy with `HasRole("...")`. See [authentication](/authentication/). ## Integrating [Section titled “Integrating”](#integrating) **Adapter.** Code that records messages and places checks for one framework. Written once per framework and reused by every agent built on it. The SDK calls enabling one “instrumenting” the framework, as in `sasy.instrument()`. **HTTP hooks.** Patches for the `httpx` and `requests` Python libraries that send outbound HTTP requests through the same check, and let the reference monitor inject credentials (add an API key the engine holds to a request). They are separate from the framework adapters and off by default; `sasy.instrument(http=True)` enables them. **Unattributed external input.** A message whose origin the adapter cannot verify. Adapters expose markers for supported message handoffs so a policy can treat them conservatively. Copying just the text into a new user message can lose its origin; the framework guides explain how to preserve message identity. **Taint.** Informal name for a policy pattern: derive a fact when the ancestry contains something undesirable, then deny actions while that fact holds. Ancestry does not cross session boundaries, and missing ancestry does not establish that an input is safe. Preserve message objects when forwarding results and handle unknown origins using your adapter’s policy-visible marker; see [LangChain](/integrations/langchain/#inputs-of-unknown-origin) and [ADK](/integrations/google-adk/#values-from-another-sasy-session). # Configuration > Configure the engine, identities, clients, and policies. Engine options, identity mappings, client settings and policy facts serve different purposes. Changing one does not automatically change the others: a working connection does not grant an action permission, and a policy role check does not configure who receives that role. ## Local profiles [Section titled “Local profiles”](#local-profiles) `sasy engine start` saves a client profile in `~/.sasy/profiles/NAME/` and selects it for Python SDK use across projects. It runs a local authenticated TLS engine in Docker; its credentials and graph storage persist in a Docker volume. See [local engine setup](/local-engine/) for named profiles and optional project `.env` output, and [CLI options](/cli/#local-engine-commands) for the launcher settings. Use the Rust binary’s `sasy serve` command below when you need custom provider configuration or other server options beyond the Docker launcher. ## Engine process [Section titled “Engine process”](#engine-process) Prepare the engine binary, certificates and local files using [building and local setup](/building/). Configure an independent full API key for each principal as described in [authentication](/authentication/); the example below assumes `config/auth/apikey.json` contains those literal keys. Start the engine explicitly: ```bash target/full-release/release/sasy serve \ --addr 127.0.0.1:10089 \ --auth-provider config/auth/apikey.json \ --auth-config config/auth_config.yaml \ --transforms config/transforms.json \ --tls-cert certs/server.crt \ --tls-key certs/server.key \ --data-dir data/graph ``` The credential store lives at `/credentials.db` unless `--credentials-db` says otherwise. Keep suffix composition disabled on the server when using literal keys. Paths are relative to the process’s working directory. Use a persistent data directory if policy bindings and observations must survive restarts. | Setting | Purpose and direct CLI default | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `--addr` | gRPC listener; `127.0.0.1:10089`. | | `--data-dir` | Graph and engine state; `data/graph`. | | `--auth-provider` | Provider JSON file; no implicit authenticated provider. Startup refuses missing authentication unless local no-auth mode is explicitly enabled. | | `--auth-config` | Entity-to-role and tenant mappings in YAML. | | `--tls-cert`, `--tls-key` | Enable server TLS; not automatically enabled by bare `sasy serve`. | | `--tls-ca` | Trust root for verifying client certificates when using mTLS. | | `--evaluator` | Policy backend; `souffle`. | | `--query-timeout-secs` | Query deadline; `10`. An evaluation that runs past it denies the action. | | `--evaluator-stall-secs` | Unresponsive evaluator recovery threshold; `60`, and must be at least the query deadline. | | `--proxy-port` | Separate HTTP forward proxy; `0` disables it. | `--policy-metadata` and `--policy` are aliases for the same source-file option. The engine compiles that source for the Soufflé backends and reads its annotations; they are not separate inputs for logic and metadata. See [engine environment](/environment/) for runtime variables and [engine CLI](/cli/) for every `sasy serve` option. A [restricted engine](/building/#full-and-restricted-engines) runs only its baked profiles: neither `--evaluator` nor a source file gives it the ability to compile a policy. The forward proxy is a separate, unauthenticated-per-request listener; enabling it requires deliberate network and tenant configuration. ### Raw forward proxy [Section titled “Raw forward proxy”](#raw-forward-proxy) The raw HTTP forward proxy does **not authenticate callers**. Anyone who can reach its listener can use the configured tenant’s stored credentials against hosts allowed by policy. Keep the loopback default (`--proxy-bind 127.0.0.1`), or isolate access at the network boundary; `--proxy-tenant` pins one tenant per listener, not a caller identity. Raw requests have no input-message ancestry. For plain HTTP forwarding, the raw proxy returns the upstream status and body but drops upstream response headers, including content type, cookies and cache controls. It is not a transparent general-purpose HTTP proxy. CONNECT relays encrypted bytes without credential injection or inspection of inner requests. These limitations concern the separate raw listener, not the authenticated gRPC `ProxyHTTP` API. ## Identity and roles [Section titled “Identity and roles”](#identity-and-roles) The provider file maps each full key to its authenticated identity, such as `worker`. The role file then describes what that identity may do: ```yaml default_tenant: default entities: worker: tenant: default roles: - reference-monitor-user - observability-writer - observability-reader ``` Use the provider’s authenticated identity value as the entity key. A missing mapping has no configured roles; omitting an entity’s tenant uses `default_tenant`. Role names such as `reference-monitor-user` authorize service APIs. A policy can impose additional action-specific requirements with `HasRole(...)`. JWT claim mapping and mTLS identity configuration are described in [authentication](/authentication/). Credential sources and `--transforms` configure secrets used for approved request transforms; they do not replace caller authentication. ## Python client and session policy [Section titled “Python client and session policy”](#python-client-and-session-policy) Configure the SDK endpoint and trust explicitly. Set `SASY_API_KEY` to the key issued to this client. This example connects to the engine above: ```python from pathlib import Path import os import sasy from sasy.auth.hooks import APIKeyAuthHook sasy.configure( sasy_url="localhost:10089", ca_path="certs/server.crt", auth_hook=APIKeyAuthHook(api_key=os.environ["SASY_API_KEY"]), ) with sasy.session(policy=Path("read-only.dl")): # Record context and check actions through the instrumentation APIs. pass ``` A `Path` loads a policy file; a plain string is interpreted as policy source. Omitting `policy` does not replace an existing session binding; a session without its own binding uses the tenant default. A session’s policy binding and its recorded graph are separate from the SDK’s connection settings. Supply `policy_metadata=[("setting", "value", "")]` alongside `policy=` when entering the session to provide policy configuration facts; those facts matter only if the policy reads them. `ActionMetadata` instead belongs to a particular proposed action. By default, leaving `sasy.session(...)` calls `EndSession`: it releases the evaluator, policy binding, session metadata and ownership while keeping recorded graph observations. Use `end_on_exit=False` when deliberately continuing a session across blocks, and end it explicitly when finished. Use a new session ID for a new conversation. Python teardown is best-effort, so a failed teardown may leave server state in place. Calling `sasy.configure()` with no arguments is optional. Python connection settings use this order: 1. Explicit `sasy.configure(...)` or client constructor arguments. 2. Exported environment variables. 3. `.env` in the current working directory. 4. The selected local-engine profile, only when no higher-priority endpoint is set. `SASY_URL` sets the endpoint. `SASY_API_KEY` supplies the full client key; `TLS_CA_PATH` supplies the CA that signs the server certificate. For mutual TLS, use `TLS_CERT_PATH` and `TLS_KEY_PATH` for the client certificate and private key. An explicit `auth_hook` overrides automatic API-key selection. The local profile is a connection bundle: its URL, client key, and CA belong together. If you set a different endpoint, the SDK does not borrow credentials or TLS settings from that profile. Configure the endpoint’s own trust and identity. `SASY_ENGINE_PROFILE` selects a named profile for one process; otherwise `~/.sasy/selected-profile` chooses it. A requested missing profile is an error. If no profile or endpoint is configured, the SDK still has no default server and raises `SasyEndpointNotConfigured` when a connection is needed. A profile’s client identity is shared by all applications using its key. `sasy.session(entity=...)` and instrumentation agent IDs are labels for recorded activity; they do not change the authenticated principal, tenant, or roles. ## Session lifetime and background work [Section titled “Session lifetime and background work”](#session-lifetime-and-background-work) Installing hooks with `sasy.instrument()` does not activate a session. By default, automatic hooks pass through unchanged outside `sasy.session(...)`; manual recording and authorization APIs require an active session and raise otherwise. To opt into a process-wide default: ```python sasy.configure(process_global_session=True) sasy.instrument() ``` This creates a generated session ID shared by otherwise unscoped work in the process. An explicit `sasy.session(...)` overrides it. The default uses the tenant’s default policy; it is distinct from the tenant-global graph selected by `sasy.global_session()`. Passing `process_global_session=False` disables it; omitting the option preserves its current setting. Async tasks inherit the context in which they are created, including the SASY session. Await all protected work before leaving the session: the default `end_on_exit=True` closes its shared lifetime, and inherited work then raises instead of running without checks or falling back to the process default. Use `end_on_exit=False` only when deliberately keeping that session open. Ending it later, through another block or `end_session(id)` from `sasy.policy`, also revokes contexts inherited from its earlier blocks. `asyncio.to_thread()` also copies the context. A raw thread pool does not: use a separate `contextvars.copy_context()` for each submitted worker, or enter a session in the worker. Likewise, awaiting a task created outside the session does not give it the awaiting task’s session. Without propagated context or a process default, automatic hooks in that worker are inactive. ## Python instrumentation [Section titled “Python instrumentation”](#python-instrumentation) `sasy.configure(...)` sets connection and instrumentation options when you need explicit values; it does not install framework hooks. `sasy.instrument()` does, and is called once at startup, after any explicit `sasy.configure(...)` and before any agent is built: * With no arguments, it registers import hooks for each supported framework that is installed ([LangChain](/integrations/langchain/), [Google ADK](/integrations/google-adk/) and [Langroid](/integrations/langroid/)). Unimported frameworks and their adapters remain unloaded until a framework import triggers installation; frameworks already imported are installed immediately. LangGraph applications are detected through its concrete graph modules because its root package is a namespace. `make install` and `uv add sasy` install none of the frameworks; `sasy[all]` installs all three and OpenTelemetry, or choose one framework’s extra. * `langchain=`, `adk=` and `langroid=` each take `True` (require the framework: validate and install immediately, with an error if it is not installed) or `False` (skip it). Left out, an installed framework its adapter cannot be used with (LangChain or ADK at a version SASY does not support, or a framework the adapter cannot import) is skipped: its agents will NOT be checked by SASY, and the first time the application uses that framework a `SasyInstrumentationWarning` says so (once per process; an application that never uses it gets no warning). With `True` the same problem is an error; with `False` the framework is skipped silently and pending import hooks are cancelled. Existing patches cannot be removed. Complete instrumentation on the startup thread before starting workers: import the frameworks there, or use `True` to install eagerly. Concurrent framework imports while an adapter is pending are unsupported. A deferred hook triggered on a different thread raises an error, but this is not a barrier around Python’s module cache; do not start workers during framework imports. An error during deferred installation surfaces during the triggering import; do not continue using that framework after an installation error. See [supplied Python adapters](/instrumentation/#supplied-python-adapters). * `http=` controls the [HTTP hooks](/instrumentation/#http-hooks), which are off by default. Pass `http=True` when you need credential injection or want the policy to check the agent’s `httpx` and `requests` calls; the policy must then allow each host the agent calls, including the model provider’s. * `sasy.instrument(http=True, langchain=False, adk=False, langroid=False)` enables only the HTTP hooks. Use this with your own adapter. Use [add a framework](/instrumentation/) to cover your own orchestration and dispatch paths. Keep `tool_policy_fail_closed=True`, the default, so Langroid tool handlers stop when the reference monitor is unavailable. Setting it to `False` allows those calls to proceed on check errors and is unsuitable for enforcement. An explicit policy denial still blocks the tool. `log_policy_decisions=True` enables decision logging; `log_transforms=True` includes applied transforms. `otel_enabled` and `otel_service_name` control OpenTelemetry tracing. These observability options do not grant permission or replace checks at dispatch. # The dependency graph > What SASY records about a conversation, and why a decision follows what a call was computed from rather than what happened earlier. SASY decides about an action from the messages that action was computed from. This page explains what is recorded, how a rule reads it, and why the order of a conversation is not a substitute. ## What is recorded [Section titled “What is recorded”](#what-is-recorded) **Message.** Anything your application records: a user input, a model output, a tool result. Each recorded message is a **node** in the session’s **graph** and has an ID the engine assigns. **Record** means to send a message, or a dependency between messages, to the engine so a policy can see it. The SDK functions are `record_events`, `resolve_events` and their async variants; an adapter for your framework calls them for you. **Dependency (edge).** A recorded statement that the computation producing message B consumed message A: “B depends on A”. It captures possible influence; it does not claim which words the model used. A model output depends on every message in the request the model was given. A tool result depends on the model output that asked for the tool. **Ancestry.** Everything a message was computed from, directly or through other messages: the whole chain backwards. *Provenance* means the same thing; this site says ancestry. **Evidence of a successful tool result.** A `ToolResult` fact. The engine has one only for a tool that actually ran and returned without raising an error, so a rule that requires `ToolResult(id, "approve", _)` cannot be satisfied by a call that was denied, failed or was merely proposed. **Message version.** Re-recording an unchanged message returns the same ID and stores nothing new. Editing it produces a new node. This matters to adapter authors; see [add a framework](/instrumentation/). ## How a decision uses the graph [Section titled “How a decision uses the graph”](#how-a-decision-uses-the-graph) Before an action runs, the application asks the engine “may I do this?”, naming the action, its arguments and the IDs of the messages the action was computed from. In a policy those IDs are `Current(id)`, and `CurrentDepends(id)` is every message they depend on, directly or indirectly: the ancestry of the call. An agent has four tools: `read_public`, `read_confidential`, `draft_summary` and `publish`. ```text Run A read_public → draft_summary → publish(external) ALLOW Run B read_confidential → draft_summary → publish(external) DENY "External publication depends on confidential information" Run B' read_confidential → draft_summary → publish(internal) ALLOW ``` In run B the draft no longer contains the confidential wording. The policy still restricts publication of outputs derived from confidential context. SASY denies it because the `publish` call depends on the draft, the draft depends on the model output that read the confidential document, and the policy says: ```prolog ConfidentialInput() :- CurrentDepends(id), ToolResult(id, "read_confidential", _). // @deny_message: External publication depends on confidential information Unauthorized(idx) :- Actions(idx, a), IsTool(a, "publish"), a = $CallTool(_, args), @json_get_str(args, "destination") = "external", ConfidentialInput(). ``` This is [examples/langchain-information-flow](https://github.com/sasy-labs/sasy/tree/main/examples/langchain-information-flow): a real LangChain agent with a scripted model, so it needs no provider key. ## Why not the order of the conversation [Section titled “Why not the order of the conversation”](#why-not-the-order-of-the-conversation) A conversation looks like a list: first this message, then that one. It is tempting to write rules over that list, such as “deny `publish` if a confidential read happened earlier in the session”. But “earlier” is not “computed from”. The messages of a session are only partly ordered: some depend on each other, and many do not, even though one was recorded before the other. ```text ┌─ calendar agent: check slots → create event ─┐ user → supervisor ───┤ ├─ supervisor: answer └─ email agent: read confidential → send ────┘ ``` The two sub-agents run side by side. The calendar agent’s `create event` was recorded after the email agent’s confidential read, but it was not computed from it. The same happens without any parallelism: a second task started in the same session, from a new user message, depends on nothing from the first. What counts is always what a message was computed from, all the way back. A model call that is given only the last three messages depends on those three and on everything they were computed from, so trimming a conversation does not shed an earlier confidential read that those messages descend from. A rule over session order gets this wrong in both directions. * **It blocks what it should allow.** Once anything confidential has been read, every later external action in the session is denied, including ones that never saw it. People respond by weakening the rule. * **It can accept unrelated evidence.** An approval elsewhere in the session may concern a different payment. Require an approval in this action’s ancestry **and** match the request ID, payee, and amount. Ancestry alone is insufficient: an earlier approval can also be an ancestor of a later, different payment. The [ADK example](/integrations/google-adk/#payment-example) shows the matching rule. Use ancestry when permission depends on the inputs behind an action. Other rules, such as role checks and global tool restrictions, can apply independently of ancestry. A list of allowed tools fails for the same reason a session-order rule does: it cannot tell two runs apart. | | Tool allowlist | Rule over ancestry | | --------------------------------------------------------- | ----------------------------------------------- | ------------------------------------------------ | | Is `publish` an allowed tool? | yes | yes | | `publish(external)` after reading only public documents | allow | allow | | `publish(external)` after reading the confidential report | allow: the allowlist cannot tell the runs apart | deny: the call depends on `read_confidential` | | the same, after a drafting step rewrote the text | allow | deny: ancestry survives the rewrite | | a parallel branch that never saw the report | allow | allow: the report is not in that call’s ancestry | | what the model believed | irrelevant | irrelevant: the check happens outside the model | The policy controls the proposed action before its handler runs. See the [security model](/limits/) for model-provider and deployment boundaries. ## What the graph cannot know [Section titled “What the graph cannot know”](#what-the-graph-cannot-know) A rule over ancestry is only as complete as the recorded graph. * **Code that reads something without recording it.** A tool that reads a file, a database or a global variable has consumed an input the graph does not show. Record it, or keep such reads inside a tool whose result is recorded. * **Text carried by hand.** Copying an answer’s text into a new user message creates a message with no ancestors. The framework guides say how to carry messages so they keep their identity. * **Session boundaries.** Each session has its own graph. Preserved message objects carried into another session can be marked as **unattributed external inputs**, with no verified ancestry or successful-tool evidence. Copying only their text can lose that origin. Follow the adapter’s rules for forwarding messages and recognizing its marker: [LangChain](/integrations/langchain/#inputs-of-unknown-origin) and [ADK](/integrations/google-adk/#values-from-another-sasy-session). An adapter records the messages and dependencies of its framework for you and places the checks; see [LangChain](/integrations/langchain/), [Google ADK](/integrations/google-adk/) and [Langroid](/integrations/langroid/). For your own orchestration code, [add a framework](/instrumentation/) lists what to record and where to check. The remaining terms are on the [concepts page](/concepts/). # Engine environment > Runtime, development and build variables understood by the core Rust engine. This is the `SASY_*` inventory for the core Rust `sasy` binary and its policy runtime. These are process settings, not policy facts. Explicit CLI values take precedence where a variable has a corresponding flag. A variable for an unavailable backend or build feature does not enable that feature. Use `sasy serve --help` for flags; see [configuration](/configuration/) for complete startup examples. SDK variables such as `SASY_URL` and `SASY_API_KEY`, and Make variables such as `SASY_BIN` configure their respective clients or launchers; the core engine does not read them as listener or authentication configuration. The server needs `--auth-provider` even when a client API key is in its environment. ## Authentication and credential sources [Section titled “Authentication and credential sources”](#authentication-and-credential-sources) | Variable | Default | Meaning | | --------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SASY_ALLOW_NO_AUTH` | off | Explicitly allow startup without an authentication provider for local development. This removes caller authentication; use a configured provider for any shared deployment. | | `SASY_API_KEY_SUFFIX` | unset | Legacy server compatibility: append `-` to every configured static key. Leave unset when provisioning independent full keys. SDKs accept full keys and do not compose suffixes. | | `SASY_ALLOW_DEFAULT_KEYS` | off | Local development override accepting the repository’s known example keys verbatim. Replace example keys instead for shared deployments. | | `SASY_CREDENTIAL_BACKEND` | `sqlite` | `--credential-backend`: `sqlite`, `memory`, or `openbao`. The memory backend shares its seeded credentials across tenants. | | `SASY_CREDENTIALS_ENV_FILE` | unset | `--credentials-env-file`: additional credentials for the memory backend; file entries override the process environment. Other backends warn and ignore this option. | | `SASY_CREDENTIAL__` | unset | Seed a credential for the memory backend, or from an env file passed to `init-credentials`. Split at the first underscore after the prefix; service and key become lowercase. These wildcard-entity credentials are available to all authenticated entities in the backend’s scope. | The default-off boolean switches above accept `1`, `true`, `yes`, or `on` (case-insensitive, whitespace trimmed). They do not provision credentials. Standard provider variables `OPENAI_API_KEY`, `OPENFDA_API_KEY`, and `BRAVE_API_KEY` also seed the credential sources. OpenBao uses the `OPENBAO_*` counterparts of its CLI flags; see `sasy serve --help`. ## Evaluation and session lifetime [Section titled “Evaluation and session lifetime”](#evaluation-and-session-lifetime) | Variable | Default | Meaning | | ----------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `SASY_QUERY_TIMEOUT_SECS` | `10` | `--query-timeout-secs`: fail-closed answer deadline. The evaluator can finish its in-flight operation after the request is refused. | | `SASY_EVALUATOR_STALL_SECS` | `60` | `--evaluator-stall-secs`: kill and replace an evaluator that owes a reply beyond this interval. Must be at least the query deadline. | | `SASY_SESSION_IDLE_TTL_SECS` | `1800` | Idle evaluator lifetime; `0` disables idle eviction. Recorded graph state survives eviction. | | `SASY_SESSION_SWEEP_INTERVAL_SECS` | `60` | Interval between session and policy-orphan sweeps; `0` disables both. | | `SASY_POLICY_VARIANT_IDLE_TTL_SECS` | `3600` | Idle lifetime of unreferenced policy variants; `0` disables orphan sweeping. | | `SASY_MAX_LIVE_SESSIONS` | unbounded | Positive cap on live per-session evaluators. Evicts the least recently active evaluator when needed; `0` also means unbounded. This is not a durable graph-storage quota. | | `SASY_REPLAY_EAGER` | off | Compile persisted policies eagerly on startup instead of loading them on demand. Accepts the default-off boolean spellings above. | | `SASY_ORACLE_REDACTION` | `on` | `--oracle-redaction`: `on` or `off` scrubbing of recognized secret shapes in oracle question/context strings. Does not redact the graph or the agent’s own model requests. Unrecognized values leave redaction on. | ## Compilation and confinement [Section titled “Compilation and confinement”](#compilation-and-confinement) | Variable | Default | Meaning | | --------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SASY_COMPILE_TIMEOUT_SECS` | `300` | Timeout for each external compiler/preprocessor step; bounds hung toolchain processes. | | `SASY_SOUFFLE_ASSETS` | embedded assets | Directory containing all six assets emitted by `sasy install-assets`. Missing assets are refused. | | `SASY_SOUFFLE_INCLUDE` | detected headers | Directory containing `souffle/SouffleInterface.h`. | | `SASY_SOUFFLE_BUILD_CACHE_DIR` | `/souffle-build-cache` | Compiled evaluator cache. Empty, `off`, `false`, or `0` disables caching. Relative paths use the process working directory. | | `SASY_SOUFFLE_BUILD_CACHE_MAX_BYTES` | `1073741824` (1 GiB) | Positive cache byte budget. Zero or invalid values use the default. | | `SASY_SOUFFLE_BUILD_CACHE_MAX_AGE_DAYS` | `30` | Prune unused cache entries by age; `0` disables age pruning while preserving the byte budget. | | `SASY_SOUFFLE_BUILD_CACHE_PER_TENANT` | off | Experimental tenant cache-key switch. The current runtime compilation path does not supply a tenant key, so enabling this emits a warning and leaves the cache shared. Do not rely on it for tenant isolation. | | `SASY_SOUFFLE_MAGIC_SET` | unset | Relation names forwarded to Soufflé’s magic-set option, a Datalog optimization that rewrites rules to compute only the facts a query needs. Changes compiled cache identity; leave unset unless qualifying the resulting policy behavior. | | `SASY_ALLOW_USER_FUNCTORS` | off | `--allow-user-functors`: admit non-admin native functors with `sandboxed` (or `1`/`true`/`yes`/`on`) only when required sandbox support works. `unsandboxed` is an explicit development escape hatch. Custom C++ is native code. | | `SASY_EVALUATOR_BWRAP` | enabled where supported | Set exactly `0` to disable evaluator bubblewrap confinement. This prevents sandbox-required non-admin functor admission. | | `SASY_SECCOMP_PRE_EXEC_DISABLE` | unset | Set exactly `1` to disable the Linux pre-exec seccomp layer for debugging. This prevents sandbox-required non-admin functor admission and removes constructor-time protection. | | `SASY_NIX_RUNTIME_MANIFEST` | unset | Nix launcher-supplied immutable runtime closure/tool manifest. Validates and confines compilation to the packaged toolchain. Use the package launcher instead of constructing this setting by hand. | `DISABLE_BWRAP=1` is the non-prefixed, host-wide development switch for bubblewrap; it also affects compilation. A host that cannot provide the required sandbox must refuse sandbox-required uploads. A [restricted engine](/building/#full-and-restricted-engines) serves only its baked profiles and does not gain the ability to compile a policy through these variables. The Nix package supplies the toolchain and manifest described in [build the engine](/building/). ## Experimental diagnostics [Section titled “Experimental diagnostics”](#experimental-diagnostics) | Variable | Default | Meaning | | ------------------------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `SASY_FLUSH_INTERVAL_US` | `1000` | Evaluator update coalescing interval in microseconds; `0` disables the timer delay. | | `SASY_KEEPALIVE_INTERVAL_MS` | `0` | Experimental empty-update keepalive interval; `0` disables it. Intended for performance investigation. | | `SASY_SERVER_LATENCY_LOG_FILE` | unset | Append request timing and session identifiers as JSONL. A failed file open disables logging. Protect the output as operational data. | ## Build-only and internal controls [Section titled “Build-only and internal controls”](#build-only-and-internal-controls) | Variable | Scope | | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SASY_POLICY_PACK` | Build-time directory consumed by Cargo for a restricted engine’s baked policy pack. Changing it when starting an installed binary cannot change its profiles. | | `SASY_ASSURED_MODE` | Exact value `1` makes the engine refuse to start unless every external tool it runs is named by an absolute path and matches a SHA-256 pin, given in the `SASY_TOOL_*` variables below. It pins tools; it is not a general security switch and produces no attestation. | | `SASY_TOOL_PYTHON3_PATH`, `SASY_TOOL_PYTHON3_SHA256`, `SASY_TOOL_SOUFFLE_PATH`, `SASY_TOOL_SOUFFLE_SHA256`, `SASY_TOOL_CXX_PATH`, `SASY_TOOL_CXX_SHA256` | The absolute paths and lowercase SHA-256 pins that `SASY_ASSURED_MODE=1` requires. Ordinary startup ignores these and resolves its tools from the Nix manifest or `PATH`. | | `SASY_SKIP_IN_PROC_SANDBOX`, `SASY_SECCOMP_PRE_EXEC` | Internal markers the engine passes to a child process it has already confined. Setting them yourself claims a protection that was never installed. | Test-only subprocess markers and `SASY_TEST_SKIP_INTERPRETED` are test harness controls, not supported deployment settings. Other libraries use their own variables, including logging (`RUST_LOG`), the model and provider settings for the optional LLM-backed policy predicate (`LLM_*`), and optional graph mirrors; consult the corresponding component documentation before enabling them. # Examples > Run policies on LangChain, Google ADK, and Langroid agents. These examples use real framework execution and SASY enforcement, with scripted models and simulated effects. No model-provider key is required. With the [quick-start engine](/get-started/) running, run the commands below from the repository root in another terminal. ## LangChain: information flow [Section titled “LangChain: information flow”](#langchain-information-flow) An agent reads a document, passes it through a drafting tool, and asks a publication tool to send the rewritten draft to an internal or external destination. Policy Allow internal publication. Allow external publication only when no confidential information influenced it. Datalog excerpt ```prolog .decl ConfidentialInput() ConfidentialInput() :- CurrentDepends(id), ToolResult(id, "read_confidential", _). Unauthorized(idx) :- Actions(idx, a), IsTool(a, "publish"), a = $CallTool(_, args), @json_get_str(args, "destination") = "external", ConfidentialInput(). ``` `CurrentDepends` follows the inputs behind the publication request. The [full policy](https://github.com/sasy-labs/sasy/blob/main/examples/langchain-information-flow/policy.dl) also defines the allowed actions. ```bash # Denied: confidential input, external destination uv run examples/langchain-information-flow/demo.py # Allowed: keep confidential input internal uv run examples/langchain-information-flow/demo.py --destination internal # Allowed: publish a summary based only on public input uv run examples/langchain-information-flow/demo.py --public ``` The default run is denied before the publication handler runs, leaving `simulated_deliveries` empty. The internal and public-input runs each make one simulated delivery. The [LangChain guide](/integrations/langchain/#information-flow-example) explains the policy and includes a [supervisor with parallel workers](/integrations/langchain/#run-a-supervisor-with-parallel-workers). See the [example README](https://github.com/sasy-labs/sasy/tree/main/examples/langchain-information-flow) for more scenarios and live-model execution. ## Google ADK: payment approval [Section titled “Google ADK: payment approval”](#google-adk-payment-approval) A requester submits a payment, a reviewer approves it, and a payer tries to add it to an in-memory ledger. The agents pass their results through a serial ADK workflow. Policy A payment is only allowed when it exactly matches a prior request which has been approved by a reviewer. Datalog excerpt ```prolog IsAuthorized(idx) :- Actions(idx, a), a = $CallTool("disburse_payment", args), ApprovedPayment( @json_get_str(args, "request_id"), @json_get_str(args, "payee"), @json_get_str(args, "amount")). ``` `ApprovedPayment` joins successful request and approval tool results in `CurrentDepends`, checks their agent labels, and matches all three fields. See its definition in the [full policy](https://github.com/sasy-labs/sasy/blob/main/examples/adk-separation-of-duties/payment_policy.dl). ```bash # Allowed: the request, approval, and payment match uv run examples/adk-separation-of-duties/main.py # Denied: the payer names a different payee uv run examples/adk-separation-of-duties/main.py --scenario wrong-payee ``` The default run records one payment under `dispatched`. The wrong-payee run is denied and leaves the ledger empty. See the [example README](https://github.com/sasy-labs/sasy/tree/main/examples/adk-separation-of-duties) for the policy and other scenarios, and the [ADK guide](/integrations/google-adk/) for supported configurations. ## Langroid: information flow across a team [Section titled “Langroid: information flow across a team”](#langroid-information-flow-across-a-team) The `research` and `records` agents read documents and pass summaries to `main`, which can send simulated email but cannot read the documents itself. An inbox document contains an injected instruction to forward a confidential merger plan to an external auditor. Run the same team under two policies. ### MLS [Section titled “MLS”](#mls) Policy Readers must be cleared for the documents they open. Email recipients must be cleared for every document that influenced the send. Datalog excerpt ```prolog Unauthorized(idx) :- Actions(idx, a), IsTool(a, "send_email"), a = $CallTool(_, args), to = @json_get_str(args, "to"), Clearance(to, clearance), ReadInDeps(path), FileLevel(path, level), level > clearance. ``` ### Toxic flow [Section titled “Toxic flow”](#toxic-flow) Policy Allow reads and internal sends. Deny an external send when both an untrusted and a confidential document influenced it. Confidential input alone does not trigger this denial. Datalog excerpt ```prolog Unauthorized(idx) :- Actions(idx, a), IsTool(a, "send_email"), a = $CallTool(_, args), to = @json_get_str(args, "to"), !Internal(to), UntrustedInDeps(), ConfidentialInDeps(). ``` `ReadInDeps` finds document reads in `CurrentDepends`; `UntrustedInDeps` and `ConfidentialInDeps` classify those reads. The full [MLS policy](https://github.com/sasy-labs/sasy/blob/main/examples/langroid-information-flow/mls_policy.dl) and [toxic-flow policy](https://github.com/sasy-labs/sasy/blob/main/examples/langroid-information-flow/toxic_flow_policy.dl) define these helpers, document levels, clearances, and allowed actions. ```bash # Enforce document and recipient clearances uv run examples/langroid-information-flow/demo.py --policy mls # Block external sends combining untrusted and confidential input uv run examples/langroid-information-flow/demo.py --policy toxic-flow ``` Both deny the injected request to send a confidential merger plan to an external auditor. A user-requested send of the plan to an uncleared partner is denied by MLS but allowed by toxic flow when no untrusted input influenced it. See the [example README](https://github.com/sasy-labs/sasy/tree/main/examples/langroid-information-flow) for the policies and concurrent scenarios, and the [Langroid guide](/integrations/langroid/) for supported configurations. ## Run with a real model [Section titled “Run with a real model”](#run-with-a-real-model) Set the provider credentials in the repository-root `.env`: `OPENAI_API_KEY` for LangChain and Langroid, or `GOOGLE_API_KEY` for ADK. Add `--live` to use a real model; Langroid also requires `--model`: ```bash # LangChain: use the live model instead of the scripted model uv run examples/langchain-information-flow/demo.py --live # ADK: use Gemini for the same payment workflow uv run examples/adk-separation-of-duties/main.py --live # Langroid: choose an OpenAI model and enforce the MLS policy uv run examples/langroid-information-flow/demo.py --policy mls --live --model gpt-4.1-mini ``` SASY still enforces the selected policy before tools execute. Live runs make paid provider requests; documents, payments, and deliveries remain simulated. The model may choose different actions, so inspect the tool decisions rather than expecting the scripted results. These examples bind their policies per session. SASY can concurrently enforce different policies for multiple agents on the same engine without restarting it. To integrate your own agents, see [SDK usage patterns](/sdk/). # Get started > Install SASY, start a local engine, and enforce a policy on your agent. For convenience, SASY includes skills for coding agents (Claude Code, Codex, Cursor and others) that help with setup, framework integration, policy writing and explaining denials. Install them with: ```bash npx skills add sasy-labs/sasy ``` Then ask your agent to walk you through a SASY demo or integrate enforcement into your system. To enforce policies on the coding agent itself (Claude Code, Codex or pi), ask it to set up SASY Guard; the skills install the [SASY Guard](https://guard.sasy.ai) skill for that. ## Use SASY in your project [Section titled “Use SASY in your project”](#use-sasy-in-your-project) You need uv and a running Docker installation. No checkout of this repository is needed. In your project: ```bash uv venv --python 3.11 source .venv/bin/activate uv add sasy # in a project with a pyproject.toml # uv pip install sasy # in a plain directory without one sasy engine start ``` `sasy engine start` starts the policy engine, with a default configuration set up at `~/.sasy`, automatically read by the Python SDK. To build the engine yourself, see [build from source](/building/). Without installing the SDK, you can also run `uvx sasy engine start`. Write your rules in Datalog using the [policy guide](/policy-language/), or describe your policy in natural language and use the [`write-policy` skill](https://github.com/sasy-labs/sasy/tree/main/plugins/policy-compiler/skills/write-policy) to translate it into enforceable Datalog. Then enable SASY before building your agents. For example, with your LangChain model and tools: ```python from pathlib import Path import sasy from langchain.agents import create_agent sasy.instrument() agent = create_agent(model, tools) with sasy.session(policy=Path("policy.dl")): result = agent.invoke({"messages": [{"role": "user", "content": "Your task"}]}) ``` See [SDK usage patterns](/sdk/) for connection options and examples with other frameworks. ## Example: information flow [Section titled “Example: information flow”](#example-information-flow) The example policy blocks email influenced by **both sensitive and untrusted inputs**. A coordinator spawns two summarizer agents to review a sensitive report and an untrusted note that tries to redirect the email. Influence follows the dependency graph through their summaries. ### See the decision [Section titled “See the decision”](#see-the-decision) The two illustrative variants show what happens when the note’s summary arrives before the send, or has not arrived yet: the redirected send is blocked; the intended send is allowed. Step through each variant to inspect its dependencies. [Open the side-by-side comparison](/diagrams/information-flow.svg) Allowed sendBlocked send #### Note has not arrived ALLOW · Send to reviewer ReplayBackNextStep 15 of 15 Policy decision · Send to reviewer ALLOW · Only S influenced this send. The email may go to the intended reviewer. #### Note arrives before the send DENY · Redirected send ReplayBackNextStep 15 of 15 Policy decision · Redirected send DENY · Both U and S influenced this send. The email handler does not run. **U**** Untrusted**S**** Sensitive** Ancestors** LLM call** Tool action** Input / result Influence follows the arrows. Borders show inherited U/S labels; dotted outlines mark the selected action’s ancestors, including untainted inputs. These are illustrative variants of the example policy. The runnable [message-flow example](https://github.com/sasy-labs/sasy/tree/main/examples/message-flow) demonstrates the same rule with a scripted single agent in two runs. It uses synthetic documents, simulated email, and a local engine; no model-provider key is needed. The example README includes the setup and run instructions. The trace shows the scripted agent’s reads, summary, send request, and policy decision in each run. The [example README](https://github.com/sasy-labs/sasy/tree/main/examples/message-flow) also explains the optional live-model version. Once the local engine is running, you can enforce policies on your own agents. Start with [SDK usage patterns](/sdk/), or run the [framework examples](/examples/). For framework-specific guidance, see [Google ADK](/integrations/google-adk/) or [Langroid](/integrations/langroid/). For custom orchestration, [use the SDK directly](/quickstart/) or [add a framework](/instrumentation/). # Add a framework An adapter has two jobs: **record how messages are produced, processed and passed**, and **check each action before the line of code that runs it**. The recorded messages and dependencies are the graph a policy reasons over; the reference monitor decides whether a proposed action may proceed. Recording an action after it happened enforces nothing. Terms used here are defined on the [concepts page](/concepts/). If you are using LangChain, Google ADK or Langroid, use the supplied adapter instead: this page is for adding a framework that has none. ## Integrate once, reuse across agents [Section titled “Integrate once, reuse across agents”](#integrate-once-reuse-across-agents) An adapter connects a framework’s shared message and dispatch methods to SASY. Build it once for a new framework or custom orchestration mechanism, then reuse it across agents using that mechanism. You do not need to rewrite it for each agent, prompt, or tool definition. Each application still configures credentials, policies and session boundaries, and covers any custom paths outside those shared methods. To add an adapter: 1. Identify the methods that produce, process and pass messages, including model calls, tool handlers and delegation. Resolve the actual input snapshots to immutable message IDs before dispatch. 2. Record those messages and their dependencies in the active session. Preserve structured tool calls even when a response has no text. 3. Find every action-dispatch site and check the exact outgoing action with its input IDs before execution. Carry decisions back to the framework and stop on denial or failure. 4. Verify the dependency graph and exercise allowed, denied, error and concurrent paths. Add coverage whenever a framework upgrade or custom override introduces a new path. The sections below describe the contract these hooks must implement. ## The core contract [Section titled “The core contract”](#the-core-contract) Treat framework methods as computations from input messages to output messages. Record the actual messages and connect each input to the output that used it: `input → output`. A dependency means “this computation consumed that input,” not simply “these events happened next to each other.” | Framework operation | Inputs | Output | | -------------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | | LLM call | The list of messages sent to the model, including supplied context | The model’s response, with any structured tool-call specifications | | Tool-call handler | The message containing the selected tool call, plus any additional message inputs the handler consumes | A message containing the tool’s actual return value and its originating tool specification | | Parser, formatter or summarizer | The messages being processed | The derived message | | Agent delegation or message forwarding | The messages passed to the receiving agent | The receiving message or subsequent result, retaining its input dependencies | Observe all methods that produce, process or pass these messages, including application-owned wrappers around a framework. Preserve an existing message ID when passing the same observation; give a newly derived message a new ID. Keep parallel calls and subagents connected to their actual inputs. If a method consumes additional context, include that context rather than linking only the most recent message. ## A tool-call handler [Section titled “A tool-call handler”](#a-tool-call-handler) This framework-neutral pseudocode shows the order of operations. `observe` and `require_allow` stand for your adapter’s SDK calls; they are not SDK function names. Inputs have already been recorded in the active session. ```python def handle_tool_call(input_message, tool_call): inputs = [input_message.id] require_allow(tool_action(tool_call), input_ids=inputs) value = dispatch_tool(tool_call) output = tool_result_message(value, derived_from=tool_call) observe(output, input_ids=inputs) return output ``` The checked name and arguments must describe the call that is actually dispatched. Place the check where execution occurs, including alternate dispatch paths, retries and delegated calls. Only an allow decision may reach `dispatch_tool`. A denial, an approval request, or an unavailable engine must stop this path; an approval suggestion is not itself authorization. Apply required transforms through a supported adapter before dispatch, or stop if the adapter cannot apply them. Record a tool exception as an error outcome, not a successful result. If the call is denied, report the denial to the framework instead of manufacturing a tool return value. ## An LLM call [Section titled “An LLM call”](#an-llm-call) The model consumes the whole supplied message list, so its reply depends on every message in that list. A reply that proposes a tool call is still a message; it is not permission to execute the call. ```python def call_model(messages): inputs = [message.id for message in messages] require_allow(model_request(messages), input_ids=inputs) response = dispatch_model_request(messages) observe(response, input_ids=inputs) return response ``` Represent the outgoing model request using the action vocabulary your policy and adapter agree on, such as its HTTP request. The check belongs at that outgoing dispatch site. If a framework adapter already mediates it, preserve that mediation. The later tool dispatch needs its own check against the selected tool and arguments. ## Connect the contract to the SDK [Section titled “Connect the contract to the SDK”](#connect-the-contract-to-the-sdk) For one message at a time, `sasy.record(text, role=..., inputs=[...])` records a new immutable version with its input edges and returns its ID; it builds on `resolve_events`, described below. In Python, `sasy.observability.record_events_with_dependencies(events, edges)` records messages and edges atomically. `Event.tools` carries tool-call specifications in an input message; `Event.derived_from` identifies the tool behind a result. `Event.metadata` is an optional free-form string of your own, described below. An `Edge(source=input_id, destination=output_id)` records the dependency. The authenticated writer is stamped by the server; message roles and caller-supplied actor labels are not authentication credentials. ### What goes in the text, and what goes in the metadata [Section titled “What goes in the text, and what goes in the metadata”](#what-goes-in-the-text-and-what-goes-in-the-metadata) An adapter has to make one guarantee about every message it records: an edit to the message is an edit the engine can see. The engine’s content hash — the digest that decides whether a message handed back later is the message that was recorded — is taken over the whole event. Whatever you put in the event is protected by it; whatever you leave out can be changed without the recorded node changing, so a compact reference to that node would still verify after the edit. That gives a rule with two halves: * **The text is what policies read.** Put the message’s content there, spelled the way a rule would expect to match it: a string as it stands, a structured body as one JSON string. A tool call’s arguments follow the same rule. Two different messages are allowed to share a text. * **`metadata` is everything else whose edit must be visible.** Put there a record of the whole source message — every field the framework carries, not only the fields a provider is known to read — encoded so that only that message can produce it. The server stores the string verbatim, returns it verbatim and never interprets it; it is simply part of what the hash covers. A policy can read it, through the `MessageMetadata(id, metadata)` relation, so it is worth writing the record in a form a rule can address — which is what the supplied adapters’ canonical JSON is. See [policy metadata](/policies/extensions/#message-metadata) for the relation and producer APIs. An event with no `metadata` hashes exactly as it did before the field existed, so an adapter that does not need it can leave it unset. Encoding the record is the part worth care. A framework’s own JSON dump is usually lossy — it typically writes bytes and the string they decode to alike, a tuple and a set as one list, and every dict key as a string — and each loss is two different messages sharing one node and one mark. The supplied [LangChain](/integrations/langchain/#what-a-node-holds) and [ADK](/integrations/google-adk/#what-a-record-holds) adapters encode the dump by type, with a wrapper per type and a prefix per key kind, and stop the run on a type the encoding does not know rather than writing it down as something else. Either follow that shape or use an encoding of your framework’s own that is injective for the same reason. For tool actions, `sasy.check_tool_call(name, args_json, input_node_ids=[...])` returns the decision. The TypeScript SDK exposes `registerEventsWithDependencies` and `checkToolCall`; call these methods on the object returned by `sasy.session(sessionId)` to supply the session scope. Unlike Python’s context manager, creating a TypeScript session does not set ambient scope for top-level SDK calls. Bind the policy and keep recording and checking inside the same session; register input observations before checking an action that depends on them. HTTP forwarding uses the reference-monitor proxy API. See [configuration](/configuration/) for connection and session setup and [core relations](/policies/core-relations/) for the request facts these operations produce. For a runnable implementation, see the [message-flow example](https://github.com/sasy-labs/sasy/tree/main/examples/message-flow). It records synthetic context, checks a proposed send through the real engine, and dispatches only the allowed case. It needs no model-provider credentials. ## Immutable message versions [Section titled “Immutable message versions”](#immutable-message-versions) Use `sasy.observability.resolve_events` (or `resolve_events_async`) to register complete message snapshots. The TypeScript equivalent is `resolveEvents`, also available on a `Session`. Send the actual consumed inputs together, then use the returned IDs in the action check and the output’s dependency edges. A framework message’s `event.id` is a stable **origin**, distinct from its server-returned version ID. Use a fresh origin for each new message-producing computation, even when two outputs contain identical text. Resolving an unchanged snapshot returns the same version, including after a server restart. It creates no new graph writes or synchronization events. ```python from sasy.observability import resolve_events from sasy.proto.observability_pb2 import Edge, Event, EventSnapshot # Inside an active sasy.session(...). original = Event(id="user-message-1", text="Draft for internal review") [first] = resolve_events([EventSnapshot(event=original)]) # A later call checks the current content and sends a compact reference. [unchanged] = resolve_events([EventSnapshot( event=original, base_id=first, reuse_dependencies=True, )]) assert unchanged == first # An observed editing operation read the original and produced this revision. [edited] = resolve_events([EventSnapshot( event=Event(id=original.id, text="Revised draft for internal review"), base_id=first, dependencies=[Edge(source=first, destination=original.id)], )]) ``` Unchanged inputs use compact references by default: the SDK still reads the full current message, but sends its origin, immutable version ID and a content digest. New messages and explicit edits send full contents and complete dependencies. Mixed batches resolve atomically; a missing version or mismatched digest rejects the batch without creating replacement IDs or graph updates. A version must be registered before an action can use it. The SDKs cache at most 4,096 successful capture fingerprints. They retain no raw message bodies in this cache, and recheck the current fields on every call. An exact match can reuse the captured digest; changes or eviction run credential capture again. Cache loss affects performance, not version identity or history. Content digests cover the captured event fields; version IDs also distinguish origins and dependencies. Identical content does not merge distinct computations. This path requires an engine with `ResolveSnapshots`; an older engine fails explicitly. Upgrade the engine before its clients. For comparison or compatibility, Python accepts `resolve_events(snapshots, compact=False)` and TypeScript accepts `resolveEvents(snapshots, sessionId, { compact: false })` (or `session.resolveEvents(snapshots, { compact: false })`). This resends full snapshots through `ResolveEvents` and disables the SDK capture cache; it does not relax provenance checks. For a mutation, provide its complete contents and incoming dependencies. Omitted fields are removed, and an empty dependency list means no inputs. `base_id` identifies the version being revised; it does not automatically add an edge or copy tool-execution evidence. An edit that reads the old message should depend on that version and every other input the edit consumed. Existing outputs keep their original dependencies. A changed hash alone cannot establish what caused an edit; `reuse_dependencies=True` rejects changed contents. Dependency sources must be immutable version IDs or origins submitted in the same atomic batch. Do not attach new dependencies later with the legacy APIs. `record_events` and `record_events_with_dependencies` remain available with their existing merge semantics, but cannot overwrite immutable versions or change their incoming dependencies. Legacy mutable messages need explicit migration before they can be inputs to immutable observations. Version comparison covers the transmitted event fields and dependencies, after credential capture sanitization. Framework-only metadata and redacted values are not additional graph facts. Keep batches below the engine’s 16 MiB RPC limit, and finish resolving all required inputs before dispatching an action. ## Supplied Python adapters [Section titled “Supplied Python adapters”](#supplied-python-adapters) | Framework | Extra | `sasy.instrument()` argument | | --------------------------------------- | ----------- | ---------------------------- | | [LangChain](/integrations/langchain/) | `langchain` | `langchain` | | [Google ADK](/integrations/google-adk/) | `adk` | `adk` | | [Langroid](/integrations/langroid/) | `langroid` | `langroid` | Call `sasy.instrument()` once at startup, after any explicit `sasy.configure(...)` and before you build any agent. Each framework argument takes one of three values: * Left out (`None`): enable the adapter if the framework is installed, and do nothing if it is not. * `True`: enable the adapter, and raise an error if the framework is not installed. * `False`: skip the framework. So `sasy.instrument()` with no arguments enables every supplied adapter whose framework is installed. It does not enable the [HTTP hooks](#http-hooks) below; those are off unless you pass `http=True`. A framework can be installed but unusable by its adapter: LangChain or Google ADK at a version its adapter does not support, or any of the three frameworks at a version its adapter cannot import. What happens then depends on the framework’s argument: * Left out (`None`): `sasy.instrument()` skips that framework and says nothing yet. The first time the application uses the framework, SASY issues a `SasyInstrumentationWarning` (a Python warning class exported from `sasy.instrumentation`; the same message is also logged). It is issued once per process and points at the line of your code that used the framework. An application that has the framework installed but never uses it gets no warning. The message gives the reason and says that the framework’s agents will NOT be checked by SASY. It then tells you how to act: pass `True` for that framework to make this an error, or `False` if your application does not use it, which also silences the warning. “Uses” means calling one of the framework’s public entry points, which SASY wraps only to issue the warning and otherwise leaves unchanged: `langchain.agents.create_agent` or running any LangGraph graph (`invoke`, `ainvoke`, `stream`, `astream`); `run`, `run_async` or `run_live` on a Google ADK `Runner`; `run` or `run_async` on a Langroid `Task`, or an LLM response from a Langroid `ChatAgent` (`llm_response`, `llm_response_messages` and their async forms). If even these entry points cannot be loaded (for example a broken install), the warning is issued by `sasy.instrument()` itself. * `True`: `sasy.instrument()` raises an error before it changes anything. The message names the argument to set to `False` if your application does not use that framework. * `False`: the framework is skipped with no warning. A framework that is not installed at all is skipped silently when its argument is left out. The Langroid adapter does not check the installed version. The changes `sasy.instrument()` makes cannot be undone, and calling it again is harmless. To turn the warning into an error for every framework at once, use Python’s standard warning filter, for example `warnings.simplefilter("error", sasy.instrumentation.SasyInstrumentationWarning)`. The error is then raised at the first use of the framework, not by `sasy.instrument()`; pass the framework’s argument as `True` to fail at start-up instead. The `langchain` argument also counts LangGraph as installed, since LangGraph does not need the `langchain` package. With LangGraph alone, the adapter cannot load: `sasy.instrument()` warns that LangChain and LangGraph agents will not be checked, or raises with `langchain=True`. Install the `langchain` extra, or pass `langchain=False`. If your own adapter covers a LangGraph graph that runs tools through a `ToolNode`, pass `langchain=False`. With the LangChain adapter enabled, inside a SASY session tools run only in agents SASY builds: every tool call of a `ToolNode` that SASY did not build is refused; see [tools SASY does not protect](/integrations/langchain/#tools-sasy-does-not-protect). The base SDK installs no agent framework. Use it to record messages and check actions directly, or with the HTTP hooks below. ### HTTP hooks [Section titled “HTTP hooks”](#http-hooks) The HTTP hooks patch `httpx` and `requests` so that outbound requests go through the reference monitor as actions your policy can allow or deny. They are off by default; `sasy.instrument(http=True)` enables them. Enable them when you need credential injection (the reference monitor adding an API key the engine holds to a request) or want the policy to check the agent’s outbound requests. The policy must then allow each host the agent calls, including the model provider’s. To enable only the HTTP hooks, alongside your own adapter, call `sasy.instrument(http=True, langchain=False, adk=False, langroid=False)`. The hooks deliberately let `localhost`, `127.0.0.1` and `::1` through without a check, and they do not cover other networking libraries or anything your code runs locally. Credential transforms on HTTP requests are applied by the reference-monitor proxy. ### Validating your adapter [Section titled “Validating your adapter”](#validating-your-adapter) Run a small conversation and check the stored input and output edges. Exercise an allowed dispatch, a denied one, a tool error, concurrent calls and an engine that is unreachable. Simulate a failed recording too: a protected call must not proceed when the messages its policy needs were never recorded. Check the synchronous and asynchronous paths separately where the framework has both. ## Captured content [Section titled “Captured content”](#captured-content) A recorded message goes to the graph as it is: the text of an event, its metadata and a tool call’s arguments are not rewritten. They are what a policy reads, and the reference monitor is handed the same bytes when it decides, so a rule reading an ancestor’s contents reads what the action carried. Recognized transport credentials are still removed where transport metadata appears — span attributes, SDK diagnostic logs, and the URLs and feedback text the HTTP hooks record — because no policy decides on those. The graph therefore holds the conversation as it happened and is sensitive: protect it as a store. Capture-budget failures stop before the observation RPC; do not proceed with a protected action whose required observations were not recorded. See [current limits](/limits/). # Google ADK > What the Google ADK adapter checks, how to enable it, and what it does not cover. ## At a glance [Section titled “At a glance”](#at-a-glance) **What you get** * Every function tool is checked against your policy immediately before its Python callable runs, with ADK’s default argument values already filled in. * Agent transfers, `AgentTool` children and native task children are checked before they start. * The check sees the call’s [ancestry](/concepts/) across agents, including values passed through session state (`output_key`, `{key}` templates, `tool_context.state`) and text artifacts. * A denied tool does not run. The model receives an error result beginning with `[BLOCKED]`. **How to enable** 1. Follow the [quick start](/get-started/) to run the engine and install the SDK. Run your Python entry point with `python your_agent.py` in the environment where you installed the SDK and framework. Google ADK **2.9.1** exactly is required. 2. Call `sasy.instrument()` once at startup. It enables the ADK adapter when Google ADK is installed. 3. Run your existing `Runner` inside `with sasy.session(policy=...):`, using `runner.run_async`. Your agents, tools and models do not change, and the adapter is the same for every ADK application. Outside an active SASY session, the patches pass through to native ADK behavior. The supported paths and restrictions below apply while SASY is active, including when you opt into a [process-wide default session](/configuration/#session-lifetime-and-background-work). ## Run the example [Section titled “Run the example”](#run-the-example) [`examples/adk-separation-of-duties`](https://github.com/sasy-labs/sasy/tree/main/examples/adk-separation-of-duties) runs three agents — a requester, a reviewer and a disburser — in an ADK `Workflow` with scripted models, and allows the payment only when its ancestry contains a matching approval. `main.py` there is the complete runnable file for the outline below. ## Enable it [Section titled “Enable it”](#enable-it) Configure the SASY endpoint and authentication as described in the [local engine guide](/local-engine/), then enable the framework patches: ```python import sasy sasy.instrument() # runner is an ordinary google.adk.runners.Runner. with sasy.session(policy=policy_source): async for event in runner.run_async( user_id=user_id, session_id=adk_session_id, new_message=user_content, ): show(event) ``` `policy_source` is the policy to bind; `runner`, `user_id`, `adk_session_id` and `user_content` are ADK’s own values, and `show` stands for whatever your application does with each event. * Call `sasy.instrument` once, at startup. It enables SASY for each supported framework that is installed: ADK, and also LangChain and Langroid if they are present. Pass `adk=True` to make a missing or unsupported ADK an error rather than skipped, and `langchain=False` or `langroid=False` to skip a framework you do not use. * If Google ADK is installed at a version other than 2.9.1, `sasy.instrument()` skips the ADK adapter. The first time the application then calls `run`, `run_async` or `run_live` on an ADK `Runner`, SASY issues a `SasyInstrumentationWarning` (a Python warning, also logged, once per process) saying that ADK agents will NOT be checked by SASY. An application that has ADK installed but never runs it gets no warning. Pass `adk=True` to make this an error, raised before anything is changed, or `adk=False` if your application does not use ADK, which also silences the warning. * HTTP checks are off by default. Pass `http=True` to route requests made with `httpx` or `requests` through the engine, which checks each one against the policy and can inject credentials (API keys the engine holds) into it. That includes the model’s request to Google, so the policy must then allow Google’s model endpoint. The example turns HTTP checks on only for its live model; its scripted models make no requests. * Keep your existing runner, model and tool objects. * Use `run_async`. The synchronous `Runner.run` runs on a thread that does not carry the SASY session. * Give each top-level ADK conversation its own SASY session. Use `end_on_exit=False` when the session has to survive between turns, and end it explicitly when the conversation finishes. * Separate conversations may run at the same time. Two turns of the *same* conversation at the same time are rejected. * Keep the runner to continue a conversation. Importing a stored history into a new runner is not supported, because the adapter cannot reconstruct where those messages came from. * Use ADK’s `InMemorySessionService` or `DatabaseSessionService` on its current v1 schema. A v0 database has to be migrated first, and another session service is untested. * For database sessions also install `'sqlalchemy[asyncio]>=2,<3'` and an async database driver, and use its URL scheme, for example `sqlite+aiosqlite:///sessions.db` with ADK’s bundled SQLite driver. ## Compatibility [Section titled “Compatibility”](#compatibility) **Not supported** — the run stops with an error, before it starts or when the path is reached: * `Runner.run` (the synchronous entry point), live audio and video, remote agents and A2A or MCP toolsets (the two protocols ADK uses to reach agents and tools in other processes), plugins, code execution, compaction, provider context caches, resumable apps, Jinja instruction templates, custom `BaseAgent` subclasses, custom execution overrides on tools, and importing an existing session history into a new `Runner`. * Credential transforms on tool calls: a decision that requires one blocks the tool. The reference monitor applies transforms to HTTP requests routed by `sasy.instrument(http=True)`. * Model egress (the model’s own requests to Google), unless you pass `http=True`, and even then when the GenAI client does not use `httpx`. **Session boundaries** [Ancestry and tool evidence do not cross SASY sessions.](#values-from-another-sasy-session) A value carried into a new session is marked as unattributed input. Policies should handle that marker explicitly; missing ancestry does not establish that the value is safe. ## Supported execution [Section titled “Supported execution”](#supported-execution) The adapter supports text `LlmAgent` execution, ordinary text streaming, synchronous or asynchronous function tools, local `transfer_to_agent` handoffs, and standard `SequentialAgent`, `ParallelAgent` and `LoopAgent` composition. Gemini’s generate-content API and scripted models are the model paths the adapter is tested against. Other model providers are untested: they may work, with no guarantee. Function-tool subclasses may retain their own declarations, but must use ADK’s standard execution methods; custom execution overrides require separate instrumentation. Agent names must be unique throughout the configured tree, so parallel agents cannot share an output or tool-call identity. The adapter also supports a root `Workflow` with a static serial chain of standard single-turn `LlmAgent` nodes, or one fan-out into disjoint agent chains that meet at a `JoinNode`, optionally followed by more serial agents. Each parallel branch keeps its own ancestry until the join combines the exact outputs of its predecessors. A later agent then sees the joined ancestry, including tool results from all branches. An exclusive conditional fork can instead select one of two or more disjoint agent chains through a guarded router tool immediately after `START`. The selected chain may reconverge at an ordinary agent. Its actions inherit the router’s decision and the selected branch’s history, including state reads made by the router. Unselected branches do not run. This profile requires at least two distinct nonempty string routes and a single finalizer; other routes and merges are rejected. Graph nodes that run arbitrary functions or tools, dynamic nodes, callbacks, retries, and schema coercion are also rejected. State templates, `output_key`, tool-context state access, and supported text artifacts use the same instrumentation in serial and exclusive conditional Workflows. In a Workflow with parallel branches, these operations are supported before the fork and after the `JoinNode`. Concurrent branches can also save and load text artifacts through ADK’s built-in `FileArtifactService`, including artifact instruction templates. Each read depends on the exact published version it consumed. Mutable state, filename listings, `LoadArtifactsTool`, and in-memory or custom artifact services remain restricted in concurrent branches. When one model message asks for several tools at once, the adapter records one node per call, and each tool’s result depends on all of those call nodes. ADK combines the results of such a batch into a single event before storing them. A tool in a batch may write state: each call’s writes are recorded against that combined event, with the same provenance a single call’s writes get. Forwarding an `AgentTool` child’s writes is the one exception, and is refused in a batch. Streaming chunks pass through normally. SASY observes the completed model output before downstream tool dispatch; it does not record an event or make an RPC for each chunk. Cancellation before completion does not create a completed-output observation. Bidirectional live audio/video is a separate, unsupported path. Local transfers are checked before the transfer tool sets its target. A denied transfer does not start the receiving agent. The receiving model’s dependencies come from the messages it actually consumes, including ADK’s presentation of another agent’s messages. Tool authorization runs after ADK’s argument preprocessing and tool callbacks. The check includes default argument values and uses a private copy of exactly the arguments passed to the callable. Denials and required transforms prevent execution; this adapter does not apply transforms. Tool error results contain a `[BLOCKED]` explanation that the model can consume. Denied calls, required transforms and tool returns containing an `error` field are recorded as feedback without successful `ToolResult` evidence. Later framework response events do not turn that feedback into evidence of execution. Recording or policy-service failures abort execution instead of allowing a tool without evidence. A model response that carries a provider error code or error message stops the run. It is never recorded as a completed model output, so it cannot dispatch a tool or count as a child agent’s successful reply. A before-model callback may drop messages or rewrite the request. Messages it keeps unchanged keep their IDs. Content it changes is recorded as a new message computed from the callback’s inputs and the state it read. A callback may not add tools or function declarations, and so cannot open a dispatch path the adapter does not check. Callbacks and tool implementations must not consume unrecorded external context or perform unmediated protected actions; such custom orchestration needs its own instrumentation. A callback’s fabricated response is not an observed model or tool execution and fails correlation. Generated system instructions are recorded as callback derivations. Before-model callbacks receive the request message IDs; after-model callbacks receive the completed output IDs. Tool preparation and before-tool callbacks receive the initiating message IDs, and after-tool callbacks also receive the actual result IDs. These task-local scopes carry into nested HTTP checks. After-model callbacks on partial streaming chunks are rejected because those chunks have no individual graph identity. Before each model call the adapter records the exact messages the model is about to receive and gets back a permanent ID for each. A message that has not changed keeps its ID, and a short content hash is sent in place of its text, so nothing new is stored. This includes ADK’s *presentation* of another agent’s messages — the context text ADK writes when it shows one agent’s output to another. A message counts as an input only if it is actually in the request, not because it sits in the ADK session. If recorded history was edited between turns, the run stops: an edit on its own does not say what the new content was computed from. Native history and message presentations retain their exact source event identities, so identical replies from different agents remain distinct. Unknown provenance or edits to a bound presentation stop execution. Tool-call IDs must be unique for each agent within the retained conversation; different agents may reuse an ID. ### What a record holds [Section titled “What a record holds”](#what-a-record-holds) The adapter records message content for policies and a canonical snapshot in metadata so the engine can detect changes to the source message. See [records for policies](/reference/google-adk-records/) for field paths, query examples, and representation limits. ### Child agents and tasks [Section titled “Child agents and tasks”](#child-agents-and-tasks) Ordinary `AgentTool(child)` calls and configured `LlmAgent` children with `mode="single_turn"` or `mode="task"` are observed automatically. Each delegation is checked under the child’s tool name before launch. Native task completion is also checked as `finish_task`; include these action names in the policy where appropriate. Calls made by the child still receive their own tool checks. The delegation target is verified again after the check returns, so a child swapped while authorization was pending is never launched. The child input depends on the exact initiating call. The parent’s return value depends on the specific completed child response that ADK returns, carrying that response’s ancestors. Parallel siblings keep separate scopes; merely sharing a session does not make one sibling’s approval evidence available to another. Denial, cancellation and failed completion do not create successful delegation evidence. Repeated identical replies retain distinct identities. These native task modes currently support plain text input/output and standard execution without task retries, `parallel_worker`, custom task schemas or resumption. Your own calls to `Context.run_node` are not supported. The adapter handles ADK’s node machinery only for the child-agent modes listed above and the qualified root `Workflow` graphs described earlier. `include_contents="none"` may still retain messages from the current invocation. When selective history matters, inspect the finalized request or filter its message objects in a before-model callback; the adapter records what is actually sent. Agent names are application-assigned labels, not authenticated human identities. SASY stamps the authenticated writer separately. Do not treat an ADK `user_id`, message role, or remote agent label as independent authentication. ## Boundaries [Section titled “Boundaries”](#boundaries) The adapter rejects unsupported ADK versions and missing dispatch hooks. Before a conversation runs, it checks for unsupported custom agents, remote/toolset tools, structured instruction values, combined or structured `static_instruction` configurations, code execution, plugins, compaction, provider context caches and resumable apps. Unobserved state changes and unsupported artifact operations also abort. Jinja rendering is rejected where it happens rather than up front: ADK 2.9.1 has no setting that turns it on, and the only way to reach it is to call `instructions_utils.inject_session_state` with `use_jinja2=True` yourself, which stops the run at that call. These paths need explicit provenance instrumentation before they can be supported. Bidirectional audio/video, remote A2A/MCP execution, and importing an existing unobserved session history are not supported. Reusing a runner’s recorded conversation is supported; reconstructing its correlation from persistent history is not. Cancellation restores the caller’s context; a cancelled run does not establish evidence for unfinished work. HTTP `extra_body` overrides are rejected in both finalized model requests and Gemini client defaults, including clients created through `client_kwargs`. These options can replace the input body after framework observation and would otherwise invalidate its provenance. Model network egress is a separate action boundary. SASY’s HTTP instrumentation, which is off by default and enabled with `sasy.instrument(http=True)`, covers supported `httpx`/`requests` transports. Google GenAI can select `aiohttp`, which these hooks do not cover; the live example explicitly supplies `types.HttpOptions(httpx_async_client=httpx.AsyncClient())`. The adapter propagates model input IDs into model HTTP checks and the originating tool-call IDs into HTTP checks made inside function tools. Other transports need their own interceptor; framework observation alone does not enforce network egress. ## State and artifact inputs [Section titled “State and artifact inputs”](#state-and-artifact-inputs) ADK injects state through instruction templates and writes model responses with `output_key`. SASY records those reads and writes, preserving the producing messages when a later agent reads a value—even with `include_contents="none"`: ```python writer = LlmAgent(name="writer", model=model, output_key="decision") reader = LlmAgent( name="reader", model=model, instruction="Use this decision: {decision}", include_contents="none", ) # Put writer before reader in a SequentialAgent. ``` An instruction may also be a callable provider, synchronous or asynchronous, that ADK calls with a read-only context before each model call: ```python def instruction(context): return "Use this decision: " + context.state.get("decision", "none") reader = LlmAgent(name="reader", model=model, instruction=instruction) ``` The provider’s `state` mapping records the key and value at each read, exactly as an instruction template does, and the resulting system instruction depends on those keys and nothing else. A provider that reads no key yields an instruction with no state dependencies, so an approval stored under a key it never read does not reach a later tool check. Testing whether a key exists is a presence read. The provider must return text. Its context offers state, the invocation id, the agent name and the user id; the session, the invocation’s user content, custom metadata and credentials stay blocked, because those carry no observed provenance of their own. `global_instruction` providers work the same way. Only referenced keys become dependencies. `{key?}` records an absent optional value; unrelated keys do not supply approval ancestry. Unprefixed keys belong to the ADK session; `app:`, `user:` and `temp:` select application, user and invocation scopes. A `temp:` key belongs to one invocation: the adapter records it under the invocation that wrote it, and ADK keeps it out of the event it stores. Writing a `temp:` key and a stored key in the same call is supported and recorded as a write of both. Initial values supplied outside an observed computation are labeled as unattributed external inputs, not successful tool results. Later unobserved edits, including nested container edits, stop execution. Function tools may receive ADK’s injected `ToolContext`. Its `state` mapping captures the key and value at each read. Reads are synchronous and do not make an RPC individually; SASY flushes pending observations before a protected tool or HTTP action and before recording the output. Callbacks use separate scopes, so their reads also reach the actions and derived messages that consume them. The runtime context handle is excluded from JSON action arguments; resolved data arguments and defaults remain in the check. Testing whether a key exists (`"decision" in tool_context.state`) is recorded as a presence read, without reading the value. When an agent’s `output_key` or a tool assignment created the key, that presence read depends on the message that created it, exactly as a read of the value would. Assign a JSON value to a state key to record a write. Nested values returned by reads are immutable: copy, edit and reassign the whole key when needed. State writes require the exact injected context: the `ToolContext` in the function-tool body, or the `CallbackContext` of the callback making the write. Direct edits to `actions.state_delta` are rejected. A successful writer’s recorded result becomes part of the written value’s provenance only after the tool completes. A tool that returns an `error` field still commits its state writes, because ADK persists them; the written value depends on what the tool consumed but carries no successful-tool evidence. A tool that raises or is cancelled has its state writes rolled back. Callbacks write state through `callback_context.state[key] = value`, in before/after agent, model and tool callbacks. The written value depends on the callback’s own inputs plus the reads it made before the write, and on nothing else. A before-model callback’s inputs are the request messages, an after-model callback’s the model output, a before-tool callback’s the messages that initiated the call, and an after-tool callback’s those plus the tool result. An agent callback consumes no message, so its own state reads are its whole input; artifact access from a callback is rejected. A callback write never carries successful-tool evidence, even when the tool it surrounds succeeds. SASY compares the state change ADK emits on the resulting event against its record of the writes; any other key in that change stops the run. For an agent callback that comparison runs as the callback returns, before ADK builds the event, so a key written straight into `actions.state_delta` there never reaches the session service and cannot outlive the stopped run as a `user:` or `app:` value. A callback that raises has its writes rolled back, and a written value becomes readable elsewhere only once ADK has emitted the event that carries it. When a callback writes the same key an agent fills through its `output_key`, ADK keeps the `output_key` value, because it is applied last; SASY records that value with the model output as its producer, and the callback’s superseded write gains no reader. State writes in the callbacks of parallel branches are rejected, exactly as tool state operations there are. An agent callback that returns content is rejected: that content would replace the agent’s own output and has no observed producer. Artifact writes in callbacks remain rejected. Text artifact support works through ADK’s artifact service interface. The in-memory and file-backed services are tested; other `BaseArtifactService` implementations must preserve the version and metadata semantics below. Tools may use `await tool_context.save_artifact(name, types.Part(text=...))` and `await tool_context.load_artifact(name)`, or the corresponding service methods with the current application, user and session identifiers. Each saved version retains its producer; a load adds only that version to subsequent result and action dependencies. Instruction templates such as `{artifact.report.txt}` and the native `LoadArtifactsTool` retain the same provenance. Before-model callbacks may select or reorder the artifact contents already placed in a request, as intact objects; callbacks cannot load or save artifacts themselves. Listing filenames does not consume every file’s contents. ADK’s artifact store has no rollback: an artifact saved before its tool raises, is cancelled or returns an error stays readable. A later reader of that version depends on what the failed tool consumed, without successful-tool evidence. The built-in `FileArtifactService` supports overlapping saves and loads in qualified Workflow branches. SASY reserves the actual native version number, records its write dependencies, and lets ADK atomically publish the content and metadata together. A read of the latest version selects a published version once and loads that exact version, even if another save finishes meanwhile. Reserved but unpublished versions are not readable. A reader can consume a published write before its producing tool returns; that read inherits the write’s inputs without assuming the tool completed successfully. Cancelling a save cannot undo a file operation already running, but any version it publishes already carries its recorded write ancestry. Canonical file and scope names are required so aliases cannot give the same stored file different identities. Filename listings remain serial; after a join, a listing retains the observed dependencies of the names it returns without consuming file contents. Listings containing a filename with no published version are rejected, including names left behind by failed saves. Other services retain serial access and catalog checks. If an error or a cancellation lands after ADK stored the version but before SASY completed the save’s bookkeeping, SASY then refuses every artifact operation that uses that artifact service object and reports an incomplete save. The refusal follows the service object, not the session, so later SASY sessions sharing that object are refused too; a new service instance, in practice a restart, is what clears it. Another writer sharing the same backend can change the store while this session runs. SASY reads the stored filenames and version numbers when an artifact operation starts and checks them again against the result that operation returns, so a version or filename that appeared or vanished outside this session stops the run rather than being read under the wrong version number or listed with no recorded dependency. Artifact storage is observed internal transport; tool dispatch is the action boundary checked by the reference monitor (RM), the SASY service that authorizes each action. Producers travel with the artifact. Each save asks ADK to store, under a reserved key in the artifact’s own custom metadata, the identifiers of the messages SASY recorded for that version together with a digest, a fixed-size fingerprint, of exactly the text it recorded. A backend that keeps its data on disk keeps that provenance with it. When a load finds a version this process never saw, such as one written by another runner or before a restart, SASY rebuilds that text from the content the load actually returned, requires the digest to match it, and asks the observation service whether those identifiers still hold exactly that text in the current SASY session. Only then does the load depend on the real producer. Stored provenance that is absent, malformed, names messages holding different text, or no longer matches the content leaves the content an unattributed external input, and so does a backend that drops custom metadata. The stored record is written when the artifact is saved, before the saving tool has finished, so it names the message recorded for that version at that point: a reader in another process inherits what the tool had read, without evidence that the tool completed. Completion records a second message for the same version, holding the same text and depending on both that first message and the tool’s result. A record that names the second message instead — which only something with write access to the store’s metadata can leave there — verifies the same way, and the load then carries the completion evidence. That second message exists only for a tool that did finish, so either record leaves the provenance accurate. Metadata your own code passes to `save_artifact` stays rejected, so the reserved entry is the only claim about an artifact’s provenance. For backends other than the built-in file service, a save also stops the run if the backend does not number the new version one above the highest version it already stored. An `AgentTool` child receives ADK’s copied state with per-key provenance: copying the dictionary does not count as reading every value. Only keys the child reads become inputs, including through nested delegations. ADK drops `temp:` keys from this copy. The child may also assign state keys and use `output_key`. When the child finishes, ADK forwards the child’s state change back into the parent’s state. A state change, which ADK calls a delta, is the set of key/value pairs an event reports as newly written. SASY matches every forwarded entry against the child’s own observed writes: the key must have a completed write inside that child holding exactly that value, or the run stops before the parent changes. The forwarded value then keeps the child’s real producers, so a later reader of the key depends on what the child consumed, and gains a child tool’s successful result as evidence only when that tool really succeeded. The delegation’s own result is not a producer of what the child wrote, and a forwarded key nobody reads adds no dependency. SASY applies the whole forwarded change when the child completes, where ADK applies each change as its event arrives, so a child that fails partway leaves the parent value untouched. Forwarding is rejected for `temp:` and ADK-internal (`_adk`) keys, and for a delegation the model requested alongside other tool calls in the same response, which would need the forwarded write ordered explicitly against those calls’ own writes. The native artifact forwarder supports reads and filename lists, preserving the selected artifact’s ancestry; forwarded artifact writes are not yet supported. ### Values from another SASY session [Section titled “Values from another SASY session”](#values-from-another-sasy-session) Retain the runner and services for continued conversations. Each SASY session records its own separate graph. Services outlive a session, so a later session can read a key or artifact an earlier one produced: `app:` and `user:` state and a shared artifact store are the common cases. Such a value enters the reading session as an unattributed external input, the same message shape used for values that were already there when observation began, with an added `origin` field naming that it came from another SASY session. The producing session’s identifier is not recorded, because it may belong to a different tenant or entity and naming it would carry that identity across. The reading session never reuses the other graph’s message identities; it records the value again under its own. Reading the same value twice in one session yields one message, so a policy sees one input rather than two. Nothing else crosses. The other session’s ancestry stays behind, and so does any evidence it holds: an approval a tool granted there does not authorize an approval-requiring action here. Taint (a dependency on untrusted content) does not cross either, so a value that was tainted in the producing session arrives here with a clean, parentless history. A policy that denies on taint should treat external inputs conservatively, for example by refusing to let an input labeled `"origin": "another SASY session"` reach a sensitive action, rather than reading its empty ancestry as evidence that the value is safe. Resource access must remain in its observed task. Application-created tasks, parallel agents outside the qualified Workflow artifact path and concurrent invocations sharing mutable services need explicit dependency and ordering support; unsupported access is rejected. ADK’s in-memory artifact backend is intended for development, not durable production storage. Jinja templates, callback artifact writes, binary artifacts, caller-supplied artifact metadata, artifact deletion and version-metadata methods, and experimental dynamic-instruction routing for artifact tools remain unsupported. Credential, memory and UI methods on `ToolContext` also require their own observation and action boundaries. Access to the raw context session is blocked. ## Application-created child tasks [Section titled “Application-created child tasks”](#application-created-child-tasks) Native agent communication is handled by the adapter. Tasks created inside your own tool or orchestration code need explicit registration of their inputs and outputs. Register each child response with the observation API, using its real consumed inputs. Then add only the response the parent actually consumes: ```python from sasy.instrumentation.adk_tasks import consume_events_async from sasy.proto.observability_pb2 import EventSnapshot # Inside an observed ADK tool or callback. Your custom orchestration has already # registered response_event and its dependencies, returning response_id. await consume_events_async([ EventSnapshot( event=response_event, base_id=response_id, reuse_dependencies=True, ) ]) ``` The helper verifies the unchanged response against the server in the current SASY session. Its ancestry then reaches subsequent action checks, state writes and the parent output. Use `consume_events` in synchronous code. Starting a child Python task does not authorize it to mutate its parent’s dependency scope; await its response and consume it in the parent task. Before passing the parent’s current inputs into custom orchestration, use `await sasy.instrumentation.dependencies.resolve_inputs_async()` to include any pending state reads. The synchronous counterpart is `resolve_inputs`. A child response carries its own ancestors. Registering every sibling result as a parent dependency would incorrectly supply context the parent never consumed. This helper covers response consumption, not arbitrary task bodies. A custom executor still needs its own task-local input scope and checks at its protected action boundaries; inheriting the parent’s context is insufficient. A value read from another SASY session arrives as a labeled external input; see [values from another SASY session](#values-from-another-sasy-session). These helpers do not carry ancestry between sessions. ## OpenTelemetry [Section titled “OpenTelemetry”](#opentelemetry) The adapter adds SASY message IDs, session/entity IDs and RM decisions to ADK’s native model and tool spans. Configure the shared SASY exporter before running agents: ```python from sasy.instrumentation.otel import OTelConfig, configure_otel configure_otel(OTelConfig(service_name="my-adk-agent")) sasy.instrument() ``` Enrichment adds identifiers and bounded outcomes, not prompt or argument copies. ADK’s own telemetry configuration controls its other attributes. Multipart outputs get child span links for every output message. `sasy.dispatch.outcome` describes model/tool dispatch; the native span status covers the surrounding ADK pipeline, including callback failures. Session/entity scope is captured before batch export so concurrent sessions do not share trace ownership. ## Payment example [Section titled “Payment example”](#payment-example) `examples/adk-separation-of-duties` runs requester, reviewer and payer agents with a real SASY policy. Approval is bound to the request ID, payee and exact amount. The default scripted models need no provider credentials; `--live` exercises Gemini 3.8 Flash with the same synthetic tools and an in-memory ledger. Set `SASY_ADK_LIVE_MODEL` to choose another Gemini model. No money moves. The example demonstrates application role separation. Its configured `reviewer` label is not evidence that an independent person approved the payment. # LangChain agents > What the LangChain adapter checks, how to enable it, and what it does not cover. Call `sasy.instrument()`, then build your agent with LangChain’s `create_agent`: SASY records the inputs behind the agent’s tool calls and enforces a policy before each tool runs. Start with the complete [LangChain example](/examples/#langchain-information-flow), then use this guide for supported configurations and multi-turn conversations. Custom LangGraph `StateGraph` applications need [their own adapter](/instrumentation/). With the LangChain adapter enabled, every tool call of a `ToolNode` that SASY did not build is refused inside a SASY session (see [tools SASY does not protect](#tools-sasy-does-not-protect)). A tool that graph code calls itself, not through a `ToolNode` (for example the hand-written tool node of the LangGraph quickstart), is not checked at all. ## At a glance [Section titled “At a glance”](#at-a-glance) **What you get** * Every tool call the agent makes is checked against your policy immediately before the tool function runs. * The check sees the call’s [ancestry](/concepts/): every message the requesting model output was computed from, through earlier tool results and drafting steps, across turns and across sub-agents called from tool bodies. * A denied call does not run. The model receives an error tool message and can carry on. **How to enable** 1. Follow the [quick start](/get-started/) to run the engine and install the SDK. Run your Python entry point with `python your_agent.py` in the environment where you installed the SDK and framework. 2. Call `sasy.instrument()` once at startup, after any explicit `sasy.configure(...)` and before you build the agent. When LangChain is installed, this makes LangChain’s `create_agent` build SASY’s agent. 3. Build the agent with `create_agent(model, tools)` from `langchain.agents`. 4. Run it inside `with sasy.session(policy=Path("policy.dl")):`. That is the whole integration, and it is the same for every agent you build this way. Your model’s HTTP requests to its provider are not checked unless you also pass `http=True`; see [model egress](#model-egress). ## Information-flow example [Section titled “Information-flow example”](#information-flow-example) The [LangChain example](/examples/#langchain-information-flow) uses a scripted model to read a document, draft a summary, and request publication. Documents are synthetic and publication writes to an in-memory list; LangChain execution, dependency recording, and policy checks are real. In this example, we tighten the security policy from the [quick start](/get-started/): confidential ancestry blocks external publication, even after a drafting step rewrites the text. The [example policy](https://github.com/sasy-labs/sasy/blob/main/examples/langchain-information-flow/policy.dl) contains this rule: ```prolog .decl ConfidentialInput() ConfidentialInput() :- CurrentDepends(id), ToolResult(id, "read_confidential", _). // @deny_message: External publication depends on confidential information Unauthorized(idx) :- Actions(idx, a), IsTool(a, "publish"), a = $CallTool(_, args), @json_get_str(args, "destination") = "external", ConfidentialInput(). ``` `CurrentDepends` follows the inputs behind the model output requesting `publish`. It includes the confidential read through the later draft, so the rule denies the external send. The policy allows internal publication and external publication based only on public input. ## Try a live model [Section titled “Try a live model”](#try-a-live-model) Both the single-agent and supervisor examples can let a live model choose their tool calls. Add `OPENAI_API_KEY=...` to the repository-root `.env`. The demo loads it without overriding an exported value. The repository’s `all` extra includes the supported provider integration: ```bash uv run examples/langchain-information-flow/demo.py --live uv run examples/langchain-information-flow/supervisor.py --live ``` Live mode defaults to `gpt-4.1-mini`. Set `SASY_LIVE_MODEL` in `.env` or pass `--live-model MODEL` to choose another model. Only synthetic documents are used. A model may choose not to publish; inspect the tool results to distinguish a denied request from one it never made. Live mode enables HTTP checks. The example policy allows `api.openai.com`, and the provider request, including its API key, passes through your engine. Use an engine you trust and review that rule before using real confidential documents. See [model egress](#model-egress) for the boundary and [supported versions](#supported-versions) for provider restrictions. ## Run a supervisor with parallel workers [Section titled “Run a supervisor with parallel workers”](#run-a-supervisor-with-parallel-workers) The [supervisor example](https://github.com/sasy-labs/sasy/blob/main/examples/langchain-information-flow/supervisor.py) runs three native LangChain agents. By default, scripted models make the run repeatable without a provider key. A supervisor delegates research and a public review in parallel, then attempts to publish their combined report. The same policy follows confidential information through the research agent’s answer and denies external publication before the simulated effect. The public reviewer does not acquire its sibling’s confidential dependencies. With the engine and SDK environment configured as for the single-agent example: ```bash uv run examples/langchain-information-flow/supervisor.py uv run examples/langchain-information-flow/supervisor.py --public uv run examples/langchain-information-flow/supervisor.py --async ``` The default confidential/external case is denied; `--public` or `--destination internal` permits publication. Use `--live` for a real model in all three agents, including their delegated research and review. This needs `OPENAI_API_KEY` in `.env` and makes paid provider requests; the document reads and publication remain simulated. Live model choices can vary between runs. The console trace labels each agent’s model output, tool call and result. ## Build an agent [Section titled “Build an agent”](#build-an-agent) Use the [SDK usage pattern](/sdk/#langchain) with your configured model and tools. The [LangChain example](/examples/#langchain-information-flow) supplies a runnable scripted example. `sasy.instrument()` enables SASY for each supported framework that is installed; pass `langchain=True` to make a missing or unsupported LangChain an error instead of a skipped framework (see [supported versions](#supported-versions)). `sasy.instrumentation.langchain.create_agent(model, tools)` is the explicit, legacy interface. It takes the same construction arguments and works without `sasy.instrument()`, but returns a `SasyAgent` with `invoke`/`ainvoke` only. The instrumented LangChain factory returns a native compiled graph. Use `await agent.ainvoke(...)` for asynchronous execution. SASY enforcement requires an active session, either an explicit `sasy.session(...)` or the opt-in process default. The explicit `SasyAgent` interface raises outside a session; instrumented native graphs retain native behavior outside one. Each protected invocation is a separate run; to continue a conversation, pass the message objects the previous invocation returned back in. The caller owns and ends the SASY session; concurrent invocations keep separate observation and dispatch state. ## What `sasy.instrument()` changes [Section titled “What sasy.instrument() changes”](#what-sasyinstrument-changes) `sasy.instrument()` changes LangChain in two ways, for the rest of the process. Calling it again changes nothing further. ### `create_agent` builds a SASY agent [Section titled “create\_agent builds a SASY agent”](#create_agent-builds-a-sasy-agent) `langchain.agents.create_agent` (also importable from `langchain.agents.factory`) is replaced by a version that builds the agent through SASY’s adapter. Code that ran `from langchain.agents import create_agent` before `sasy.instrument()` gets the SASY version too: SASY updates every module-level name that refers to LangChain’s original function. A reference kept anywhere else, such as a class attribute, a dictionary or a `functools.partial`, still holds the original, so call `sasy.instrument()` before any code stores `create_agent`. The instrumented factory returns LangChain’s native `CompiledStateGraph`. Agents can be built outside a session and invoked inside one. The following restrictions apply to protected execution in an active SASY session; unscoped execution retains native LangChain behavior. Supported execution methods are `invoke`, `ainvoke`, `batch` and `abatch`. `get_graph()` exposes its topology. `with_config()` preserves the guarded invocation boundary; supported settings are `recursion_limit`, `max_concurrency`, `tags`, `metadata`, `run_name` and `run_id`. Each invocation, including each batch item, has its own dependency scope. Checked delegation tools can use `batch` and `abatch`; child runs retain the caller’s ancestry, and their returned answers become dependencies of the tool result. All items start from the ancestry available before the batch, so an earlier item’s answer does not become an input of a later sibling. Settings bound with `with_config()` also apply to batches. Batch configuration can be one supported config or a list of configs, one per input. Explicit callbacks and checkpoint settings remain unsupported. `return_exceptions=True` is refused before any batch item runs: failed-run exceptions can contain data whose provenance is not yet tracked as a result. The inherited `batch_as_completed` and `abatch_as_completed` methods are also refused; use `batch` or `abatch` instead. Returned messages carry verified provenance as described below. You can pass `{"recursion_limit": 12}` as the second argument to `invoke`/`ainvoke`; the previous `recursion_limit=12` spelling also works. A native graph does not enable every LangGraph feature. Direct `stream` and `astream`, embedding the compiled agent as a custom graph node, callbacks, checkpoint configuration, and graph-structure edits are refused. Sub-agents invoked from checked tool bodies are supported. Custom middleware, persistence, state-based handoffs and Deep Agents are not supported yet. The replacement takes four arguments: * `model`: a chat model object (a `BaseChatModel` instance such as `ChatOpenAI(...)`), or a model name such as `"openai:gpt-5"`. A name is turned into a model object exactly as LangChain’s own `create_agent` does it, with `langchain.chat_models.init_chat_model`, and the resulting model is then checked like any other (see [supported versions](#supported-versions) for the model configurations that are refused). * `tools`: plain functions or `StructuredTool` instances. * `system_prompt`: a string or a `SystemMessage`. LangChain turns a string into a `SystemMessage` with that content, so a string and a `SystemMessage` with the same content and no other fields are recorded identically. Any other field a `SystemMessage` carries (its own `name`, `id` and so on) is recorded as given. A `SystemMessage` is copied when the agent is built: changing your message object afterwards does not change what the agent sends, just as with a string. Any other type raises `ValueError`. * `name`: the name of the LangGraph graph that LangChain compiles, as in LangChain’s `create_agent`. LangChain also puts this name on every message the model produces, and SASY records those messages under that agent name (in place of the default `langchain`), so a policy that matches on agent names sees it. Every other LangChain `create_agent` argument — `middleware`, `response_format`, `state_schema`, `context_schema`, `checkpointer`, `store`, `interrupt_before`, `interrupt_after`, `debug`, `cache` and `transformers` — raises `ValueError` naming the argument when it is given anything other than its default value, because the adapter cannot record what that feature does. The same argument passed at its default (for example `checkpointer=None`) is accepted. An argument LangChain’s `create_agent` does not take at all raises `TypeError`. ### Tools SASY does not protect [Section titled “Tools SASY does not protect”](#tools-sasy-does-not-protect) LangGraph runs an agent’s tools through a `ToolNode`: the step of the graph that calls the tool the model asked for. When the LangChain adapter is enabled (you did not pass `langchain=False` to `sasy.instrument()`), one rule applies inside a `with sasy.session(...)` or `with sasy.global_session(...)` block: **tools run only in agents SASY builds.** Every tool call of a `ToolNode` that SASY did not build is refused with `InstrumentationError` (from `sasy.instrumentation.langchain`) before any tool-call wrapper or tool body runs. It does not matter which tool the model asked for, whether the node knows that tool’s name, whether the tool itself is one SASY wrapped, or whether the node has a tool-call wrapper (`wrap_tool_call` or `awrap_tool_call`, which is how middleware reaches it). The error stops the run: LangGraph’s `handle_tool_errors` setting does not turn it into a tool message. “Agents SASY builds” means the agent that LangChain’s `create_agent` returns after `sasy.instrument()`, and the one `sasy.instrumentation.langchain.create_agent` returns. Their `ToolNode` runs every call through SASY’s own middleware, which checks it against your policy and reports a tool name the model invented back to the model without running anything. This catches an agent built without SASY at its first tool call, instead of letting it act unchecked. Such agents include one built with LangChain’s original `create_agent` held from before `sasy.instrument()`, one built with LangGraph’s `create_react_agent`, and your own `StateGraph` with a `ToolNode`. None of them can run tools inside a SASY session; custom LangGraph graphs are not supported inside a session yet. Build the agent with `create_agent` after `sasy.instrument()` instead. If you write [your own adapter](/instrumentation/) for a graph that runs tools through a `ToolNode`, pass `langchain=False` to `sasy.instrument()`; the check is then not installed, and `create_agent` is not replaced either. What the check does not cover: * Outside a SASY session nothing is refused, and an agent built without SASY runs its tools unchecked. * A tool that your own graph code calls directly, not through a `ToolNode`, is not checked. This includes the hand-written tool node of the LangGraph quickstart, which calls `tool.invoke` itself, and functional-API (`@task`) code that calls a tool. * The check needs the `langchain` package. With LangGraph installed but not `langchain`, the adapter cannot load. `sasy.instrument()` then skips it, so `ToolNode` tools run unchecked, and the first LangGraph graph the application runs issues a `SasyInstrumentationWarning` saying that LangChain and LangGraph agents will NOT be checked; with `langchain=True`, `sasy.instrument()` raises an error instead. Install the `langchain` extra, or pass `langchain=False` if the application does not use LangChain or LangGraph. ## Compatibility [Section titled “Compatibility”](#compatibility) **Supported scope.** The adapter covers the agent that `create_agent` returns after `sasy.instrument()`, or that `sasy.instrumentation.langchain.create_agent` returns. Unsupported configurations are refused; external execution paths need their own checks: * Custom middleware, callbacks, checkpointers, streaming delivery, dynamic tools, injected state, runtime or store arguments, custom `BaseTool` subclasses, state-mutating `Command` results and arbitrary LangGraph nodes. * Tools declared `return_direct=True`, which end the run on their own result. The run would then have no final model answer, and the text a caller reads back would not depend on the tool result it came from. Setup refuses them. * Tools whose arguments are Pydantic models, and tools taking a `RunnableConfig`, runtime, store or callbacks parameter. Setup refuses them. * Anything the model provider does on its own side: provider web search, code execution, provider-side tools. * Calling your original tool objects directly. Only the agent `create_agent` returns is guarded. * The model’s own HTTP request to its provider, unless you pass `http=True` to `sasy.instrument()` (see [Model egress](#model-egress)). **Tool outcomes** * When a call is denied, the model receives an error tool message that names the tool and carries your policy’s denial reasons and suggestions. Write them for the model to read, and keep out of them anything the model should not see. * A denial inside a sub-agent does not fail the outer delegation. The inner agent normally answers anyway, and the outer tool result looks successful. * A tool that returns the string `"Error: ..."` without raising counts as a successful result, and so produces `ToolResult` evidence. ### Model egress [Section titled “Model egress”](#model-egress) The adapter checks tools. The HTTP request your model client sends to its provider (its “egress”) is not checked by default. SASY’s HTTP hooks check it when you enable them with `sasy.instrument(http=True)`; they are off by default. With them on, requests made with `httpx` or `requests` go through the engine, which checks each one against the policy and can inject credentials (add an API key the engine holds to the request). The engine then sees each request, including your provider API key, so enable the hooks only with an engine you operate. Your policy must then allow the host, or the model’s request is denied: ```prolog IsAuthorized(idx) :- Actions(idx, a), QueriesHost(a, "api.openai.com"). ``` ## What is recorded and enforced [Section titled “What is recorded and enforced”](#what-is-recorded-and-enforced) Model outputs depend on every actual input message, including the system message. Structured message content and tool-call specifications are preserved. A tool result depends on the model output that requested it. Later model calls consume those results, preserving information flow through multiple processing steps. The adapter does not add dependencies merely because another message is available in a session. Tools are ordinary functions or `StructuredTool` instances. Authorization sees the arguments after Pydantic validation, coercion, and function defaults. The adapter checks and dispatches the same detached argument objects, preventing an external mutation during an asynchronous check from changing what runs. Denials and unsupported required transforms produce error tool messages without executing the function. (A transform is a change the policy requires before an action runs, such as credential injection; the adapter cannot apply one to a tool call, so a policy that requires one for a tool call is reported as an error. The reference monitor applies transforms to HTTP requests routed by `sasy.instrument(http=True)`.) Recording failures and reference-monitor failures stop the run. Error results do not emit successful `ToolResult` provenance. Successful results include the tool name and normalized dispatch arguments. Within one `invoke`, a LangChain message ID identifies one message. Across invocations it does not: a message in a new `invoke` is treated as new even if it reuses an old LangChain ID, unless it is one of the message objects a previous `invoke` returned (see Multi-turn conversations below). Before each model call, the adapter checks the actual consumed messages and resolves them in one batch: compact references for known generated messages, full snapshots for new observations and for user and system messages. It uses the returned immutable version IDs. Repeated unchanged snapshots keep their IDs without graph or synchronization writes. Version comparison covers the whole message, because [the recorded node holds the whole message](#what-a-node-holds): content and its type, role, name, the LangChain `id`, tool calls parsed and unparsed, tool-result status and `tool_call_id`, every `additional_kwargs` entry and all response metadata. Two different messages therefore never produce one recorded node, and no edit to a message leaves the node it was recorded as unchanged. Changes to the fields outside the graph’s role/name/content/tool-call projection are additionally reported as such before the round trip, rather than only as a rejected version. Generated messages re-observed as inputs must still match their recorded computation. Unexplained content edits and changes to recorded tool-call specifications are rejected. Existing tool results retain their actual dispatch inputs and arguments. Server version identity survives retries and restart, and a message’s identity travels with the message object itself, as described under [carrying messages between invocations](#carrying-messages-between-invocations). Model observation alone is not network mediation. SASY’s HTTP hooks (off by default; enabled with `sasy.instrument(http=True)`) cover supported `httpx`/`requests` provider paths; authorize the specific endpoint. Custom transports need their own dispatch checks. Localhost HTTP bypass behavior also applies. This adapter does not redact streamed tokens. ## Carrying messages between invocations [Section titled “Carrying messages between invocations”](#carrying-messages-between-invocations) When an invocation ends, the adapter marks each message it recorded: it writes that message’s graph node, and the alias the node was recorded under, into the message’s `response_metadata` under the reserved key `sasy`. A mark is bookkeeping, not content. It is removed from the copy of the conversation handed to the model, so no provider ever receives it, and it is ignored when the adapter compares auxiliary message fields. Pass those same message objects back — as `result["messages"]` plus a new user message, carried through your own state, or restored from a store your application keeps — and the next invocation restores each message’s identity. It sends the mark to the engine as a compact reference: a short form that names an existing immutable version instead of recording the message again. The engine accepts it only if that version exists for that alias, in this session, for this principal, and its stored content hash equals the hash of the content the adapter just computed. Multi-turn chat therefore keeps its history: a tool result read in turn one is still an ancestor of an action attempted in turn three. A mark that does not verify buys nothing. An invented node, a mark copied onto different text, an edited message, a mark taken from another session, and a tool result whose mark claims a tool that never ran all fail the check, because to pass it the message would have to *be* the recorded message. What the engine hashes is [the recorded node](#what-a-node-holds), which holds the whole message, plus its role, agent and tool entries, so changing anything about a recorded message makes its mark fail — including a tool result’s `tool_call_id`, the message’s own `id`, and an `additional_kwargs` entry no released provider client has ever read. Nothing about a message is outside the hash. Tool calls carried on an admitted assistant message are history: this run will not dispatch them. Identity is checked on top of that, not instead of it: the engine accepts a mark only as a version of the alias that mark names, so a message cannot inherit another message’s node by taking its id either. A message is recorded as being of unknown origin only when the engine checks its mark and rejects it. If the engine cannot be reached, times out or errors, nothing has been decided, so the invocation stops with an error rather than carrying on with ancestry it simply failed to look up. The adapter reads the engine’s `INVALID_ARGUMENT` answer as the rejection. The engine also returns that status for a few transport-level problems with the request itself, such as a text containing a NUL byte, so a message rejected for one of those is recorded as being of unknown origin rather than stopping the run. ### What a node holds [Section titled “What a node holds”](#what-a-node-holds) The adapter records message content for policies and a canonical snapshot in metadata so the engine can detect changes to the source message. See [records for policies](/reference/langchain-records/) for field paths, policy examples, and representation limits. ### Inputs of unknown origin [Section titled “Inputs of unknown origin”](#inputs-of-unknown-origin) Where the adapter cannot establish where a message came from, it continues and says so instead of refusing. An assistant or tool message with no mark, or with a mark that does not verify, is recorded as a node of its own holding a JSON object `{"s:langchain_message": ..., "s:provenance": "unattributed external input", "s:value": ...}` — the same encoding as above, prefixes and all — with the user role, no ancestors and no tool evidence. Its metadata is the whole message, exactly as for a recorded message. `langchain_message` is the whole message, as above; `value` repeats its content so a policy can read what the run consumed without unpacking the message. The model call that reads it depends on that node, so a policy can see that the run consumed text of unknown origin and decide what to allow. A supplied tool result is never evidence that the tool ran. The `s:provenance` key is what a policy reads to tell this text from the content of a recorded message. The two shapes also cannot produce one node, whatever a message’s content is made to spell: the metadata is the message either way, and these two events carry different texts for the same message. So an argument value the model can read back — a secret pasted into a historical search query, say — is text a policy can match on either way, not something only the provider sees. The common `UnattributedInput` helper reads the unprefixed `provenance` key. For LangChain’s canonical envelope, add these rules to your policy before using `DependsOnUnattributedInput()`: ```prolog CurrentDependsPolicyRelevant() :- IsTool(_, "publish"). UnattributedInput(id) :- Current(id), SentMessage(id, msg), @json_get_str(msg.contents, "s:provenance") = "unattributed external input". UnattributedInput(id) :- CurrentDepends(id), SentMessage(id, msg), @json_get_str(msg.contents, "s:provenance") = "unattributed external input". Unauthorized(idx) :- Actions(idx, a), IsTool(a, "publish"), DependsOnUnattributedInput(). ``` These rules cover both direct inputs and ancestors. Change `publish` to the sink your policy protects, and retain its ordinary allow rules. The generic helper alone does not recognize LangChain’s prefixed marker. This canonical envelope has no origin field, so match its provenance marker rather than relying on `UnattributedInputOrigin` to identify it. Which tool calls a message records is the rule its provider client applies, not the sum of the places a call can hide. `langchain-openai` uses one source and ignores the rest: the parsed and the unparseable tool calls together when the message carries any, otherwise the raw `additional_kwargs["tool_calls"]`, otherwise the legacy `function_call`. The recorded tool list follows that rule, so a message carrying both a parsed call and a raw one records the parsed call alone — the call the provider is actually asked to make. The ignored source is still part of the recorded content, where adding it breaks the message’s mark; it is simply not a requested tool. Two hand-offs still lose provenance. **Flattened text**: if you carry only the text of an answer (`str(result["messages"][-1].content)`) into a new `HumanMessage`, there is nothing to verify, and it is recorded as an ordinary fresh user input with no ancestors. **Rewritten messages**: shortening a message’s content, or rebuilding it without its `response_metadata`, invalidates or drops its mark, and the message becomes an unattributed external input. Whole messages dropped by `trim_messages` or `RemoveMessage` change nothing for the messages that remain. ## Supported versions [Section titled “Supported versions”](#supported-versions) The adapter is tested against, and the extra pins, LangChain 1.4.0, langchain-core 1.6.3, LangGraph 1.2.11 and langgraph-prebuilt 1.1.0. Setup refuses a different version rather than silently losing a hook it needs. When LangChain is installed at another version, `sasy.instrument()` skips the adapter. The first time the application then calls `langchain.agents.create_agent` or runs a LangGraph graph (`invoke`, `ainvoke`, `stream` or `astream`), SASY issues a `SasyInstrumentationWarning` (a Python warning, also logged, once per process) saying that LangChain agents will NOT be checked by SASY. An application that has LangChain installed but never uses it gets no warning. Pass `langchain=True` to make this an error, raised before anything is changed, or `langchain=False` if your application does not use LangChain, which also silences the warning. The example’s live mode uses langchain-openai 1.6.2. The factory intentionally does not accept custom middleware, callbacks, injected state/runtime/store arguments, dynamic tools, checkpointers, streaming delivery, or arbitrary graph nodes. It rejects custom `BaseTool` subclasses, tools declared `return_direct=True` and state-mutating `Command` results. These paths need additional observation and dispatch contracts before they can be supported. Provider-retained conversations, previous-response IDs, remote prompt references, automatic previous-response reuse, and raw provider body overrides are rejected. Their hidden inputs cannot be resolved into the observed graph by this adapter. Model configuration is checked both at setup and before each model dispatch. A tool must consume only the arguments it was given. If a tool reads a file, a database or another message on its own, record those inputs yourself or the policy will not see them. Your tool code and your model implementation are trusted code: SASY checks what a tool is asked to do, not what it then does. ### One invocation is the tracked unit [Section titled “One invocation is the tracked unit”](#one-invocation-is-the-tracked-unit) Dependencies are tracked inside a single `invoke` or `ainvoke`, and across the delegations that an invocation starts itself. Five consequences follow: * **Sub-agents called through tools are tracked.** A guarded agent may be invoked inside the body of a guarded tool of another guarded agent (the “agent as a tool” or supervisor pattern), in the same `sasy.session(...)`. Every model call of the inner agent is recorded as depending on the tool call that started it, whatever the inner agent was handed — a fresh question, a conversation restored from marks, or text of unknown origin — so everything the outer agent had read is in the inner check’s ancestry: the set of messages an action was computed from. The tool result the outer agent then reads depends on the inner agent’s final answer, so what the sub-agent found reaches the outer agent’s later checks. A run always ends on a model answer, which is why a tool declared `return_direct=True` is refused at setup. Delegation nests up to eight levels deep; deeper delegation raises an error. Invoking a guarded agent anywhere else inside a run — with no guarded tool body around it — raises an error, because the inner input would have no observed cause. * **One tool body is one computation.** Different tool calls made by the same model message (for example two parallel `delegate` calls) never share dependencies: one call’s sub-agents contribute nothing to the other call’s ancestry. Within a single tool body the rule is deliberately coarse: a body may run a small workflow, calling agent A and passing A’s answer as plain text to agent B. Plain text carries no identity, so every inner run started by a body depends on the tool call plus every inner answer already returned to that body, and the tool’s result depends on all of them. Timing decides this, not your code: a sub-agent depends on every sub-agent answer that had already come back to the same tool body when it started. Two sub-agents started together with `asyncio.gather` are independent. Started one after the other, the second depends on the first, even if you never passed the first answer to it. A tool is checked once, before its body runs. A body that delegates and then acts on the answer itself is not checked again for that action unless the action is its own checked call: an HTTP request through SASY’s HTTP instrumentation, or a direct reference-monitor check. Those checks do include the answers already returned to the body. A check made *inside* a sub-agent belongs to that sub-agent’s run instead, not to the body — including the HTTP request the sub-agent’s model sends, which is checked with that run’s own inputs and the tool call that started it. Prefer a separate guarded tool for the action, so the model’s request for it is checked with the delegated answer in its ancestry. Two limits follow from Python’s context variables, which carry the SASY session and the body’s inputs. Work a body starts and leaves running is refused if it makes a check, or starts a sub-agent, after the body has returned, and a sub-agent still running when its body returns is stopped at its next model call or tool call. A tool call that has already passed its check when the body returns is not interrupted; it runs to completion and its result is then refused. Await the sub-agents a body starts before returning. Work a body hands to its own thread pool with a plain `executor.submit(fn)` has no session and no inputs at all. Use `asyncio.to_thread(fn)`, which copies the context, or capture the context in the body and run the function inside it: `executor.submit(contextvars.copy_context().run, fn)`. * **Side channels need explicit registration.** The tool-body rule covers answers returned to the body that started the sub-agent. It does not cover an answer that leaves a body another way — a global variable, a file, a database or a cache — and is read by a different tool call or a later invocation. Inside the tool body that reads it, register the message objects you read: ```python from sasy.instrumentation.langchain import consume_messages def recall() -> str: """Return the answer kept from an earlier run.""" consume_messages([saved_answer]) # a message returned by a guarded agent return str(saved_answer.content) ``` A message whose mark verifies keeps the ancestry it already has. An assistant or tool message without a verified mark is recorded as an unattributed external input; a user or system message without one is recorded as a new input, whose ancestor is the tool call that started the run when this is a delegated run, and which has none at the top level. A message this run has already recorded keeps what it has, so handing back a copy that lost its `response_metadata` does not downgrade it. That holds as long as it is the same message: register a *different* message under an identity the run recorded — the same `id`, other text — and the new one is recorded as an unattributed external input of its own instead of being taken for the first. Nothing the body read is missing from the graph, and the new text inherits nothing the first message established. Registering the same replacement twice records it once. The identity the replacement is given is a fresh one the run mints, not a name derived from the message: a derived name is one that could be worked out and occupied in advance, and the run would then find the identity already taken. The call only adds dependencies, and only to the tool body that makes it. * **An answer handed on as plain text loses its history.** If you pass an agent’s answer into another invocation as the text of a new user message, SASY records it as a fresh user input with no ancestors; pass the message objects instead. A delegated run that opens a different `sasy.session(...)` is a partial case: sessions do not share message identities, so that run is recorded as independent work, its own input has no ancestors, and what the outer agent had read is not in its checks. Its answer is not lost, though. The calling tool body records the answer in its own session as an unattributed external input — the same node shape used for any message whose origin cannot be established — and the tool’s result depends on that node. A policy sees that the result came from outside, with the answer’s text, but not which tools produced it. Checks made inside that run, including the HTTP request its model sends, resolve against that run and its own session. Keep a rule that depends on tool evidence inside one session. * **Later turns keep their history when messages are passed back.** An invocation accepts earlier assistant and tool messages. Each one is admitted with the ancestry it already has when its mark verifies, and recorded as an unattributed external input when it does not. A denied or failed sub-agent run adds no successful-tool evidence: the denied call is recorded as a failed tool result. The denial does not travel out of the sub-agent, though. LangChain hands the inner agent an error tool message, the inner agent normally carries on and answers anyway, and the outer agent then receives an ordinary successful `delegate` result whose ancestry holds the failed call rather than a successful one. If a delegation must fail when an inner action is denied, check the delegating tool itself as well. Pass the agent returned by `create_agent` to the rest of your application. The factory guards copies of your tools, so the original tool objects you still hold are not checked if you call them directly. ### Provider-side tools and context [Section titled “Provider-side tools and context”](#provider-side-tools-and-context) The factory accepts any LangChain chat model. What a provider does on its own side is out of scope: if a model or option makes the provider search the web, run code or call its own tools, SASY does not check that action and its results do not appear as dependencies of the model’s answer. One group of options is rejected, because it changes the input the model receives after the adapter has recorded it: for the tested client, `ChatOpenAI`, these are retained conversations, previous-response IDs, remote prompts, replacement inputs or instructions, provider-side tool lists and raw body overrides. The adapter does not know the equivalent options of other provider clients; review them yourself. ### Tool shapes refused at setup [Section titled “Tool shapes refused at setup”](#tool-shapes-refused-at-setup) Arguments are recorded as JSON, so a tool that cannot present its arguments that way is refused when you build the agent, with an error naming the tool and the argument. Use JSON-native argument types: strings, numbers, booleans, lists and dictionaries. * An argument declared as a Pydantic model. A model instance has no JSON form in the check, so the call would stop the run when its arguments are serialized. Take the fields as arguments of their own, or a JSON string the tool parses. * An injected-state argument, including the optional form `Optional[Annotated[int, InjectedState("key")]]` with a default. The optional form reaches the model as an ordinary parameter and fails validation at every call, so the body never runs and no check is ever made. A tool that takes a `RunnableConfig`, `runtime`, `store`, `callbacks` or `run_manager` parameter is refused at setup for the same reason: the adapter checks the arguments the tool is actually given. ### A tool the model invented [Section titled “A tool the model invented”](#a-tool-the-model-invented) If the model asks for a tool that does not exist, the framework has nothing to run. Nothing runs and nothing is checked, and the model is told — `Error: no tool named X is available.` — so it can correct itself, as it would without the adapter. The failed result is recorded with no successful-tool evidence. A dispatch that does not match the model output the adapter recorded is a different matter and still stops the run. A tool result counts as successful when LangChain marks it so. A tool that returns the text “Error: …” without raising is recorded as a successful result. When a call is denied, the model is told which tool was denied, the reasons the policy gave, and any suggestions it carried. The [`examples/langchain-information-flow`](https://github.com/sasy-labs/sasy/tree/main/examples/langchain-information-flow) example includes allowed and denied publication, transitive dependencies through a drafting tool, a deterministic scripted model, and optional live model execution. All data and deliveries are synthetic. Its policy explicitly permits the live provider to process that data. # Langroid > What the Langroid adapter checks, how to enable it, and what it does not cover. ## At a glance [Section titled “At a glance”](#at-a-glance) **What you get** * Langroid agent responses and task handoffs are recorded across cooperating agents. Custom tools and Langroid’s built-in orchestration tools are checked against your policy immediately before they run. * Model inputs, tool inputs and the framework’s own history truncation are recorded, so a check sees the call’s ancestry: every message the requesting model output was computed from. * A reply holding several tool calls is recorded call by call. Langroid runs them all and hands back one combined result; each tool’s own result is recorded as a node of its own, carrying the call it came from, and the combined result is recorded as computed from all of them. A rule that finds a read through its tool result therefore sees every read in the reply, however many calls the model chose to make. Two calls with the same name and the same arguments are two calls: each gets its own result, because the second may return different data from the first. * A tool handler may return another tool call, which Langroid runs at once. The first tool’s result is that returned call, recorded as such, and the second call is checked with the first tool’s result among what it was computed from — so a rule that denies a send computed from a secret read still sees the read. The second tool’s result is recorded as computed from the first’s, and the reply is recorded as computed from the end of the chain. A chain of any length is recorded the same way. * A tool call may not name its own handler. A model’s tool JSON can carry an extra `_handler` field, and older Langroid ran the agent method named there while the call was checked and recorded under its own name. A call that names a handler other than the one its tool class declares is refused, and neither method runs. The handler a tool class declares for itself keeps working. * With `sasy.instrument(http=True)`, outbound HTTP requests made with `httpx` or `requests` go through the same check. HTTP checks are off by default. **How to enable** 1. Follow the [quick start](/get-started/) to run the engine and install the SDK. Run your Python entry point with `python your_agent.py` in the environment where you installed the SDK and framework. The extra accepts Langroid 0.67.1 through 0.67.8; 0.67.8 is the version the test suite runs against. 0.67.1 is the floor because earlier versions let a tool call redirect itself to another agent method. 2. Call `sasy.instrument()` once at application startup. This enables the Langroid adapter when Langroid is installed, along with the adapter for any other supported framework that is installed. If Langroid is installed but the adapter cannot import it, `sasy.instrument()` skips the adapter. The first time the application then runs a Langroid `Task` or asks a `ChatAgent` for an LLM response, SASY issues a `SasyInstrumentationWarning` (a Python warning, also logged, once per process) saying that Langroid agents will NOT be checked by SASY. An application that has Langroid installed but never uses it gets no warning. If even those Langroid classes cannot be loaded, the warning comes from `sasy.instrument()` itself. Pass `langroid=True` to make a missing or unloadable Langroid an error, or `langroid=False` if your application does not use Langroid, which also silences the warning. The adapter does not check which Langroid version is installed, so install it through the extra. HTTP checks are off by default; pass `http=True` to have the engine check the agent’s `httpx` and `requests` calls and inject credentials (API keys the engine holds) into them. The policy must then allow each host the agent calls, including the model provider’s. 3. Run each conversation inside its own `with sasy.session(policy=...):` block. Keep `tool_policy_fail_closed=True`, the default: with it, a tool whose decision could not be obtained does not run. It is set in code only, through `sasy.configure(tool_policy_fail_closed=...)`. No environment variable and no `.env` file changes it, so a file dropped next to your application cannot turn the gate off, and `sasy.instrument()` logs a warning when it is off. The other instrumentation settings do read the environment, under names that start with `SASY_` (`SASY_LOG_DENIALS`, `SASY_LOG_POLICY_DECISIONS`, `SASY_LOG_POLICY_DECISIONS_TRANSFORMS_ONLY`, `SASY_LOG_TRANSFORMS`); the two OpenTelemetry settings keep the names that ecosystem uses, `OTEL_ENABLED` and `OTEL_SERVICE_NAME`. **Not covered** * File attachments. * History restored into a new run. A message this session never recorded has no inputs the adapter can defend, so a task continued from one stops at `task.init()`. Record the message first (below). “Continued” means a task started with no message of its own: `Task(agent, restart=False)`, or a second `task.run()` on the same agent. `Task(agent)` on its own clears the history and starts fresh, so it is not affected. Restored history that is only read as model input is treated by role: a USER or SYSTEM message with no parent is recorded as a fresh root, because that is what it is, while a restored assistant or tool message stops the next protected call. * An edit your application makes to a message, unless you record it (below). * A decision that requires a credential transform the tool adapter cannot apply: the tool is blocked rather than run unprotected. HTTP transforms are applied separately, by the reference-monitor proxy, to requests routed by `sasy.instrument(http=True)`. * HTTP requests, including the model’s requests to its provider, unless you pass `http=True`. * Networking libraries other than `httpx` and `requests`. The HTTP hooks deliberately let `localhost`, `127.0.0.1` and `::1` through: those requests are neither checked nor recorded, so a service reachable under one of those exact names is invisible to your policy. The same machine under another spelling (`127.0.0.2`, `0.0.0.0`, a decimal address) is checked like any other host. * Request bodies the hooks cannot read: an `httpx` request whose body is an async iterator, or a `requests` request whose body is a file object or a generator. These stop with an error from the conversion, which does not say why; nothing is sent unchecked. * Langroid’s synthetic “no answer” document, which a task injects when a step produces nothing and `allow_null_result=True`, and its `__SEND__:` / `__PASS__` routing, which rewrites a message that was already recorded. Both stop the run rather than record a computation that did not happen. * An allowlist policy has to name Langroid’s own orchestration tools (`done_tool`, `pass_tool`, `send_tool`, `forward_tool` and the rest) if your agents use them. They go through the same check as your tools, and a denied one stalls the task loop. The [Langroid example](https://github.com/sasy-labs/sasy/tree/main/examples/langroid-information-flow) in `examples/langroid-information-flow` is a three-agent team: two helpers read documents and a third agent, which can never read a file, sends the email. One document carries an injected instruction, and the agent that sends obeys it. The same program runs under two policy files — multi-level security, and a toxic-flow rule — so only the policy decides what is allowed. Its two helpers also run as concurrent tasks in one session, which is where a check on what a message was computed from differs from a session-wide flag: a secret another agent has already read is not a dependency of a message that never saw it. [Your first policy](/quickstart/) shows the plain configure-and-check shape. ## Threads inside a handler [Section titled “Threads inside a handler”](#threads-inside-a-handler) The adapter keeps the session and the current inputs in context variables (Python’s `contextvars`), which hold a separate value per thread and per asyncio task. A worker thread started inside a handler therefore begins with the defaults: no session, and no inputs. Carry the context into the worker: ```python import contextvars from concurrent.futures import ThreadPoolExecutor def fetch_all(self, msg: FetchAll) -> str: with ThreadPoolExecutor() as pool: running = [pool.submit(contextvars.copy_context().run, fetch, url) for url in msg.urls] pages = [task.result() for task in running] return summarize(pages) ``` One copy per worker: a single `Context` object cannot be entered by two threads at once. In async code, `asyncio.to_thread(...)` carries the context already. Without a copied context or a process-wide default, automatic Langroid and HTTP instrumentation in the worker is inactive. Carry the context, or open a `sasy.session(...)` block inside the worker. Keep the owning session open until its workers finish; an inherited closed session raises rather than bypassing checks. See [session lifetime](/configuration/#session-lifetime-and-background-work). ## Calling a handler yourself [Section titled “Calling a handler yourself”](#calling-a-handler-yourself) Handlers are checked where Langroid dispatches them, inside a responder: `agent_response`, `llm_response`, `task.run` and their async forms. Calling `agent.handle_message(...)` or `agent.handle_tool_message(...)` yourself is refused as soon as it reaches a tool handler, because outside a responder there is no record of what the call was computed from, and a check with no ancestry answers a different question than the one your run is asking. Passing a plain string to a responder (`agent.agent_response("some text")`) records the string as a fresh user message with no ancestry — which is what a string from outside the conversation is. To keep the ancestry, pass the `ChatDocument`, or record the message your code composed (below). ## Recording an edit your application makes [Section titled “Recording an edit your application makes”](#recording-an-edit-your-application-makes) If your code changes a message after it was recorded, record the change before the message is used again: ```python from sasy.instrumentation.langroid import record_message_update message.content = revised_text new_id = record_message_update(message, input_ids=[other_consumed_id]) ``` The helper includes the previous version of `message` plus the input IDs you supply. Pass `input_ids=[]` when the edit consumed only the previous message; use `record_message_update_async` in async code. The message must already have a recorded version in the current session. An edit clears the evidence that a tool completed successfully, unless the operation explicitly supplies `derived_from` for a completed tool. Do not copy that evidence from an earlier result: a rule that requires a successful `ToolResult` would then accept work that never ran. Unexpected content, or a changed parent, fails before the next protected dispatch. For a message in the form the model provider sees (an `LLMMessage`), the adapter compares the fields it recorded and refuses on the spot. For a `ChatDocument`, the changed message goes to the engine as an unchanged one and the engine refuses it, because its content no longer matches what was recorded under that version. Either way the run stops. Neither check can say what the new content was computed from, which is why an application edit has to be recorded explicitly. Custom handlers that read files, external state or extra messages must record those inputs too. ## Recording a message your application composes [Section titled “Recording a message your application composes”](#recording-a-message-your-application-composes) A `ChatDocument` your code builds from earlier results — the question for the next task, assembled from a previous task’s answer — was produced by no responder the adapter observes. Record it, with the version IDs of what it was computed from, before handing it to a task: ```python from sasy.instrumentation.langroid import record_message, recorded_version_id answer_id = recorded_version_id(answer_document) # None if never recorded question = ChatDocument(content=f"Does {answer} ...", metadata=ChatDocMetaData(sender=Entity.USER)) record_message(question, input_ids=[answer_id]) task.run(question) ``` Without this, a composed message with no parent is recorded as a fresh user input and the policy sees none of its ancestry. `record_message` refuses a message that already has a version; that is an edit. ## Subclassing `Task` [Section titled “Subclassing Task”](#subclassing-task) The adapter records the result of `Task.result` on Langroid’s `Task`. A subclass that overrides `result` replaces that method, so the override must record the document it builds: ```python from sasy.instrumentation.langroid import is_instrumented, record_task_result class MyTask(lr.Task): def result(self, status=None): result_doc = ... if is_instrumented(): record_task_result(self, result_doc) return result_doc ``` `is_instrumented()` is true once `sasy.instrument()` has patched Langroid in this process, so the same class runs unchanged without SASY. ## What counts as a recorded tool call [Section titled “What counts as a recorded tool call”](#what-counts-as-a-recorded-tool-call) A message’s tool calls are read from the message itself: the provider’s function and tool-call fields, plus any call written into the text, in Langroid’s JSON form (`{"request": "", ...}`) or its XML form (`...`). No agent’s tool registry is consulted, so every agent that reads a message records the same calls for it. That is what lets a parent task emit a call its sub-task handles: both record the same message, and neither refuses the other’s reading of it. Two consequences: * A JSON object with a `request` field is recorded as a tool call even when no agent could handle it. It is what the message asked for; whether anything runs is still decided by the check at dispatch. * A call whose fields are unusable — a known tool with the wrong types — is recorded as it was written and left to Langroid, which feeds its own validation error back to the model. Recording it does not end the run. ## What the adapter does with in-place edits [Section titled “What the adapter does with in-place edits”](#what-the-adapter-does-with-in-place-edits) Each responder receives a detached copy of its input message; the caller’s object stays as it was recorded, and the responder’s output is recorded from what it returns. A value a handler writes onto its input — on the tool object it was given, for another agent to read later — therefore does not reach that agent. Pass it in the returned message, or keep it on the agent that produced it. Langroid itself writes `request=` into a tool call’s arguments when an agent handles it. The adapter leaves that tag out of the recorded arguments, so a message reads the same before and after handling. # Security model and limits SASY enforces the bound policy before an action runs. Its guarantee rests on three conditions: the policy expresses the intended rule, the integration faithfully records policy-relevant inputs and dependencies, and it checks each protected action before execution. Under those conditions, a denied action does not execute, even when requested by a mistaken or compromised model. The engine, policy, application code, tool implementations, and adapter are trusted. Model output and external content are not. Framework guides describe the supported paths; this page covers deployment boundaries and current limits. ## Instrumentation and storage [Section titled “Instrumentation and storage”](#instrumentation-and-storage) A policy can only act on what the application recorded and on checks that run before a side effect. A dispatch site with no check in front of it never reaches the reference monitor, and a missing message in the graph does not prove the event never happened. Start with [add a framework](/instrumentation/). The supplied adapters cover the framework paths their guides list. The [LangChain](/integrations/langchain/) and [ADK](/integrations/google-adk/) adapters refuse an unsupported configuration, at setup or when the unsupported path is reached, rather than guess dependencies; the [Langroid guide](/integrations/langroid/) lists the message paths its adapter records and how to record your own edits. Paths a guide does not list as supported, such as framework checkpoints, custom state and remote agents, are not covered. LangChain messages recorded by an earlier SDK version, before events carried the whole message as metadata, no longer verify when passed back: the conversation continues, but they are recorded as [unattributed external inputs](/integrations/langchain/#inputs-of-unknown-origin) without their earlier ancestry. An event can carry a `metadata` string, which a policy reads through `MessageMetadata(id, metadata)`. The relation has a row only for a message recorded with metadata, and it is empty under a policy plugin. See [add a framework](/instrumentation/#what-goes-in-the-text-and-what-goes-in-the-metadata). Policy decisions are based on a faithful record of the execution trace, so graph content and engine logs are sensitive: they hold whatever the agent read. A recorded message is recorded as it is: the SDKs do not rewrite an event’s text, its metadata or a tool call’s arguments, because a policy decides on them and the reference monitor is given the same bytes. Recognized transport credentials are removed only from transport metadata — span attributes, SDK diagnostic logs, and the URLs and feedback text the HTTP hooks record. Nothing removes a secret an agent reads into its own context, which was in the model’s context before it reached the graph. Optional scrubbing of the prompt sent by an LLM-backed policy predicate does not redact the graph. Operators must control access, retention, request capacity, and storage capacity; per-tenant rate and durable storage quotas are not implemented. ## Trust boundaries [Section titled “Trust boundaries”](#trust-boundaries) The agent’s code is trusted: it defines the agents and their tools and places the checks. The content an agent reads is not trusted, and neither is the model’s judgment, which can be wrong with no attacker involved. Policies are written against both. A policy is provided by an authorized user, who is responsible for it, including any custom functor (a native function) it brings. Custom functors are admin-only unless an operator opts in. To enforce a policy obtained from someone else, run the engine in a Linux environment that supports sandboxing of both policy compilation and the evaluator; [build the engine](/building/) describes that setup. macOS does not provide the same bubblewrap boundary, so it suits development with policies you wrote or trust. An in-process evaluator plugin is a different thing. It is not part of a policy: the operator loads it when starting the engine, it runs inside the engine process with the engine’s privileges, and the sandbox does not apply to it. Load only a plugin you built or trust. A tool result containing secrets can disclose them to the agent’s model provider when the framework sends its next model request. A policy check on a later outbound action cannot undo that disclosure. Keep secrets outside the agent’s readable workspace, or enforce a read boundary before returning tool results. Credential scrubbing in transport metadata, and redaction of an LLM predicate’s prompt, do not change the agent’s own tool result or its own model requests. ## Policy analysis and diagnostics [Section titled “Policy analysis and diagnostics”](#policy-analysis-and-diagnostics) Policies are preprocessed by a Python script (`sugar.py`) when loaded, so the engine’s host needs Python. Static analysis models user `@functor` calls symbolically without executing them; some Soufflé built-in expressions remain explicitly unsupported. See [validation and debugging](/policies/validation/) for reports, behavioral checks, and denial traces. Allow-route diagnostics use fixed request conditions. They do not rerun functors or evaluate ancestry, and a `possible` route is not a promise that a suggested edit makes a rule match. Generated diagnostics reserve relation names beginning with `SasyAllow`. Automatic [dependency relevance](/policies/relevance/) inference is conservative: when it cannot narrow traversal, it may do more work. It preserves authored gate rules. An explicit gate changes which ancestry facts a policy can observe, so compare its decisions with an always-enabled baseline before relying on it. Runtime deadlines also cover generated diagnostic work. Compiled/interpreted parity tests and policy fixtures exercise selected cases; they are not a proof for arbitrary policies. See [core relations](/policies/core-relations/) for rule semantics and [configuration](/configuration/) for evaluation deadlines. ## Distribution scope [Section titled “Distribution scope”](#distribution-scope) This repository provides the engine and the gRPC policy API. The separate [sasy-guard repository](https://github.com/sasy-labs/sasy-guard) contains its released Claude Code policy and hooks; its daemon and management implementation are outside this core release. See [build the engine](/building/) for platform dependencies and policy sandboxing. Report vulnerabilities privately through the repository’s Security tab on GitHub (Report a vulnerability). # Start a local engine > Run the engine in Docker with one command and connect your agent. Keep an engine running while you build and test your agent. The Docker image includes the engine and its policy compiler; the Python SDK runs on your host. For a native engine, see [build from source](/building/). ## Start the engine [Section titled “Start the engine”](#start-the-engine) You need a running Docker (Docker Desktop, Colima or OrbStack) and the SDK installed as shown in the [quick start](/get-started/). No checkout of the SASY repository is needed: ```bash sasy engine start ``` Without the SDK installed, `uvx sasy engine start` runs the same command; it needs [uv](https://docs.astral.sh/uv/) and a running Docker. On first start, the engine image creates independent random client and admin API keys, role and transform configuration, and a private CA with a `localhost` server certificate, all in a Docker volume (`sasy-engine-data`). Later starts reuse them and the engine’s stored data. The engine listens on `127.0.0.1:10089` only. Startup returns after verifying a TLS connection against its generated CA. No pre-existing SASY credential is required; authentication is enabled, using the generated keys. The command saves the client connection settings in `~/.sasy/profiles/local/profile.json`, with the CA certificate alongside it as `ca-SHA256.crt`, where `SHA256` is the certificate content hash. `~/.sasy/selected-profile` selects that profile for the Python SDK. Directories are private to your user (mode `0700`), and files are owner-readable and writable (`0600`). The admin key and server private keys stay in the Docker volume; API keys are not printed. No project files are written by default. ```bash sasy engine status # running state and port of the selected engine sasy engine stop # stop it; retain the volume and its data ``` The SDK command and the engine binary are both named `sasy`: the SDK runs `sasy engine start` on your host, while the binary runs `sasy serve` inside the container. The engine starts with deny-all behavior until an application binds a policy; it does not load or run an example. ## Named profiles and custom settings [Section titled “Named profiles and custom settings”](#named-profiles-and-custom-settings) A profile is a saved endpoint, client credential, CA and Docker configuration. It selects an engine connection, not a session. One engine supports many concurrent sessions, so projects do not need separate profiles to run independent agent tasks. Named profiles are optional, useful when switching between engine instances or connection settings. The command uses `--profile`, then `SASY_ENGINE_PROFILE`, then the selected profile; without any of these it creates `local`. Starting a profile selects it for subsequent SDK use. For a separate engine: ```bash sasy engine start --profile research --port 10090 \ --client-entity research-client --admin-entity research-admin \ --tenant research --trust-domain sasy.local sasy engine status --profile research sasy engine stop --profile research ``` The `research` profile defaults to container `sasy-engine-research` and volume `sasy-engine-research-data`. The `local` profile retains container `sasy-engine` and volume `sasy-engine-data`. Repeat starts reuse saved Docker settings. Use `--name`, `--volume`, or `--image` to customize those settings; see the [CLI reference](/cli/#local-engine-commands) for all options. The generated identities default to `client` and `admin`, both in tenant `default`, with trust domain `sasy.local`. Identity options apply on first initialization. A request conflicting with the volume’s stored identity configuration fails instead of changing identities or rotating credentials. Create a fresh volume when you need a different initial configuration. [Authentication](/authentication/) explains roles, tenants, and remote providers. All applications using the same profile authenticate as its client principal. Sessions distinguish executions; they do not create separate authenticated principals or tenants. Separate named profiles with their own volumes provide separate local engines. Giving two profiles the same volume shares engine data and credentials. To write project-specific connection settings as well, opt in: ```bash sasy engine start --profile local --env-file .env ``` This writes missing `SASY_URL`, `SASY_API_KEY`, and `TLS_CA_PATH` values while preserving existing entries. The command reports conflicting retained settings; update those values before using that file. Treat `.env` as a secret file and keep it out of version control. The default image is `ghcr.io/sasy-labs/sasy:VERSION`, matching the SDK version. The release workflow publishes the SDK only after native AMD64 and ARM64 images pass qualification and their exact version tag and qualified digests can be pulled without registry credentials. A private or incomplete image fails this gate before SDK publication. `--image` selects a different image; `SASY_ENGINE_IMAGE` supplies the initial default for a new profile. To reset an engine, stop it, remove its Docker volume, then start the same profile again. This replaces the profile with the new client settings; it also discards the old volume’s graph data and credentials. ### Without the SDK command [Section titled “Without the SDK command”](#without-the-sdk-command) The image initializes the same configuration when started directly: ```bash docker run -d --rm --name sasy-engine -p 127.0.0.1:10089:10089 \ -v sasy-engine-data:/data ghcr.io/sasy-labs/sasy:0.5.1 docker exec sasy-engine sasy local-init /data/local ``` The second command prints the client API key and CA certificate as JSON. Save the certificate to a file and set `SASY_URL=localhost:10089`, `SASY_API_KEY`, and `TLS_CA_PATH` yourself. This direct Docker path does not create a host profile. ## Connect your agent from any project [Section titled “Connect your agent from any project”](#connect-your-agent-from-any-project) Run `python your_agent.py` in the environment where you installed SASY. The Python SDK falls back to the selected `~/.sasy` profile when no endpoint is configured through `sasy.configure()`, the environment, or the current working directory’s `.env`. An explicit endpoint uses its own authentication and TLS settings; it never borrows the local profile’s key or CA. Use `SASY_ENGINE_PROFILE=research` to select a profile for one process. See [client configuration](/configuration/#python-client-and-session-policy) for precedence and overrides. Each application binds its policy with `sasy.session(policy=...)`. The engine compiles and validates that policy; you do not need Soufflé or a C++ compiler on the host. The SDK uses your application’s installed frameworks; check the integration guides for supported versions. ## From a repository checkout [Section titled “From a repository checkout”](#from-a-repository-checkout) Only the repository’s examples need a checkout. From the repository root, the same command works through the workspace environment: ```bash uv run sasy engine start ``` It selects the shared local profile; the included demos use that profile unless you configure project overrides. The make targets below are an alternative that keeps the engine’s keys, certificates and data in the checkout instead of a Docker volume. ### Make targets [Section titled “Make targets”](#make-targets) These need Make, OpenSSL and Python 3.11 or newer on the host. Pull the built GHCR image and start the engine in the foreground: ```bash make docker-serve-ghcr ``` This target downloads the image for your architecture (ARM64 or x86-64), then uses the same local setup as `make docker-serve`. It does not build from source or require Nix on the host. The default image is `ghcr.io/sasy-labs/sasy:0.5.1`. Set `SASY_GHCR_IMAGE` to another release tag or digest to choose a different image. To build a modified engine locally, follow [build from source](/building/#docker). The run target creates local configuration and runs `make certs` before starting the engine. That target uses OpenSSL on your host to generate `certs/server.key` and a self-signed `certs/server.crt` for `localhost`. The engine uses the private key; the SDK trusts the certificate through `TLS_CA_PATH`. The demo does not generate a separate CA or need access to the private key. Setup fills in missing `SASY_URL`, `TLS_CA_PATH`, and `SASY_API_KEY` settings in the repository-root `.env`, using the **client** key from `config/auth/apikey.json`. A separate admin key stays in that auth file. Existing settings, keys, and certificates are preserved; `.env` is readable only by your user. API keys are not printed. The engine is ready when it logs `starting gRPC server`. Leave it running. It listens on your host’s loopback interface and retains its graph in `data/`. The target mounts `config/` and `certs/` read-only, mounts `data/` for storage, and runs the container as your user so it can read the key and write data. These local files are ignored by Git and excluded from the image build. With `config/` mounted, the image serves that configuration instead of creating its own. Stop it with Ctrl-C and restart with `make docker-serve-ghcr` to reuse the same configuration and data. ### Repository examples [Section titled “Repository examples”](#repository-examples) With an engine running, run the included examples from the repository root: ```bash uv run examples/message-flow/demo.py ``` On first use, `uv run` creates `.venv` and installs the local SDK, supported frameworks, and model clients from the root workspace. Later runs update that environment as needed. No separate install or sync command is required. Live-model examples describe their provider credentials. **Next: [SDK usage patterns](/sdk/) or the [LangChain example](/examples/#langchain-information-flow).** ## Troubleshooting [Section titled “Troubleshooting”](#troubleshooting) * **`Docker is not running`.** Start Docker Desktop, or `colima start`, and run `sasy engine start` again. * **`UNAUTHENTICATED` or a TLS error after recreating the volume.** Run `sasy engine start` to refresh the profile. Remove or update stale exported variables and project `.env` settings, which take precedence over profiles. * **Port 10089 is occupied.** Stop the old engine, then run `sasy engine start --port 10090`, or create a separate profile on that port. * **An identity setting conflicts with existing state.** Reuse the original identity settings or choose a fresh volume. Restarting does not rotate keys. * **The wrong engine is selected.** Run `sasy engine start --profile NAME`, or set `SASY_ENGINE_PROFILE=NAME` for the application process. With the make targets: * **The engine rejects a key at startup.** `config/auth/apikey.json` still holds the example keys from an older setup. Delete it and run `make init-config`. * **`UNAUTHENTICATED` from the SDK.** Its `SASY_API_KEY` must match the key mapped to `client` in `config/auth/apikey.json`. If you regenerate the auth file, update the existing key in `.env` too. * **A TLS error.** Use `localhost:10089` and the `certs/server.crt` created above. Setup writes an absolute `TLS_CA_PATH`; update it if you move the checkout. * **Port 10089 is occupied.** Run `make docker-serve-ghcr SASY_DOCKER_PORT=10090` and update `SASY_URL=localhost:10090` in `.env` if it already exists. Fresh setup uses the selected port; existing values are never overwritten. This local setup runs policies you trust. For remote clients or policies from other authors, see [configuration](/configuration/) and the [security model](/limits/#trust-boundaries). # Policy cookbook > Recipes for tool arguments, ancestry, approvals, roles, and unknown-origin input. These recipes use the [core relations](/policies/core-relations/) and [built-in functions](/policies/reference/). They are rule fragments: combine them with the rest of your policy’s allow and denial rules. No allowlist match means an action is not authorized. [Validate and test](/policies/validation/) the resulting policy against the observations your integration records. ## Allow a fixed set of tools [Section titled “Allow a fixed set of tools”](#allow-a-fixed-set-of-tools) ```prolog IsAuthorized(idx) :- Actions(idx, a), IsTool(a, "read_public"). IsAuthorized(idx) :- Actions(idx, a), IsTool(a, "draft_summary"). ``` ## Allow a tool only for one argument value [Section titled “Allow a tool only for one argument value”](#allow-a-tool-only-for-one-argument-value) ```prolog IsAuthorized(idx) :- Actions(idx, a), IsTool(a, "publish"), a = $CallTool(_, args), @json_get_str(args, "destination") = "internal". ``` ## Deny when the ancestry contains a confidential read [Section titled “Deny when the ancestry contains a confidential read”](#deny-when-the-ancestry-contains-a-confidential-read) The rule fires even though a drafting tool rewrote the text in between, because it follows recorded dependencies rather than searching the output for secret words. ```prolog .decl ConfidentialInput() ConfidentialInput() :- CurrentDepends(id), ToolResult(id, "read_confidential", _). // @deny_message: External publication depends on confidential information // @suggestion: Publish internally or start a separate task using public inputs Unauthorized(idx) :- Actions(idx, a), IsTool(a, "publish"), a = $CallTool(_, args), @json_get_str(args, "destination") = "external", ConfidentialInput(). ``` ## Deny a combination of sources [Section titled “Deny a combination of sources”](#deny-a-combination-of-sources) Either source alone does not trigger this denial; together they do. ```prolog .decl ReadSource(name: symbol) ReadSource(name) :- CurrentDepends(id), ToolResult(id, "read_document", args), name = @json_get_str(args, "name"). // @deny_message: This summary depends on both untrusted and sensitive documents Unauthorized(idx) :- Actions(idx, a), IsTool(a, "send_summary"), ReadSource("external-note"), ReadSource("sensitive-report"). ``` ## Decide on a field the text does not show [Section titled “Decide on a field the text does not show”](#decide-on-a-field-the-text-does-not-show) A node’s text is what the model read; the rest of the message is in its metadata. Here a LangChain message whose `additional_kwargs` carries a marker refuses the publication, although the text is unremarkable. ```prolog .decl MarkedDependency(id: symbol) MarkedDependency(id) :- CurrentDepends(id), MessageMetadata(id, md), @json_get_str_path(md, "s:additional_kwargs.s:marker") = "exfil". // @deny_message: A message this publication depends on is marked in its metadata Unauthorized(idx) :- Actions(idx, a), IsTool(a, "publish"), MarkedDependency(_). ``` This recipe inspects ancestors. Add a corresponding `Current(id)` rule when direct inputs must also be checked. A message without metadata does not match. See [LangChain records](/reference/langchain-records/) for field paths and [extension points](/policies/extensions/#message-metadata) for metadata producers. ## Require a prior approval bound to the same arguments [Section titled “Require a prior approval bound to the same arguments”](#require-a-prior-approval-bound-to-the-same-arguments) Because `ToolResult` exists only for a call that actually ran and returned without error, a denied or failed approval cannot satisfy this. ```prolog .decl ApprovedPayment(request_id: symbol, payee: symbol, amount: symbol) ApprovedPayment(request_id, payee, amount) :- CurrentDepends(approval), ToolResult(approval, "approve_payment", approved_args), SentMessage(approval, approved_message), approved_message.agent = "reviewer", request_id = @json_get_str(approved_args, "request_id"), payee = @json_get_str(approved_args, "payee"), amount = @json_get_str(approved_args, "amount"). IsAuthorized(idx) :- Actions(idx, a), IsTool(a, "disburse_payment"), a = $CallTool(_, args), ApprovedPayment(@json_get_str(args, "request_id"), @json_get_str(args, "payee"), @json_get_str(args, "amount")). ``` The `reviewer` condition matches the integration’s agent label. If the approval must come from a particular authenticated writer, also check the result message’s `principal` field; agent labels are not authenticated identity. ## Allow a tool only for a role [Section titled “Allow a tool only for a role”](#allow-a-tool-only-for-a-role) The role comes from the engine’s authentication configuration, not from the conversation. ```prolog IsAuthorized(idx) :- Actions(idx, a), IsTool(a, "disburse_payment"), HasRole("treasury"). ``` ## Allow model traffic to one provider host [Section titled “Allow model traffic to one provider host”](#allow-model-traffic-to-one-provider-host) Only relevant when the HTTP hooks are enabled (`sasy.instrument(http=True)`); without a rule like this, an outbound request is denied. ```prolog IsAuthorized(idx) :- Actions(idx, a), QueriesHost(a, "api.openai.com"). ``` ## Treat input of unknown origin conservatively [Section titled “Treat input of unknown origin conservatively”](#treat-input-of-unknown-origin-conservatively) An adapter records a value it consumed but cannot attribute — a message handed back without its mark, state another process wrote, a value from a different SASY session — as a message of unknown origin, and carries on. `DependsOnUnattributedInput()` matches a recognized unknown-origin marker in a direct input or ancestor. ```prolog CurrentDependsPolicyRelevant() :- IsTool(_, "publish"). // @deny_message: This action depends on input whose origin was not recorded Unauthorized(idx) :- Actions(idx, a), IsTool(a, "publish"), DependsOnUnattributedInput(). ``` To act only on values that came from another session, read the label instead. It says where the adapter placed the value; it is not a claim that the value is trustworthy. ```prolog // @deny_message: This action depends on a value from another SASY session Unauthorized(idx) :- Actions(idx, a), IsTool(a, "publish"), UnattributedInputOrigin(_, "another SASY session"). ``` Note that the gate rule above names `publish`. A rule that reads the ancestry for some other tool needs that tool in the gate too, or it never fires: ```prolog CurrentDependsPolicyRelevant() :- IsTool(_, "publish"). CurrentDependsPolicyRelevant() :- IsTool(_, "send_email"). ``` The common helper reads the unprefixed provenance marker. For LangChain, add its [adapter-specific rules](/integrations/langchain/#inputs-of-unknown-origin). See [dependency relevance](/policies/relevance/) before narrowing either gate. Such a message never carries successful-tool evidence, so a rule that requires a `ToolResult` already refuses it. These relations are for the other direction: noticing that something unattributed reached the action at all. ## Request human approval [Section titled “Request human approval”](#request-human-approval) Use `// @ask` on a denial rule to return an approval request. The application must handle that result before an action can run; supplied adapters block it. See [approval requests](/policies/reference/#approval-requests) for the notation and its interaction with allowlist matches and hard blocks. # Core policy relations > Actions, authorization, identity, and the recorded evidence a policy reads. Start with the [small policy examples](/policy-language/). This page explains the relations used in most policies. They are declared by the engine’s common schema; you do not need to declare them again. ## Proposed actions and decisions [Section titled “Proposed actions and decisions”](#proposed-actions-and-decisions) | Relation | Source and meaning | | --------------------------- | ------------------------------------------------------------------------------------------------------------- | | `Actions(idx, action)` | Input: proposed actions in this check. `idx` is the zero-based action index. | | `IsTool(action, name)` | Helper: the action is a tool call with this name. | | `QueriesHost(action, host)` | Helper: the action is an HTTP request to this non-empty host. | | `IsAuthorized(idx)` | Policy output: put this action on the allowlist. | | `Unauthorized(idx)` | Policy output: block this action, even if it also has an allowlist match. | | `Authorized(idx)` | Common-rule output: an authenticated principal exists, the action is allowlisted, and it is not hard-blocked. | An action is a tagged value with one of these shapes: | Action | Fields | | --------------------------------------- | --------------------------------------------------------------- | | `$CallTool(name, args)` | Tool name and ordinary JSON argument string. | | `$HTTPRequest(url, body, headers_json)` | Request URL, body, and JSON headers. | | `$SendAttempt(message)` | A proposed message, using the `Message` record described below. | Bind the same `idx` from `Actions` in your decision rule. A check can contain more than one action; a decision for index 0 says nothing about index 1. Graph observations and session policy bindings are scoped to the authenticated tenant. A session keeps its recorded context across checks; recording a fact does not execute or authorize a tool. See [session configuration](/configuration/). No allowlist match means the action is not authorized. `Unauthorized` wins over an allowlist match. Approval requests and HTTP forwarding controls have additional behavior described in [built-ins and feedback](/policies/reference/). ## Authenticated identity [Section titled “Authenticated identity”](#authenticated-identity) | Relation | Meaning | | -------------------------------- | --------------------------------------------------------------------------------- | | `Principal(id)` | The authenticated caller of this check, stamped by the server. | | `PrincipalRole(principal, role)` | Roles associated with that authenticated principal. | | `HasPrincipal()` | True when this request has an authenticated principal. | | `HasRole(role)` | True when that principal holds the named role. | | `TenantId(id)` | Server-derived tenant for the request. | | `Entity(id)` | A free-form actor label supplied by the caller; it is not authenticated identity. | For example, require the authenticated caller’s role: ```prolog IsAuthorized(idx) :- Actions(idx, action), IsTool(action, "disburse_payment"), HasRole("treasury"). ``` Message records also carry the principal that wrote them. A message’s `agent` label or `entity` field is not a substitute for authenticated identity. See [authentication](/authentication/) for the source of principals, roles, and tenants. ## Context and dependency direction [Section titled “Context and dependency direction”](#context-and-dependency-direction) | Relation | Meaning | | ---------------------------- | ---------------------------------------------------------------------------------------------- | | `Edge(source, destination)` | The destination was computed from the source. | | `Current(id)` | A recorded message supplied as a direct input of this check. | | `CurrentDepends(id)` | An ancestor of a current message, following dependencies backward. | | `SentMessage(id, message)` | The recorded message and its fields. | | `ToolResult(id, tool, args)` | Successful-tool evidence attached to this recorded result, with the tool’s name and arguments. | An edge from a tool result to a summary means the summary depends on the result. A check using that summary as a current input can therefore find the tool result in `CurrentDepends` even if its text was rewritten along the way. `CurrentDepends` does not include a node merely because it is current. To inspect both direct inputs and ancestors, declare a helper: ```prolog .decl InScope(id: symbol) InScope(id) :- Current(id). InScope(id) :- CurrentDepends(id). ``` These relations describe the graph the application or adapter recorded. Missing observations do not prove that an event never happened. `!Relation(...)` tests absence in the supplied facts and derived results, so a rule using absence needs complete recording for the question it asks. Dependency traversal can be restricted by the [relevance gates](/policies/relevance/). An explicit gate must cover every action whose rules need ancestry. ## Message fields and tool evidence [Section titled “Message fields and tool evidence”](#message-fields-and-tool-evidence) A `Message` has these fields, available through the preprocessor’s dot notation: | Field | Meaning | | ------------ | ------------------------------------------------------------------------------------- | | `contents` | Recorded text; the adapter determines how structured content is represented. | | `tools_json` | JSON list of tool calls carried by this message. | | `agent` | Free-form agent or conversation label. | | `agent_role` | Conversation role: `$Assistant()`, `$SystemRole()`, `$UserRole()`, or `$AgentType()`. | | `entity` | Caller-supplied actor label on the recorded message. | | `principal` | Server-stamped identity of the writer, or empty when unknown. | For example, inspect the contents of a successful result: ```prolog .decl ConfidentialRead(id: symbol) ConfidentialRead(id) :- CurrentDepends(id), ToolResult(id, "read_document", _), SentMessage(id, message), @json_get_str(message.contents, "classification") = "confidential". ``` `ToolResult` establishes that a guarded call returned successfully; a proposed, denied, failed, or supplied historical call is not that evidence. Its `args` column holds the call arguments. Read the return value from the result message’s `contents`. The [LangChain](/reference/langchain-records/) and [ADK](/reference/google-adk-records/) references describe their record shapes. Continue with [built-ins and feedback](/policies/reference/) for the broader relation and functor reference, or use the [cookbook](/policies/cookbook/) for rules that combine these pieces. # Policy extension points > Supply message, action, and policy metadata, and add native functors. Use ordinary policy rules to combine the [core relations](/policies/core-relations/). When a rule needs information outside those relations, supply metadata or add a custom functor. Metadata supplies facts; a functor computes a value during policy evaluation. ## Choose the scope of a fact [Section titled “Choose the scope of a fact”](#choose-the-scope-of-a-fact) | Policy relation | Populate it through | Lifetime | | -------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------- | | `MessageMetadata(id, value)` | `Event.metadata` when recording or resolving a message. | Part of the recorded message version. | | `ActionMetadata(idx, rel, a, b)` | The proposed action’s metadata in an authorization request. | This action in this check. | | `PolicyMetadata(rel, a, b)` | Policy upload metadata, or the session metadata-update API. | Configuration and accumulated facts for the policy binding/session. | These facts are supplied by the application or adapter. The engine does not perform the external lookup that a fact describes. Give the producer a defined meaning and scope before using its facts to authorize an action. Metadata is not a replacement for the server-derived `Principal` and roles. ## Policy configuration [Section titled “Policy configuration”](#policy-configuration) Separate deployment settings from policy logic. For example, this policy allows publication only to destinations configured on its binding: ```prolog .decl AllowedDestination(name: symbol) AllowedDestination(name) :- PolicyMetadata("allowed_destination", name, _). IsAuthorized(idx) :- Actions(idx, action), action = $CallTool("publish", args), AllowedDestination(@json_get_str(args, "destination")). ``` After configuring the SDK connection, bind it with Python: ```python from pathlib import Path import sasy with sasy.session( policy=Path("publication.dl"), policy_metadata=[("allowed_destination", "internal", "")], ): result = sasy.check_tool_call("publish", '{"destination":"internal"}') ``` Python accepts `(rel, a)` or `(rel, a, b)` tuples; omitted `b` is empty. The TypeScript equivalent is `session.setPolicy(source, { policyMetadata: [{ rel: "allowed_destination", a: "internal", b: "" }] })`. The gRPC field is `SetPolicyRequest.policy_metadata`. ### Append facts during a session [Section titled “Append facts during a session”](#append-facts-during-a-session) An application can add a fact after an external event, such as a completed review: ```python from sasy.policy import update_policy_metadata update_policy_metadata(session_id, [("reviewed", "synthetic-report", "approved")]) ``` `session_id` is the active session’s wire ID, available in Python through `sasy.get_current_session_id()` for an ordinary session. TypeScript exposes `session.updatePolicyMetadata(facts)`; gRPC exposes `UpdatePolicyMetadata`. Facts accumulate: this API appends and does not remove or replace earlier facts. Use per-action metadata for a verdict that must apply to one check, and bind approval facts to the resource and arguments they actually cover. A policy must read the fact for it to affect a decision. ## Facts for one proposed action [Section titled “Facts for one proposed action”](#facts-for-one-proposed-action) Pass a lookup result with the action it describes: ```python result = sasy.check_tool_call( "publish", '{"destination":"internal"}', metadata=[("content_scan", "classification", "public")], ) ``` The engine projects that tuple into `ActionMetadata` with the same index as the action. A matching allow rule is: ```prolog IsAuthorized(idx) :- Actions(idx, action), IsTool(action, "publish"), ActionMetadata(idx, "content_scan", "classification", "public"). ``` Missing metadata leaves this allow rule unmatched. A denial is returned in `result.authorized`; the application must check it before dispatch. Required transforms must also be applied or the action refused. TypeScript’s `session.checkToolCall` accepts `metadata: [{ rel, a, b }]`. At the gRPC layer these facts are `Action.metadata` for `CheckAuthorization`, or `ToolCallRequest.metadata` on the reference-monitor tool-check API. They are separate from the RPC’s authentication headers. ## Message metadata [Section titled “Message metadata”](#message-metadata) Write the source message’s policy-relevant fields into `Event.metadata`. The server exposes the string as `MessageMetadata(id, value)` and includes it in the message’s content identity. It does not interpret or validate your schema. Inside an active session, record a custom JSON field with an immutable version: ```python import json from sasy.observability import Event, EventSnapshot, resolve_events node_id, = resolve_events([EventSnapshot(event=Event( id="synthetic-report", text="A synthetic report", metadata=json.dumps({"marker": "reviewed"}), ))]) ``` For immutable observations, use Python’s `resolve_events` with `EventSnapshot` objects, or TypeScript’s `session.resolveEvents`. The older `record_events_with_dependencies` / `session.registerEventsWithDependencies` APIs also accept `Event.metadata`. See [recording and versioning](/instrumentation/#immutable-message-versions) for the APIs and dependency handling. For custom events, choose a documented format, usually JSON. Supplied integration adapters already define their formats: [LangChain records](/reference/langchain-records/) and [ADK records](/reference/google-adk-records/). Their metadata keys carry type prefixes such as `s:`; custom metadata does not acquire those prefixes automatically. ## Custom functors [Section titled “Custom functors”](#custom-functors) Use a custom functor for an operation that the existing rules and [built-in functions](/policies/reference/#json-functors) cannot express. Declare its Datalog signature and provide a matching C++ implementation separately. This minimal example shows the interface: ```prolog .functor label_is_internal(label: symbol): unsigned stateful IsAuthorized(idx) :- Actions(idx, action), action = $CallTool("publish", args), @label_is_internal(@json_get_str(args, "label")) = 1. ``` ```cpp #include extern "C" souffle::RamDomain label_is_internal( souffle::SymbolTable* symbols, souffle::RecordTable*, souffle::RamDomain label) { return symbols->decode(label).rfind("internal:", 0) == 0 ? 1 : 0; } ``` The `stateful` signature receives the symbol and record tables before its Datalog arguments. Decode symbol arguments and encode symbol return values through the symbol table. Keep the implementation’s name and types consistent with its declaration. For Python file-based policies, put the implementation in a companion `functors.cpp`; the SDK discovers it when loading the policy. For explicit uploads, use `sasy.policy.set_session_policy(..., functor_source=cpp_source)`. TypeScript’s `session.setPolicy` accepts `functorSource`; the gRPC field is `SetPolicyRequest.functor_source`. The engine compiles the source into the compiled evaluator or the interpreted backend’s shared functor library. Custom functors are native code. Admission requires an administrator unless the operator explicitly enables non-admin admission; sandbox-required admission needs working Linux confinement. See [engine options](/cli/#engine-server-options) and [security limits](/limits/). A restricted build accepts installed profiles, not new source uploads. Validate the policy and exercise allowed, denied, and missing-data cases with the intended backend. A syntax check does not execute the C++ implementation. See [validation and debugging](/policies/validation/). # Built-ins and feedback > Additional relations, JSON and text functors, and denial feedback annotations. The [core relations](/policies/core-relations/) cover actions, identity, messages, and authorization. This page adds the helpers and feedback notation used by more specific policies. The schema and signatures are in [`souffle/common_policy.dl`](https://github.com/sasy-labs/sasy/blob/main/souffle/common_policy.dl). ## Context helpers [Section titled “Context helpers”](#context-helpers) | Relation | Meaning | | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `IsToolCall(action)` | Matches any proposed tool call. | | `ReachableFrom(source, destination)` | Forward reachability between ancestors of the current inputs. Both endpoints are in the backward slice. Useful for ordering earlier events. | | `ToolResultFieldName(field)` | A fact you write to select a top-level JSON result field to extract. | | `ToolResultField(tool, field, value)` | A selected, non-empty string field from a successful tool result in the ancestry. | | `UnattributedInput(id)` | A direct input or ancestor whose recorded text carries the common unknown-origin marker. | | `DependsOnUnattributedInput()` | True when any such input is in scope. | | `UnattributedInputOrigin(id, origin)` | Its non-empty origin label, when the adapter recorded one. | | `CurrentDependsPolicyRelevant()`, `ReachableFromPolicyRelevant()` | Gates controlling dependency traversal; see [relevance](/policies/relevance/). | Declare a field to make it available through `ToolResultField`: ```prolog ToolResultFieldName("classification"). // @deny_message: This publication depends on a confidential document Unauthorized(idx) :- Actions(idx, action), IsTool(action, "publish"), ToolResultField("read_document", "classification", "confidential"). ``` `ToolResultField` omits missing fields and empty strings and handles string values only. For numbers or nested fields, join `ToolResult` with `SentMessage` and use a JSON functor directly. The helper does not identify which resource a result belongs to; join on message IDs and arguments when that distinction matters. Unknown-origin helpers recognize the unprefixed `provenance` marker in message text. LangChain uses a prefixed envelope and needs its [adapter-specific marker rules](/integrations/langchain/#inputs-of-unknown-origin). ## Metadata and edge details [Section titled “Metadata and edge details”](#metadata-and-edge-details) | Relation | Meaning | | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `MessageMetadata(id, metadata)` | The adapter’s record of the source message, stored as `Event.metadata`. No row exists when metadata was omitted. | | `ActionMetadata(idx, rel, a, b)` | Facts attached to this proposed action, indexed like `Actions`. | | `PolicyMetadata(rel, a, b)` | Configuration supplied with the policy, plus any session-scoped facts appended later. | | `EdgeData(source, destination, data)` | Optional recording context: `data.proximal` is 1 for an immediate predecessor, 0 for false, or -1 if unset; `data.message_index` is the zero-based input position, or -1 if unset. | | `EdgePrincipal(source, destination, principal)` | Server-stamped identity of the edge writer, when known. | | `EdgeEntity(source, destination, entity)` | Caller-supplied actor label for the edge, when present. | See [extension points](/policies/extensions/) for the APIs that populate metadata and examples of projecting it into policy-specific relations. An edge can exist without any of these optional edge-detail rows. ## Feedback and denial reasons [Section titled “Feedback and denial reasons”](#feedback-and-denial-reasons) Put annotation comments immediately above a rule: ```prolog // @deny_message: External publication is disabled // @suggestion: Publish internally Unauthorized(idx) :- Actions(idx, action), IsTool(action, "publish"), action = $CallTool(_, args), @json_get_str(args, "destination") = "external". ``` | Notation | Effect | | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `// @deny_message: text` | Human-readable reason for a matching denial rule. | | `// @suggestion: text` | Suggested remediation. It does not change authorization. | | `// @ask` | Return an approval request instead of a hard block. | | `// @tool_pattern: pattern`, `// @url_pattern: pattern` | Filter suggestions on `IsAuthorized` allowlist rules to matching actions. They do not replace conditions in the rule body. | | `// @broad` | Marks a broad rule for static analysis, such as an intentional allow rule with narrower denials. It does not change evaluation. | The preprocessor rewrites ordinary `Unauthorized` rules to `DenialReason(idx, kind, reason, suggestion)`. Unannotated rules use `"Action is denylisted"`, an empty suggestion, and kind `"block"`. A block reason implies `Unauthorized`. You can also derive `DenialReason` directly when the reason needs values from the rule. Annotations on `IsAuthorized` provide hints when no allow rule matches; they do not create a denial rule. `@tool_pattern` and `@url_pattern` filter those allowlist suggestions. Feedback on `Unauthorized` denylist rules is provided when the rules fire. See [debugging denial traces](/policies/validation/#read-a-denial-trace) for how those hints and allow-route statuses appear in a response. ### Approval requests [Section titled “Approval requests”](#approval-requests) ```prolog // @ask // @deny_message: Publishing externally needs human approval Unauthorized(idx) :- Actions(idx, action), IsTool(action, "publish"), action = $CallTool(_, args), @json_get_str(args, "destination") = "external". ``` `@ask` emits a reason of kind `"ask"`. It does not itself supply an allowlist match, and a hard block still wins. The engine returns the request as not authorized; the supplied integration adapters block the tool. An application that supports approval must handle that result and arrange a subsequent authorized check. The annotation does not open a human approval UI by itself. ### HTTP controls and transforms [Section titled “HTTP controls and transforms”](#http-controls-and-transforms) | Output | Effect | | ----------------------------------- | ---------------------------------------------------------------------------------------------- | | `ApplyTransform(idx, transform_id)` | Requires the configured credential/header/query transform on an authorized HTTP proxy request. | | `DenyUnauthorized(idx)` | Explicitly reject an unauthorized HTTP proxy request. | | `AllowPassthrough(idx)` | Allows the HTTP proxy to forward an unauthorized request unchanged, without transforms. | Tool-call checks do not honor HTTP passthrough. A caller that receives required transforms must apply them or refuse to dispatch; the LangChain and ADK tool adapters refuse transforms they cannot apply. See [configuration](/configuration/) for the HTTP path and credential configuration. ## JSON functors [Section titled “JSON functors”](#json-functors) A functor is called with `@name(...)` inside a rule. These functions inspect JSON strings; they do not fetch additional observations. | Functor | Result | | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | | `@json_get_str(json, field)`, `@json_get_int(json, field)` | A top-level string or integer; `""` or -1 on a miss. | | `@json_has_field(json, field)` | 1 when the top-level field is present, otherwise 0. | | `@json_get_str_path(json, path)`, `@json_get_int_path(json, path)` | Nested string or integer using dotted paths and array indices; the same miss values apply. | | `@json_array_len(json, path)` | Length of the array at a path. | | `@json_array_get_str(json, path, i)` | String element of an array. | | `@json_array_get_field_str(json, path, i, field)` | A string field of an array’s object element. | | `@json_object_has_key(json, path, key)` | 1 if the object at the path has this key, otherwise 0. | | `@json_object_field_int(json, base, key, sub)` | Integer at the nested path assembled from `base`, dynamic `key`, and `sub`. | For example, `@json_get_str_path(args, "destination.account")` reads a nested account field, and `@json_get_str_path(result, "items[0].name")` reads an array entry. Missing or wrongly typed values use the function’s miss value; they are not a positive observation. Do not treat an empty string or -1 as evidence of a successful lookup when the rule requires one. Paths split on `.` and `[`; colons in metadata keys need no escaping. A key containing `.` or `[` cannot be addressed by a path. At the top level, use `@json_get_str(json, "")` to read such a string field. ## Text, URL, time, and semantic functors [Section titled “Text, URL, time, and semantic functors”](#text-url-time-and-semantic-functors) | Functor | Result | | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | | `@str_contains(s, sub)`, `@str_starts_with(s, prefix)` | 1 for a match, otherwise 0. | | `@str_to_lower(s)`, `@str_len(s)` | Lowercased text or its length. | | `@url_host(url)` | The URL’s host. | | `@registrable_domain(s)` | The registrable domain of the first URL or host, or `""`. | | `@count_urls(s)` | Number of URL/host fetch targets; may overcount. | | `@hours_between(t1, t2)` | Absolute whole hours between ISO-style timestamps; -1 if either fails to parse. | | `@llm_check_fn(prompt, context)` | Optional LLM yes/no predicate, returning 1 or 0. Requires operator configuration; it is not an independent source of recorded facts. | The compiled backend supplies the configured LLM predicate. The shipped interpreted functor library does not make live LLM requests and returns 0 on an uncached input. Choose the backend deliberately when a policy depends on it. Shell-command and Unicode helpers include `@cmd_invokes`, `@cmd_runs_sub`, `@cmd_egress_class`, `@normalize_cmd`, `@dangerous_rm`, `@has_deceptive_unicode`, and `@deceptive_unicode_class`. Their signatures and classification values are commented in the common schema. Use [custom functors](/policies/extensions/#custom-functors) when a required operation is not available here. # Dependency relevance > Control when ancestry and pairwise reachability are evaluated. A policy that checks only a tool name does not need to walk the message graph. A policy that depends on earlier results does. SASY uses relevance gates to avoid unnecessary dependency traversal. ## What the gates control [Section titled “What the gates control”](#what-the-gates-control) An **EDB relation** contains supplied facts, such as `Actions` and `Edge`. An **IDB relation** is derived by rules, such as `CurrentDepends`. The built-in relevance mechanism gates these two derived relations: | Gate | Derived relation | | -------------------------------- | ------------------------------------------------------------- | | `CurrentDependsPolicyRelevant()` | `CurrentDepends`: ancestors of current inputs. | | `ReachableFromPolicyRelevant()` | `ReachableFrom`: pairwise reachability among those ancestors. | When a gate is false, the corresponding relation is empty. Helpers that depend on it, including `ToolResultField` and ancestry-based unknown-origin checks, have no ancestor rows to read. Direct `Current` inputs remain available. `ReachableFromPolicyRelevant` also implies `CurrentDependsPolicyRelevant`. These are the two built-in gates. Naming a new relation `SomethingPolicyRelevant` does not automatically gate another IDB; a custom relation must be joined in its own rules if it is meant to control their evaluation. ## Automatic behavior [Section titled “Automatic behavior”](#automatic-behavior) You can write a correct ancestry policy without authoring gates. Preprocessing supplies default gates when the policy references a gated relation or a common helper that depends on it. A policy with no consumer needs no default traversal. The engine then analyzes those defaults and can restrict traversal to actions whose decision or diagnostic rules need it. It traces dependencies through policy-defined helper relations as well. When syntax, recursion, or analysis limits prevent a sufficiently precise result, it retains conservative behavior and may do more work. It does not turn an unanswered dependency question into a negative policy fact. Automatic inference changes only generated defaults. It preserves authored gate rules. This bounded optimization is separate from the [static policy analysis report](/policies/validation/#static-analysis). ## Explicit action gates [Section titled “Explicit action gates”](#explicit-action-gates) For a policy whose ancestry rules protect `publish` and `send_email`, write: ```prolog CurrentDependsPolicyRelevant() :- IsTool(_, "publish"). CurrentDependsPolicyRelevant() :- IsTool(_, "send_email"). ``` This enables ancestry when either tool appears in the action batch. The gate is request-wide, not indexed per action. Add every action whose rules need ancestry, including rules that use helpers such as `DependsOnUnattributedInput`. If only `publish` needs pairwise event ordering, use the narrower second gate: ```prolog ReachableFromPolicyRelevant() :- IsTool(_, "publish"). ``` That also enables `CurrentDepends` for `publish`. `ReachableFrom` is more expensive than collecting ancestors alone, so do not enable it merely to read a prior tool result. ## Gates affect what a rule can observe [Section titled “Gates affect what a rule can observe”](#gates-affect-what-a-rule-can-observe) An explicit gate is part of policy behavior. If the gate omits `send_email`, an ancestry-based denial for `send_email` may never match. A negated ancestry test may instead succeed because the relation is empty. Neither outcome establishes that the underlying graph contains no relevant event. Base gate conditions on the proposed action and other available request facts. Do not require `CurrentDepends` to establish its own gate: that circular requirement can leave the relation empty. Before narrowing a gate, compare decisions with an always-enabled baseline: ```prolog CurrentDependsPolicyRelevant(). ReachableFromPolicyRelevant(). ``` Use a separate policy variant for the baseline. Exercise every protected action, including mixed action batches, a relevant ancestor, no relevant ancestor, and missing required evidence. The [validation guide](/policies/validation/) explains how to distinguish compiler checks, diagnostics, and behavioral tests. # Validate and debug policies > Compile policies, test decisions, interpret denial traces, and use static analysis. Validate in stages: check the policy’s syntax, exercise decisions against the engine and integration, then use diagnostics and static analysis to understand unexpected results. ## Compile without changing a policy binding [Section titled “Compile without changing a policy binding”](#compile-without-changing-a-policy-binding) From a source checkout: ```sh make souffle-validate FILE=my_policy.dl ``` This preprocesses and validates the policy locally without a running engine. It needs Python and Soufflé on `PATH`; it reports compiler errors and does not exercise the policy against recorded context. The SDK also provides `sasy.policy.validate_policy(source)` and TypeScript’s `validatePolicy(source)`, backed by the `ValidatePolicy` RPC. They validate source without installing it. Binding a policy to a session compiles it as well; a binding error surfaces when entering `sasy.session(policy=...)`, not when calling `sasy.configure`. Pass `Path("my_policy.dl")` to load a Python policy file. A plain string is interpreted as policy source. Declare policy-specific relations with `.decl`; the [common relations](/policies/core-relations/) are already declared. ## Test the resulting decisions [Section titled “Test the resulting decisions”](#test-the-resulting-decisions) Use synthetic observations in an isolated session. For each rule, check a case that should allow, a case that should deny, and a case with missing prerequisite evidence. Check the actual arguments and recorded message versions that the integration supplies. For ancestry rules, test direct inputs separately from ancestors. For an approval rule, test a matching approval and one for another resource or different arguments. If the application only recorded a proposed or failed call, it must not satisfy a requirement for a successful `ToolResult`. When testing [relevance gates](/policies/relevance/), compare the gated policy with an always-enabled variant for every protected action. A false gate yields an empty ancestry relation; an empty result is not evidence that no ancestor exists. In this checkout, build and select the engine explicitly: ```sh make build-rust-dev SASY_TEST_ENGINE="$PWD/target/debug/sasy" \ .venv/bin/python -m pytest -q --run-integration -m integration ``` These are the repository’s owned-engine tests. Use the same build and session isolation for your own policy scenarios. See the [test guide](https://github.com/sasy-labs/sasy/blob/main/tests/README.md) for prerequisites and test lanes. Normal CI uses scripted models; live-provider checks are separate and opt in. ## Read a denial trace [Section titled “Read a denial trace”](#read-a-denial-trace) For a Python tool check, inspect `result.authorized`, `result.denial_reasons`, `result.suggestions`, and `result.denial_trace`. At the policy API layer, each action result carries its trace. A transport or evaluator failure means no usable decision was obtained; it is not evidence that a semantic denial rule matched. A fired denial rule contributes its [reason and suggestion annotations](/policies/reference/#feedback-and-denial-reasons). When no allow rule matches, the trace also describes candidate allow routes: | `allow_routes` status | Meaning | | --------------------- | -------------------------------------------------------------------------------------------------------- | | `blocked` | Fixed request conditions rule out this allow rule, for example a different tool name. | | `possible` | Those conditions do not rule it out. This is a hint, not a promise that a suggested edit makes it match. | | `unknown` | The bounded analysis could not decide. | This diagnostic analysis does not run functors again or evaluate ancestry conditions. Rule identifiers and statuses are in `allow_routes`. The text in `reasons` uses applicable allow-rule `@deny_message` hints; `suggested_fixes` uses suggestions from routes not classified as blocked. On `IsAuthorized` allowlist rules, `@tool_pattern` and `@url_pattern` filter suggestions to matching actions; without them, there is no action-pattern restriction. Suggestions on `Unauthorized` denylist rules are provided when those rules fire. A missing metadata row, a JSON path using the wrong field names, and an omitted ancestry gate can each leave a rule unmatched. Check the recorded inputs and metadata shapes before interpreting an unmatched rule as a policy decision about data that was never supplied. ## Static analysis [Section titled “Static analysis”](#static-analysis) ```sh python3 scripts/validate_policy.py --analyze my_policy.dl python3 scripts/validate_policy.py --analyze --json my_policy.dl ``` The script tries a configured engine first and otherwise falls back to local validation and the `policy-analyze` binary. Add `--no-rpc` to require the local path. Local analysis may build that binary from the checkout. The report identifies overlaps between allow and deny rules, redundancy, and conditional reachability. An intentional broad allow with narrower denials can be an expected carve-out rather than an error. Inspect the reported conditions against the policy’s intended behavior. Analysis covers a supported subset of the language. User `@functor` calls are modeled symbolically, not executed to establish their meaning. Some Soufflé built-in expressions, such as `strlen(...)`, are explicitly unsupported by the full analysis pipeline. An unsupported or inconclusive result does not invalidate an otherwise compilable policy, and it is not a proof that the policy is correct. Generated diagnostics reserve relation names beginning with `SasyAllow`; do not use that prefix for your own relations. See [security limits](/limits/#policy-analysis-and-diagnostics) for analysis and runtime bounds, and [configuration](/configuration/) for evaluation deadlines. # Start writing policies > Small SASY policy examples and the Datalog basics needed to read them. A SASY policy answers a question about a proposed action: may this authenticated caller perform it, given the recorded context? Policies use Soufflé Datalog in `.dl` files. The engine supplies the common types and relations; your file adds rules. ## A small policy [Section titled “A small policy”](#a-small-policy) Save this as `read-only.dl`: ```prolog // Allow Read calls. Other tool names have no allowlist match. IsAuthorized(idx) :- Actions(idx, action), IsTool(action, "Read"). // @deny_message: Writes are disabled in this session // @suggestion: Read the existing file and describe the proposed change Unauthorized(idx) :- Actions(idx, action), IsTool(action, "Write"). ``` The first rule allows a `Read` call. The second explicitly blocks `Write` and provides feedback. An action with no allowlist match is not authorized; a hard denial wins even if an allow rule also matches. Bind the file to a session with `sasy.session(policy=Path("read-only.dl"))`, as in [use the SDK directly](/quickstart/). The engine compiles it when the session binds. The application checks the actual proposed action before executing it. This policy checks tool names; it does not restrict which files `Read` may access. ## Facts and rules [Section titled “Facts and rules”](#facts-and-rules) A **relation** is a table of facts. `Actions` contains the proposed actions, `Principal` identifies the authenticated caller, and `Edge` records message dependencies. The engine supplies those facts; your rules derive new ones. Read `IsAuthorized(idx) :- Actions(idx, action), IsTool(action, "Read").` as: “put `idx` on the allowlist if that action is a Read tool call.” * Commas mean AND. Separate rules with the same head mean OR. * Variables join matching values across relations. `_` matches any value without retaining a binding; quoted strings are constants. * Rules end with a period. `//` starts a comment. * Declare a relation you introduce with `.decl`; common relations are already declared by the engine. A check can propose several actions. `idx` is their zero-based index, shared by allow and denial results. A tool action is a tagged value, such as this input fact: ```prolog Actions(0, $CallTool("Read", "{\"file_path\":\"notes.txt\"}")). ``` The application supplies this fact; do not hard-code it in a policy. `$CallTool` contains the tool name and a JSON argument string. ## Read an argument [Section titled “Read an argument”](#read-an-argument) An allow rule can constrain the action’s arguments: ```prolog IsAuthorized(idx) :- Actions(idx, action), action = $CallTool("publish", args), @json_get_str(args, "destination") = "internal". ``` `@json_get_str` reads a string field. A missing field does not match `"internal"`, so this rule alone does not allow a publication with no destination. More rules can inspect recorded messages, successful tool results, and authenticated roles. ## Continue writing policies [Section titled “Continue writing policies”](#continue-writing-policies) | Page | What it explains | | ------------------------------------------------- | ---------------------------------------------------------------------------------------- | | [Core relations](/policies/core-relations/) | Actions, authorization, identity, message fields, and dependency direction. | | [Built-ins and feedback](/policies/reference/) | More relations, JSON and text functors, denial reasons, and approval notation. | | [Extension points](/policies/extensions/) | Metadata scopes and producer APIs, policy-specific relations, and custom functors. | | [Cookbook](/policies/cookbook/) | Rules for tool arguments, information flow, approvals, roles, and unknown-origin inputs. | | [Validation and debugging](/policies/validation/) | Compilation, behavioral checks, denial traces, and static analysis. | | [Dependency relevance](/policies/relevance/) | The IDB relevance gates, automatic inference, and safe ways to narrow traversal. | To check a file before binding it, see [validation](/policies/validation/). For observations supplied by a specific framework, see the integration guides and the [LangChain](/reference/langchain-records/) or [ADK](/reference/google-adk-records/) record references. # Use the SDK directly > Connect the Python SDK to a running engine, bind a policy you wrote, and check two proposed actions. This tutorial binds a small policy to a session and checks two proposed actions with the Python SDK. It prints the decisions without dispatching either tool. For a framework agent, start with [SDK usage patterns](/sdk/). ## Connect the SDK [Section titled “Connect the SDK”](#connect-the-sdk) Follow the [quick start](/get-started/) to install the SDK and run `sasy engine start`. It saves a selected local connection profile in `~/.sasy`, which the Python SDK uses from any project directory. ## Write a policy [Section titled “Write a policy”](#write-a-policy) Save this policy as `read-only.dl`: ```prolog IsAuthorized(idx) :- Actions(idx, action), IsTool(action, "Read"). // @deny_message: Writes are disabled in this session // @suggestion: Read the existing file and describe the proposed change Unauthorized(idx) :- Actions(idx, action), IsTool(action, "Write"). ``` The engine compiles and validates the policy when the session starts, including when it runs in Docker. No local compiler is needed for this tutorial. Save the following as `first_check.py` in that directory and run `python first_check.py` in the environment where you installed SASY. Keep the file beside `read-only.dl`. ```python import json from pathlib import Path import sasy with sasy.session(policy=Path("read-only.dl")): read = sasy.check_tool_call("Read", json.dumps({"file_path": "notes.txt"})) write = sasy.check_tool_call("Write", json.dumps({"file_path": "notes.txt", "content": "hello"})) print("Read:", read.authorized) # True print("Write:", write.authorized) # False print(write.denial_reasons) ``` The first two output lines are `Read: True` and `Write: False`; the denial reasons include “Writes are disabled in this session.” The allow rule permits `Read`; the deny rule rejects `Write` and supplies the reason. Other tool names have no allow rule and are denied. This example checks tool names; add argument conditions to restrict which paths may be read. ## When it does not work [Section titled “When it does not work”](#when-it-does-not-work) * **`UNAUTHENTICATED`, or a TLS failure on connect.** `SASY_API_KEY` and `TLS_CA_PATH` (or `ca_path`) must belong to the running engine. `sasy engine start` refreshes its local profile. Exported environment variables and project `.env` settings take precedence; update or remove stale overrides. See [troubleshooting](/local-engine/#troubleshooting) for the make-based setup. * **An error when the `with sasy.session(...)` block is entered.** That is where the policy is compiled, so a syntax error or an undeclared relation surfaces here. Check the error against your policy source. * **Everything is denied.** A session with no policy of its own uses the tenant default, and a new store’s default denies everything. ## Connect a tool handler [Section titled “Connect a tool handler”](#connect-a-tool-handler) Run the tool only when `decision.authorized` is true. For rules about the inputs behind a call, also record each message with `sasy.record`, together with the messages it was computed from, and pass the requesting message’s ID to the check: ```python import json from pathlib import Path import sasy with sasy.session(policy=Path("policy.dl")): task = sasy.record("Summarize the report and email the team", role="user") report = sasy.record(report_text, result_of=("read_document", {"name": "report"})) request = sasy.record(model_reply, role="llm", inputs=[task, report], tool_calls=[("send_email", args)]) decision = sasy.check_tool_call("send_email", json.dumps(args), input_node_ids=[request]) # Conditional approvals (transform_ids) are treated as denials here. if decision.authorized and not decision.transform_ids: result = send_email(**args) sasy.record(result, inputs=[request], result_of=("send_email", args)) ``` `sasy.record` returns each message’s ID; `inputs` become edges in the dependency graph, `tool_calls` lists the calls a message requests, and `result_of` marks a tool result so a policy can match it with `ToolResult`. Roles are `"system"`, `"user"`, `"llm"` and `"agent"` (the default). `sasy.record_async` is the async form. SASY decides; your code enforces by running the tool only when it is allowed. A decision with `transform_ids` allows the call only with those credential transforms applied, so a loop that does not apply them treats it as denied. [Add a framework](/instrumentation/) explains which messages and edges to record, and the supplied [framework adapters](/sdk/) do this for you. Continue with [policy language](/policy-language/) for rules over arguments, roles, approvals, and ancestry. # ADK records for policies > Read ADK text, function calls, results, and metadata in policies. Use this reference when a policy needs fields from a Google ADK message. For setup and supported execution, see the [Google ADK guide](/integrations/google-adk/). ## Record representation [Section titled “Record representation”](#record-representation) ADK groups message parts into a `Content`; the adapter records one node per part. | Part or resource | What a policy reads | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | Text part | Its text in `SentMessage(id, msg)` → `msg.contents`. | | Function call | Its tool name and arguments; argument JSON uses the original field names. | | Function result | Its response as ordinary JSON in `msg.contents`. Only a guarded tool’s successful return establishes `ToolResult(id, tool, args)` evidence. | | State or artifact read | Resource details, provenance, and value in `msg.contents`; metadata repeats this text under `s:text`. | | Any recorded part | The source part as JSON in `MessageMetadata(id, md)`. | For ordinary tool arguments and results, use paths such as `destination.account`. Metadata uses prefixed paths such as `s:function_call.s:args.s:destination.s:account`. ## Read part metadata [Section titled “Read part metadata”](#read-part-metadata) String dictionary keys in metadata have an `s:` prefix at every level. Common paths are: | Part field | Metadata path | | ---------------------------- | -------------------------------------------------------- | | Text | `s:text` | | Function-call name or ID | `s:function_call.s:name`, `s:function_call.s:id` | | Function-call arguments | `s:function_call.s:args` | | Function-response name or ID | `s:function_response.s:name`, `s:function_response.s:id` | | Function-response value | `s:function_response.s:response` | For example, a call to `pay(amount=5)` with ID `c1` has metadata shaped like: ```json {"s:function_call":{"s:args":{"s:amount":5},"s:id":"c1","s:name":"pay"}} ``` Read the call ID with `@json_get_str_path(md, "s:function_call.s:id")` after joining `MessageMetadata(id, md)`. Read the amount with `@json_get_int_path(md, "s:function_call.s:args.s:amount")`. Scope such rules with `Current(id)` for direct action inputs or `CurrentDepends(id)` for ancestors. A message without metadata has no `MessageMetadata` row. See [JSON functions](/policies/reference/#json-functors) and [core relations](/policies/core-relations/) for ancestry rules. ## Value representation and limits [Section titled “Value representation and limits”](#value-representation-and-limits) Metadata uses the [same key prefixes and value wrappers as LangChain records](/reference/langchain-records/#value-representation-and-limits), including wrappers for bytes, tuples, sets, and ordered dictionaries. Tool arguments and result text use ordinary JSON instead. Other serializable Python values in metadata use a `py::` wrapper around their JSON rendering. Enum wrappers contain the member name under `enum` and its encoded value under `value`. Such renderings may omit object state; use ordinary JSON fields for values your policy needs to inspect. Values that cannot be serialized in the required representation stop the run. The supported part fields are text, function calls, function responses, and thought markers. `Part.part_metadata` and other unsupported part fields stop the turn before recording, so policies cannot read them. Saved artifact provenance is matched on the stored version’s ordinary JSON text. Metadata participates in snapshot identity. Snapshots can differ across Pydantic or adapter versions, including older encodings of `OrderedDict`. # LangChain records for policies > Read LangChain message content, tool evidence, and metadata in policies. Use this reference when a policy needs fields from a LangChain message. For setup and supported execution, see the [LangChain guide](/integrations/langchain/). ## Record representation [Section titled “Record representation”](#record-representation) | Policy data | What it contains | | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `SentMessage(id, msg)` → `msg.contents` | The message’s string content, or structured content blocks encoded as JSON using the representation below. | | Tool-call arguments | Ordinary JSON with the tool’s argument names, without metadata key prefixes. | | `ToolResult(id, tool, args)` | Evidence that a guarded tool ran successfully, with its name and arguments. Supplied historical tool messages do not establish this evidence. | | `MessageMetadata(id, md)` | The source message as JSON, including content, message type, name, LangChain ID, tool calls, `additional_kwargs`, and response metadata. | Use message contents and tool evidence for ordinary content and action rules. Use metadata for fields that message contents do not show. ## Read message metadata [Section titled “Read message metadata”](#read-message-metadata) String dictionary keys have an `s:` prefix at every level. For example, `additional_kwargs={"marker": "exfil"}` appears in metadata as `{"s:additional_kwargs": {"s:marker": "exfil"}, ...}`. | Message field | Metadata path | | ------------------------------------- | ----------------------------- | | Message type, such as `human` or `ai` | `s:type` | | LangChain message ID | `s:id` | | Message name | `s:name` | | An `additional_kwargs` entry | `s:additional_kwargs.s:` | | A response metadata entry | `s:response_metadata.s:` | This block denies `publish` when a current input or any ancestor carries the `exfil` marker. Add it alongside your ordinary allow rules: ```prolog CurrentDependsPolicyRelevant() :- IsTool(_, "publish"). .decl MarkedMessage(id: symbol) MarkedMessage(id) :- Current(id), MessageMetadata(id, md), @json_get_str_path(md, "s:additional_kwargs.s:marker") = "exfil". MarkedMessage(id) :- CurrentDepends(id), MessageMetadata(id, md), @json_get_str_path(md, "s:additional_kwargs.s:marker") = "exfil". Unauthorized(idx) :- Actions(idx, a), IsTool(a, "publish"), MarkedMessage(_). ``` `CurrentDepends` covers ancestors; `Current` covers the direct inputs. A message without metadata has no `MessageMetadata` row and does not match these rules. See [core relations](/policies/core-relations/) and [JSON functions](/policies/reference/#json-functors) for query details, and [inputs of unknown origin](/integrations/langchain/#inputs-of-unknown-origin) for rules that recognize messages whose provenance could not be established. ## Value representation and limits [Section titled “Value representation and limits”](#value-representation-and-limits) Strings, numbers, booleans, nulls, and lists retain their JSON shapes. Dictionary keys are prefixed by type: `s:` for strings, `i:` for integers, and `b:` for base64-encoded bytes. Other supported Python values use these wrappers: | Python value | JSON representation | | -------------------- | -------------------------------------------------------------------------------------------------------------- | | `bytes`, `bytearray` | `{"bytes": ""}`, `{"bytearray": ""}` | | `tuple` | `{"tuple": [...]}` | | `set`, `frozenset` | `{"set": [...]}`, `{"frozenset": [...]}`; elements are sorted by their encoding. | | `OrderedDict` | `{"ordered_dict": [["s:key", "value"], ...]}`; entries retain their order and keys retain their type prefixes. | These shapes also apply inside structured message content. Convert unsupported values, such as `datetime`, `Decimal`, UUIDs, or enum members, before recording; values the adapter cannot represent stop the run. Non-finite numbers and invalid Unicode also stop the run. Metadata participates in snapshot identity, so an edit to it can invalidate a carried message reference. Snapshots can differ across Pydantic versions; in particular, older versions treat an `OrderedDict` value as a `dict`. # SDK usage patterns > Connect an agent to SASY, enable a framework adapter, and bind a policy to a session. Install the SDK and start the engine as shown in the [quick start](/get-started/). `sasy engine start` saves a selected client profile in `~/.sasy`; the Python SDK uses it across project directories unless you configure another endpoint. The common pattern is to call `sasy.instrument()` once at startup, then run an agent inside `sasy.session(policy=Path("policy.dl"))`. A session is SASY’s enforcement context, binding an agent’s execution trace to a policy. Pass a `Path` for a policy file; a plain string is treated as policy source. The engine compiles and validates the policy when the session starts. By default, automatic instrumentation is active only within a session context manager. See [configuration options](/configuration/#session-lifetime-and-background-work) to enable process-wide instrumentation, and [client configuration](/configuration/#python-client-and-session-policy) to set an explicit endpoint or other options with `sasy.configure(...)`. Sessions are independent; to express policies that take the traces of multiple interacting agents into account, run them in the same session. ## LangChain [Section titled “LangChain”](#langchain) Call `sasy.instrument()` before building an agent with `create_agent`, using your application’s LangChain `model` and `tools`. The adapter records model messages and checks tool calls before dispatch: ```python from pathlib import Path import sasy from langchain.agents import create_agent sasy.instrument() agent = create_agent(model, tools) with sasy.session(policy=Path("policy.dl")): result = agent.invoke({"messages": [{"role": "user", "content": "Your task"}]}) ``` Run the [LangChain example](/examples/#langchain-information-flow) for a complete scripted example, then see the [LangChain guide](/integrations/langchain/) for supported compositions. ## Google ADK [Section titled “Google ADK”](#google-adk) Instrument your ADK `Runner` and execute it within a SASY session: ```python from pathlib import Path import sasy sasy.instrument() with sasy.session(policy=Path("policy.dl")): async for event in runner.run_async( user_id=user_id, session_id=adk_session_id, new_message=user_content, ): show(event) ``` The [ADK example](https://github.com/sasy-labs/sasy/tree/main/examples/adk-separation-of-duties) is runnable; the [ADK guide](/integrations/google-adk/) describes supported runner and agent paths. ## Langroid [Section titled “Langroid”](#langroid) Instrument your configured Langroid `task` and execute it within a SASY session: ```python from pathlib import Path import sasy sasy.instrument() with sasy.session(policy=Path("policy.dl")): result = task.run("Your task") ``` See the [Langroid example](https://github.com/sasy-labs/sasy/tree/main/examples/langroid-information-flow) and [Langroid guide](/integrations/langroid/) for team handoffs and supported tool behavior. ## Your own agent loop [Section titled “Your own agent loop”](#your-own-agent-loop) Record messages and dependencies produced by your system, and check the authorization of actions before they execute: ```python import json from pathlib import Path import sasy with sasy.session(policy=Path("policy.dl")): task = sasy.record("Summarize the report and email the team", role="user") report = sasy.record(report_text, result_of=("read_document", {"name": "report"})) request = sasy.record(model_reply, role="llm", inputs=[task, report], tool_calls=[("send_email", args)]) decision = sasy.check_tool_call("send_email", json.dumps(args), input_node_ids=[request]) if decision.authorized: result = send_email(**args) sasy.record(result, inputs=[request], result_of=("send_email", args)) else: print(decision.denial_reasons) ``` `sasy.record` returns the message’s ID; its `inputs` become edges in the dependency graph over which policies operate. The built-in framework adapters make these calls for you; see [add a framework](/instrumentation/) to integrate yours. See [use the SDK directly](/quickstart/) for more on recording and authorization.