Metadata-Version: 2.4
Name: runlayer-hooks-sdk
Version: 0.4.0
Summary: Runlayer Hooks SDK for Python agent runtimes
Project-URL: Homepage, https://runlayer.com
Project-URL: Documentation, https://docs.runlayer.com/
Author-email: Runlayer <engineering@runlayer.com>
License: Apache-2.0
License-File: LICENSE
Keywords: agent,llm,mcp,runlayer,security
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: httpx==0.28.1
Description-Content-Type: text/markdown

# Runlayer Hooks Python SDK

Python SDK companion to `@runlayer/hooks-sdk`.

## Configure

```sh
export RUNLAYER_BASE_URL="https://your-runlayer-instance.com"
export RUNLAYER_API_KEY="rl_..."
```

For cloud installations that authenticate with a shared organization API key
(`rl_org_...`), also name the Runlayer user the deployment runs as so sessions
and enforcement are attributed to it:

```sh
export RUNLAYER_API_KEY="rl_org_..."
export RUNLAYER_USER_EMAIL="svc-my-agent@your-company.com"
```

The identity can be a service user provisioned just for the deployment; events
sent before that user exists in the workspace are buffered and replayed once it
does. The organization key must carry the AI Watch scan role. `user_email` is
also available as a `RunlayerClient` constructor option; it applies only to API
key auth (agent accounts express the acting user via `subject_token`).

Agent account auth is also supported:

```sh
export RUNLAYER_BASE_URL="https://your-runlayer-instance.com"
export RUNLAYER_AGENT_CLIENT_ID="client_..."
export RUNLAYER_AGENT_CLIENT_SECRET="..."
```

Optional OBO subject fields:

```sh
export RUNLAYER_AGENT_SUBJECT_TOKEN="user@example.com"
export RUNLAYER_AGENT_SUBJECT_TOKEN_TYPE="urn:runlayer:token-type:user-email"
```

The SDK mints an agent token with `client_credentials` and, when an OBO subject
is configured, exchanges it via RFC 8693 token exchange
(`urn:ietf:params:oauth:grant-type:token-exchange`); both tokens are cached and
refreshed internally.

Optional runtime controls:

| Variable | Purpose |
| --- | --- |
| `RUNLAYER_HOOK_TIMEOUT_MS` | Hook request timeout. Defaults to `10000`. |
| `RUNLAYER_HOOK_MAX_TOOL_OUTPUT_BYTES` | Maximum serialized tool output sent to Runlayer. Defaults to `65536`. |
| `RUNLAYER_HOOK_ENFORCEMENT_FAILURE_MODE` | Defaults to `closed`; set to `open` only if tool calls should continue when Runlayer is unreachable. |
| `RUNLAYER_ALLOW_INSECURE_TRANSPORT=1` | Allow non-HTTPS `RUNLAYER_BASE_URL` for local development. |

## Usage

```python
from runlayer_sdk import RunlayerClient

runlayer = RunlayerClient.from_env(client_version="my-agent/1.0.0")


def run_local_tool(tool_input: dict[str, object]) -> str:
    return "tool output"


output = runlayer.run_tool(
    execute=run_local_tool,
    session_id="session-id",
    tool_input={"command": "cat README.md"},
    tool_name="Bash",
    tool_type="shell",
)
```

Use `tool_enforcement` to skip Runlayer-owned MCP tools or proxy URLs:

```python
runlayer = RunlayerClient.from_env(
    tool_enforcement={
        "ignored_mcp_server_names": ["github-preview"],
        "skip_runlayer_mcp_proxy_urls": True,
    }
)
```

`RunlayerClient` exposes:

- `emit_event`
- `before_prompt`
- `before_tool`
- `after_tool`
- `run_tool`
- `should_enforce_tool`

The package also exports `send_runlayer_preflight`.

## Prompt Guard

Call `before_prompt` (or `before_prompt_async`) before sending user text to your
model. It records the `UserPromptSubmit` event, scans the prompt (and optional
system prompt), and raises `RunlayerBlockedError` when Runlayer blocks it:

```python
from runlayer_sdk import RunlayerBlockedError

try:
    runlayer.before_prompt(
        prompt=user_text, session_id=session_id, system_prompt=system_prompt
    )
except RunlayerBlockedError:
    return "I can't help with that request."
```

Pass `system_prompt` whenever your bot has one: Prompt Guard scans the user
prompt against it and catches more attacks with it. The Claude Agent SDK hooks
and the Google ADK plugin send only the user prompt, so call `before_prompt`
yourself to give Prompt Guard that context.

