Metadata-Version: 2.4
Name: runlayer-hooks-sdk
Version: 0.3.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_tool`
- `after_tool`
- `run_tool`
- `should_enforce_tool`

The package also exports `send_runlayer_preflight`.

## 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.3.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. `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.