The `RunlayerBlockedError` message carries Runlayer's violation details for
your logs; don't show it to end users. The Claude Agent SDK hooks reply with
`blocked_prompt_message` and the Google ADK plugin with `blocked_message`; both
default to `DEFAULT_BLOCKED_PROMPT_MESSAGE` ("Sorry, I can't help with that
request.").

Runlayer only blocks a prompt when all of these hold:

- The client hooks integration is enabled for the workspace, and Prompt Guard
  is enabled and set to Block (the default is Alert, which only records
  detections).
- The workspace's AI Watch mode isn't Monitor.
- Runlayer can attribute the prompt to a workspace member: a user API key, an
  agent account, or an organization key with `RUNLAYER_USER_EMAIL` /
  `user_email` set to a workspace user's email. A bot's end customers usually
  aren't workspace users, so use the bot owner's or a service user's email.
  If Runlayer can't attribute the prompt, it skips the scan and allows it.

Prompt checks always fail open, whatever `enforcement_failure_mode` says: a
network error, timeout (at most 6 seconds), or server error lets the prompt
through. If Runlayer rejects the scan or the agent account's token request with
a 401 or 403 (a bad key, or a firewall), the client logs one warning.
`before_prompt_async` and the ADK plugin run the check on asyncio's default
thread pool, and the 6 seconds start once a thread is free; a bot that takes
many prompts at once should size that pool (`loop.set_default_executor`) to
match. A scan
request carries at most 5 MB; past that, the system prompt is trimmed first,
then the prompt. A prompt over the workspace's scan payload budget
follows that budget's action: skipped, truncated, or blocked. The Claude Agent
SDK hooks and the Google ADK
plugin below call it for you.

## Troubleshooting: sessions not appearing

Lifecycle hooks send events best-effort and do not raise on their own. If the
server accepts an event but does not record it, it responds with
`status: "ignored"` and a `reason`. The client logs a one-time warning to stderr
for the actionable reasons so a misconfiguration is not silent:

- `client_not_enabled` — the SDK session-monitoring client is off for this
  workspace. Enable the client (and any required SDK toggle) in Runlayer
  settings. This is a separate switch from tool enforcement, so both must be on
  to get full session + tool telemetry.
- `sessions_disabled` — the applicable MDM configuration disables session
  reporting. Ask a Runlayer administrator to enable **Sessions** in that MDM
  configuration.
- `actor_unresolved` — the request authenticated but Runlayer could not map it
  to a user/agent. With an organization API key, set `RUNLAYER_USER_EMAIL` (or
  the `user_email` client option) to the Runlayer user the deployment runs as;
  events are buffered until that user exists in the workspace. Otherwise use a
  personal API key (`RUNLAYER_API_KEY`) or agent-account credentials
  (`RUNLAYER_AGENT_CLIENT_ID` / `RUNLAYER_AGENT_CLIENT_SECRET`).

Set `RUNLAYER_HOOK_DEBUG=1` to also log transient ignore reasons and network
failures. Run `send_runlayer_preflight()` for an explicit check.

## Framework tool adapters

Dependency-free adapters wrap common tool dictionary shapes:

- `with_runlayer_vercel_ai_tool`
- `with_runlayer_vercel_ai_tools`
- `with_runlayer_openai_agents_tool`
- `with_runlayer_google_adk_tool`
- `run_runlayer_adapter_tool`

## Claude Agent SDK hooks

Use the adapter helpers when a Python agent runtime wants the same Claude Agent
SDK hook output shapes as the Hooks TypeScript SDK:

```python
from runlayer_sdk import RunlayerClient, create_claude_agent_sdk_hooks

runlayer = RunlayerClient.from_env()
hooks = create_claude_agent_sdk_hooks(runlayer, include_stop=False)
```

The adapter exports:

- `create_claude_agent_sdk_hooks`
- `emit_claude_agent_sdk_transcript_stop`
- `claude_agent_sdk_assistant_message_to_transcript_line`
- `tool_type_from_name`

TypeScript-style camelCase aliases are also available for SDK parity.

Each `query()` call starts a new Claude Agent SDK session with a fresh
`session_id`, and Runlayer records each session id as a separate session. To
keep a multi-prompt conversation in a single Runlayer session, resume the
previous session on follow-up calls (leave `fork_session` unset so the session
id is preserved), then emit the transcript `Stop` per run as usual:

```python
options = ClaudeAgentOptions(
    hooks=create_claude_agent_sdk_hooks(runlayer, include_stop=False),
    resume=session_id,  # session_id captured from the previous run's init message
)
```


## Google ADK lifecycle plugin (Python)

Install ADK separately; importing the SDK or using the existing dictionary tool
wrapper does not require ADK. Available in Hooks SDK 0.3.0. The native plugin requires `google-adk[mcp]>=2.11,<3`
and is tested with `google-adk[mcp]==2.11.0` on Python 3.10 and 3.13.

```sh
uv add 'runlayer-hooks-sdk>=0.4.0' 'google-adk[mcp]==2.11.0'
```

```python
from google.adk.agents import LlmAgent
from google.adk.apps import App
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from runlayer_sdk import RunlayerClient, create_google_adk_plugin


def search_tickets(query: str) -> dict[str, str]:
    """Search support tickets."""
    return {"query": query}


runlayer = RunlayerClient.from_env()
plugin = create_google_adk_plugin(runlayer, model="gemini-2.5-flash")
runner = Runner(
    app=App(
        name="support",
        root_agent=LlmAgent(
            name="assistant", model="gemini-2.5-flash", tools=[search_tickets],
        ),
        plugins=[plugin],
    ),
    session_service=InMemorySessionService(),
)
# Create an ADK session, then consume runner.run_async(...) normally.
# At application shutdown: await runner.close()
```

Each invocation emits `SessionStart`, a `UserPromptSubmit` for new user text,
local/MCP tool events, and a transcript-bearing `Stop` on completion or an
unhandled run error. A prompt that Prompt Guard blocks ends the invocation with
`blocked_message` as the model reply, before any model or tool call; the ADK
session stores `[Blocked by Runlayer]` instead of the prompt, so later turns
never replay it. If a plugin listed before Runlayer returns content from
`on_user_message_callback`, ADK skips Runlayer's; the plugin then scans the
rewritten message before the run, and still ends a blocked run. The session
keeps that message, but records the blocked invocation in session state
(`runlayer_blocked_prompt_invocations`), and the plugin swaps the message for
the placeholder in later model requests, including after a restart or on
another worker; resuming a blocked invocation ends it again with
`blocked_message`. That record is written from `on_event_callback`, so a plugin
listed before Runlayer that returns an event from its own `on_event_callback`
must not do so for the block's reply. `Stop` ends the turn, not the conversation; no
`SessionEnd` is invented. Reuse the ADK app/user/session identity across turns
to keep one Runlayer conversation. Concurrent identities have separate state.
The session ID is correlation metadata, not authentication: the configured
Runlayer client still owns user/agent attribution. Use appropriately scoped
clients and credentials when acting on behalf of different users.

Completed assistant text and available ADK thought-summary text are recorded;
partial streaming events are ignored and completed event IDs deduplicated.
Opaque thought signatures and image/audio/file contents are omitted. This does
not expose hidden model reasoning. Assistant timestamps record when completed
messages are observed; `provider_event_timestamp` preserves the original ADK
time without changing ADK events. The plugin does not estimate token usage.

`max_transcript_bytes` defaults to 256 KiB per invocation. Once the next complete
entry would exceed it, remaining entries are omitted and the `Stop` payload
contains `transcript_truncated: true`. Tool outputs use the client's existing
`max_tool_output_bytes` limit. Buffers are released on completion/error. ADK
2.11 does not call completion/error plugins on task cancellation: cancelled
buffers are discarded when ADK releases the invocation context or the runner
is closed, and a final `Stop` is not guaranteed. Consume or explicitly close
run iterators, and close the runner during shutdown.

Lifecycle delivery uses `emit_event` best-effort behavior. A server
`status: "ignored"` follows the client's warning behavior. Use
`send_runlayer_preflight` to check ingestion. Local tool enforcement follows the
client's existing fail-closed default, including argument/output rewriting and deny results.
Tool/run errors continue to propagate even if error reporting fails.

### Correlate Runlayer MCP calls

Supply the actual endpoint for each tool through `tool_url`. The client uses
its existing URL/enforcement rules to skip duplicate scanning of Runlayer
proxy calls. Skipped tools still emit observation-only input/result/error
telemetry. Unrecognized/direct MCP tools retain SDK enforcement. A tool name
alone does not prove it is routed through the gateway.

```python
from google.adk.tools.mcp_tool import McpTool, McpToolset, StreamableHTTPConnectionParams
from runlayer_sdk import create_google_adk_plugin, google_adk_session_headers

# Use the endpoint and authentication from your existing Runlayer MCP setup.
gateway_url = "https://your-runlayer-instance.com/api/v1/proxy/YOUR_SERVER_ID/mcp"
toolset = McpToolset(
    connection_params=StreamableHTTPConnectionParams(
        url=gateway_url, headers=existing_auth_headers,
    ),
    header_provider=google_adk_session_headers,
)
plugin = create_google_adk_plugin(
    runlayer,
    tool_url=lambda tool: gateway_url if isinstance(tool, McpTool) else None,
)
# Include toolset in the agent's tools, and plugin in App.plugins.
```

That resolver assumes all MCP tools in this runner use this endpoint; map each
actual tool to its own endpoint when using multiple servers. The header helper
sets `x-runlayer-session-id` to `google_adk_session_id(context)`, matching SDK
session events. ADK preserves static connection headers. If you already have a
dynamic `header_provider`, merge its result with
`google_adk_session_headers(context)` rather than replacing authentication.
Gateway audit/scanner records correlate through this header; the plugin's
observation events do not create a second policy scan. The helper does not mint
MCP tokens or change OAuth/resource scopes; keep existing MCP authentication.

Register one Runlayer plugin per runner, last in `App.plugins`. Earlier tool
callbacks may transform arguments/results in place, but must return `None`:
returning a value short-circuits later plugins, including Runlayer. ADK runs
agent-level `before_tool_callback` and `after_tool_callback` after plugins, so
those callbacks must be read-only and return `None`; move transformations into
an earlier plugin. Do not also wrap the same local tools with
`with_runlayer_google_adk_tool` or `run_tool`, which would enforce twice. The
existing dictionary wrapper remains available unchanged. This native lifecycle
plugin is Python-only; the TypeScript ADK adapter still wraps tools only.
