Metadata-Version: 2.5
Name: oi-starship-helm
Version: 0.2.0
Summary: Standalone governance SDK wrapping the Microsoft Agent Governance Toolkit (AGT) behind a stable, layer-modular interface.
Author: Orion Innovation
License-Expression: MIT
License-File: LICENSE
License-File: NOTICE
License-File: agent_sre/LICENSE
Keywords: agent-governance-toolkit,ai-agents,governance,kill-switch,langchain,langgraph,policy
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
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 :: Security
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.10
Requires-Dist: pydantic<3.0,>=2.0
Requires-Dist: pyyaml>=6.0
Provides-Extra: a2a
Requires-Dist: agent-governance-toolkit-core[full]<6,>=5.0; extra == 'a2a'
Provides-Extra: assurance
Requires-Dist: agent-governance-toolkit-compliance<6,>=5; extra == 'assurance'
Provides-Extra: compliance-reporting
Requires-Dist: agent-governance-toolkit-core[full]<6,>=5.0; extra == 'compliance-reporting'
Provides-Extra: dev
Requires-Dist: build>=1.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Provides-Extra: discovery
Requires-Dist: agent-discovery; extra == 'discovery'
Provides-Extra: full
Requires-Dist: agent-governance-toolkit-cli; extra == 'full'
Requires-Dist: agent-governance-toolkit-compliance<6,>=5; extra == 'full'
Requires-Dist: agent-governance-toolkit-core[full]<6,>=5.0; extra == 'full'
Requires-Dist: agent-marketplace; extra == 'full'
Requires-Dist: agent-rag-governance; extra == 'full'
Requires-Dist: agentmesh-lightning; extra == 'full'
Provides-Extra: identity-trust
Requires-Dist: agent-governance-toolkit-core[full]<6,>=5.0; extra == 'identity-trust'
Provides-Extra: mcp-governance
Requires-Dist: agent-governance-toolkit-core[full]<6,>=5.0; extra == 'mcp-governance'
Provides-Extra: policy
Requires-Dist: agent-governance-toolkit-core[full]<6,>=5.0; extra == 'policy'
Requires-Dist: cedarpy<5,>=4.8; extra == 'policy'
Provides-Extra: rag-governance
Requires-Dist: agent-rag-governance; extra == 'rag-governance'
Provides-Extra: reliability
Provides-Extra: runtime
Requires-Dist: agent-governance-toolkit-core[full]<6,>=5.0; extra == 'runtime'
Provides-Extra: sandbox
Requires-Dist: agent-governance-toolkit-cli; extra == 'sandbox'
Provides-Extra: storage-azure
Requires-Dist: azure-identity>=1.17; extra == 'storage-azure'
Requires-Dist: azure-storage-blob>=12.19; extra == 'storage-azure'
Provides-Extra: storage-cosmos
Requires-Dist: azure-cosmos>=4.5; extra == 'storage-cosmos'
Provides-Extra: storage-gcp
Requires-Dist: google-cloud-storage>=2.14; extra == 'storage-gcp'
Provides-Extra: storage-s3
Requires-Dist: boto3>=1.34; extra == 'storage-s3'
Provides-Extra: supply-chain
Requires-Dist: agent-marketplace; extra == 'supply-chain'
Provides-Extra: training-governance
Requires-Dist: agentmesh-lightning; extra == 'training-governance'
Description-Content-Type: text/markdown

# Starship Helm

**Governance for AI agents, in one call.**

![Python](https://img.shields.io/badge/python-3.10%2B-blue)
![License](https://img.shields.io/badge/license-MIT-green)
![Version](https://img.shields.io/badge/version-0.2.0-informational)

```bash
pip install oi-starship-helm      # import as starship_helm
```

---

## Overview

Starship Helm is a lightweight governance SDK for AI agents. Wrap any agent action in
`govern()` and every call is checked for identity, policy, kill-switch state and
reliability, then recorded to an audit trail — before your code runs.

Under the hood it is backed by the Microsoft Agent Governance Toolkit (AGT), but your application never imports AGT directly. Every AGT concern sits behind a stable
interface with a single adapter, so AGT upgrades touch one file in the SDK — not your
codebase.

## Key Features

- **One governed entry point** — `govern()` runs a fixed pipeline on every action:
  identity resolve → kill-switch check → guardrails & policy → trust/SLO update → audit.
- **Modular layers** — 12 governance layers, each enabled or disabled from config. A
  disabled layer falls back to a no-op adapter, with no code changes and no extra
  dependencies.
- **Framework adapters** — drop-in support for LangGraph, LangChain, Microsoft Agent
  Framework (MAF) and Google ADK.
- **Declarative configuration** — one YAML file with environment-variable expansion.
- **Pluggable storage** — local disk, in-memory, HTTP, S3-compatible, Azure Blob, Google
  Cloud Storage or Azure Cosmos DB.
- **Versioned audit schema** — export entries as flat database rows or OpenTelemetry-style
  log records.
- **Mirror hooks** — stream audit events, error budgets and trust scores into your own
  store, without ever blocking a governed call.

## Requirements

- Python **3.10+**
- `agent-governance-toolkit-core` **5.x** (installed automatically by the AGT-backed extras)
- [OPA CLI](https://www.openpolicyagent.org/docs/latest/#running-opa) on `PATH`, only if
  your workflows ship a `policy.rego`

## Installation

Install the base package, plus one extra per layer you want backed by AGT:

```bash
# Core governance layers
pip install "oi-starship-helm[identity-trust,policy,runtime,reliability]"

# Every layer
pip install "oi-starship-helm[full]"

# Optional cloud storage backends
pip install "oi-starship-helm[storage-s3]"      # or storage-azure, storage-gcp, storage-cosmos
```

| Extra | Enables |
|---|---|
| `identity-trust`, `policy`, `runtime` | Core `govern()` layers |
| `reliability` | Core SLO layer — its dependency ships vendored, so the base install already covers it |
| `sandbox`, `assurance`, `compliance-reporting`, `supply-chain`, `rag-governance`, `mcp-governance`, `training-governance`, `discovery`, `a2a` | Peripheral layers |
| `storage-s3`, `storage-azure`, `storage-gcp`, `storage-cosmos` | Cloud storage backends |
| `full` | All layer extras |

Layers left disabled need no extra.

## Quick Start

**1. Define policies** for each workflow under a policies directory. For a template of
each file, see [Policy Files](#policy-files).

```
policies/
└── orders/                         # one folder per workflow_id
    ├── mesh.yaml                   # agent roster (identity_trust)
    ├── policy.yaml                 # per-action rules (policy)
    ├── sre.yaml                    # SLO target (reliability)
    └── collective_policies.yaml    # optional: cross-agent limits
```

**2. Create `sdk.yaml`:**

```yaml
storage:
  backend: local
  root_dir: ./governance_data

policies_dir: ./policies

identity_trust:
  enabled: true      # true | false

policy:
  enabled: true      # true | false

runtime:
  enabled: true      # true | false

reliability:
  enabled: true      # true | false
```

**3. Govern an action:**

```python
from starship_helm import GovernanceSDK, GovernanceDenied

sdk = GovernanceSDK.from_yaml("sdk.yaml")

def issue_refund(action: dict) -> dict:
    return {"status": "refunded", "order_id": action["order_id"]}

try:
    result = sdk.govern(
        "orders",            # workflow_id
        "support-agent",     # role
        "issue_refund",      # action_type
        {"order_id": "O-1", "amount": 250},
        issue_refund,
        session_id="session-1",
    )
except GovernanceDenied as exc:
    print(f"Denied by {exc.rule}: {exc.reason}")
```

`issue_refund` runs only if every check passes. Every outcome is written to the audit
trail, whether the action succeeds, fails or is denied.

## Policy Files

Create one folder per `workflow_id` under `policies_dir`, containing these files.

**`mesh.yaml`**

```yaml
agents:
  - role: <role>
    did: <did>
    ring: <0-3>
    trust_score: <0.0-1.0>
    needs_approval: <true|false>
```

**`policy.yaml`**

```yaml
apiVersion: governance.toolkit/v1
name: <policy-name>
version: "1.0"
default_action: <allow|deny>
agents: ["*"]
rules:
  - name: <rule-name>
    condition: "<expression>"
    action: <allow|deny|require_approval|warn|log>
```

**`sre.yaml`**

```yaml
slo:
  target_success_rate: <0.0-1.0>
  window: "<window>"
```

**`collective_policies.yaml`** *(optional)*

```yaml
policies:
  - name: <rule-name>
    scope: multi-agent
    condition:
      aggregate: <count|sum|max|distinct_agents>
      window_seconds: <seconds>
      threshold: <number>
    action: <deny|alert|throttle>
    enabled: <true|false>
```

## Framework Integrations

If your agents run on a supported framework, attach the matching adapter instead of
calling `govern()` yourself. Every adapter takes the same `workflow_id`, `role` and
`session_id`.

| Framework | Adapter | Governs |
|---|---|---|
| Google ADK | `StarshipHelmPlugin` | Each tool call and agent run |
| Microsoft Agent Framework | `StarshipHelmMiddleware` | Each agent run or tool call |
| LangChain | `StarshipHelmCallbackHandler` | Each tool call |
| LangGraph | `govern_compiled_graph` / `wrap_node` | Each graph node |

```python
# Google ADK
from starship_helm.integrations.adk_adapter import StarshipHelmPlugin
runner = InMemoryRunner(agent=agent, app_name="orders",
                        plugins=[StarshipHelmPlugin(sdk, workflow_id="orders", role="risk_check", session_id=sid)])

# Microsoft Agent Framework
from starship_helm.integrations.maf_adapter import StarshipHelmMiddleware
agent = Agent(client=chat_client, name="refund_reviewer",
              middleware=[StarshipHelmMiddleware(sdk, workflow_id="orders", role="refund_reviewer",
                                                 action_type="review_refund", session_id=sid)])

# LangChain
from starship_helm.integrations.langchain_adapter import StarshipHelmCallbackHandler
handler = StarshipHelmCallbackHandler(sdk, workflow_id="orders", role="support-agent", session_id=sid)
refund_tool.invoke({"order_id": "O-1"}, config={"callbacks": [handler]})

# LangGraph
from starship_helm.integrations import govern_compiled_graph
graph = build_graph().compile()
govern_compiled_graph(sdk, graph, workflow_id="orders", role="support-agent",
                      session_id=lambda state, config: config["configurable"]["thread_id"])
```

For the full walkthrough, see the [Integration Guide](docs/INTEGRATION_GUIDE.md).

## Configuration

### YAML Configuration

`GovernanceSDK.from_yaml(path)` is cached per file path, so you can call it at every call
site without any cost after the first load. It supports:

- **Environment variables** — `${VAR}` or `${VAR:-default}` in any string value.
- **A shared `policies_dir`** — set it once at the top level and it applies to
  `identity_trust`, `policy` and `reliability`.
- **A `starship:` block** — connects the SDK to a Starship platform (see below).

For a complete runnable example, see [`docs/sdk.yaml`](docs/sdk.yaml). Build `SDKConfig` in
Python instead only if you need a custom `trust_store`, `backup_store` or mirror hook.

### Connecting to Starship

With `starship.enabled: true`, the SDK keeps the workflow's `policy.yaml` in sync with the
one saved in the Starship UI, and sends audit events, error budgets and trust scores to
Starship automatically. Sending happens in the background, so an unreachable Starship never
slows down or breaks `govern()`. With it off (the default), nothing leaves the process.

```yaml
starship:
  enabled: true
  url: ${STARSHIP_URL}
  key: ${STARSHIP_SDK_KEY}
  workflow_id: orders        # the slug the agent was registered with in Starship
```

Telemetry is not configured in YAML any other way: the old `audit_on_record`,
`reliability.on_error_budget` and `identity_trust.trust_store` keys are rejected with an
error pointing to `starship.enabled`.

### Enabling and Disabling Layers

Each layer has an `enabled` flag. Flipping it is the only change you need:

```yaml
reliability:
  enabled: false     # govern() keeps working; SLO recording becomes a no-op
```

The core layers (`identity_trust`, `policy`, `runtime`, `reliability`) are enabled by
default. Peripheral layers are disabled by default.

### Storage Backends

All SDK state — the audit trail, trust scores, kill-switch state and SLO snapshots — goes
through a single `storage` setting:

| Backend | Key settings | Extra |
|---|---|---|
| `local` *(default)* | `root_dir` | — |
| `memory` | — | — |
| `http` | `endpoint_url`, `api_key`, `headers` | — |
| `s3_compatible` | `s3_bucket`, `s3_endpoint_url`, `s3_region` | `storage-s3` |
| `azure_blob` | `azure_container`, `azure_connection_string` or `azure_account_url` | `storage-azure` |
| `gcs` | `gcs_bucket`, `gcs_project` | `storage-gcp` |
| `cosmos` | `cosmos_endpoint`, `cosmos_key`, `cosmos_database`, `cosmos_container` | `storage-cosmos` |

`s3_compatible` works with AWS S3, MinIO, Cloudflare R2, Backblaze B2 and other
S3-compatible services. An `http` endpoint needs to implement this contract on
`{endpoint_url}/{key}`:

| Method | Behavior |
|---|---|
| `GET` | `200` with the stored bytes, or `404` if the key is not found |
| `PUT` | Store the request body at the key; returns any `2xx` |
| `DELETE` | Remove the key; returns `2xx` or `404` |

### Mirror Hooks

Use the mirror hooks to copy governance state into a store you own, such as your
dashboard's database. A hook runs synchronously right after the state is finalized. If a
hook raises an error, the SDK logs it and the governed call continues unaffected.

| Hook | Configured on | Receives |
|---|---|---|
| `audit_on_record` | `SDKConfig` | Each finished audit entry |
| `on_error_budget` | `ReliabilityConfig` | Per-SLO error-budget snapshot |
| `trust_store` | `IdentityTrustConfig` | A `TrustStorePort` implementation (`load` / `seed` / `record_event`) |

These are set in Python, not in `sdk.yaml`. If the target is Starship, `starship.enabled:
true` wires all three automatically.

```python
from starship_helm import GovernanceSDK, SDKConfig
from starship_helm.layers.reliability.config import ReliabilityConfig

config = SDKConfig(
    audit_on_record=lambda entry: my_db.insert("audit_events", entry),
    reliability=ReliabilityConfig(
        policies_dir="./policies",
        on_error_budget=lambda row: my_db.upsert("error_budgets", row, key="slo_id"),
    ),
    ...
)
sdk = GovernanceSDK(config)
```

## Usage Examples

### Peripheral layers

```python
report = sdk.assurance.scan_prompt(system_prompt)
if report.is_blocking:
    raise RuntimeError(f"Prompt failed assurance scan: grade {report.grade}")

sdk.discovery.scan()                       # find agents running in this environment
shadow_agents = sdk.discovery.reconcile()  # agents not in your registry
```

### Agent-to-Agent (A2A)

```python
card = sdk.a2a.issue_agent_card(
    "orders", "support-agent",
    url="https://support-agent.example.com",
    capabilities=["issue_refund"],
)

if sdk.a2a.verify_peer("orders", "support-agent", peer_did="did:mesh:..."):
    sdk.a2a.create_task("orders", "support-agent", peer_did="did:mesh:...",
                        message={"order_id": "O-1"})
```

### Exporting audit events

```python
from starship_helm.audit import to_platform_row, to_otel_log_record

for entry in sdk.audit.entries:
    row = to_platform_row(entry)          # flat database row
    log = to_otel_log_record(entry)       # OpenTelemetry-style log record
```

Each entry carries `session_id`, `agent_id`, `use_case`, `action`, `tool`, `ring`, `result`
(`success`, `failure` or `denied`) and a free-form `attributes` map.

## Layer Reference

| Layer | Config class | Extra | In `govern()` |
|---|---|---|---|
| `identity_trust` | `IdentityTrustConfig` | `identity-trust` | ✅ |
| `policy` | `PolicyConfig` | `policy` | ✅ |
| `runtime` | `RuntimeConfig` | `runtime` | ✅ |
| `reliability` | `ReliabilityConfig` | *(built in)* | ✅ |
| `sandbox` | `SandboxConfig` | `sandbox` | — |
| `assurance` | `AssuranceConfig` | `assurance` | — |
| `compliance_reporting` | `ComplianceReportingConfig` | `compliance-reporting` | — |
| `supply_chain` | `SupplyChainConfig` | `supply-chain` | — |
| `rag_governance` | `RagGovernanceConfig` | `rag-governance` | — |
| `mcp_governance` | `McpGovernanceConfig` | `mcp-governance` | — |
| `training_governance` | `TrainingGovernanceConfig` | `training-governance` | — |
| `discovery` | `DiscoveryConfig` | `discovery` | — |
| `a2a` | `A2AConfig` | `a2a` | — |

You can reach every layer as an attribute of the SDK instance: `sdk.identity`,
`sdk.policy`, `sdk.runtime`, `sdk.reliability`, `sdk.sandbox`, `sdk.assurance`,
`sdk.compliance_reporting`, `sdk.supply_chain`, `sdk.rag_governance`, `sdk.mcp_governance`,
`sdk.training_governance`, `sdk.discovery` and `sdk.a2a`.

## Documentation

| Resource | Description |
|---|---|
| [Integration Guide](docs/INTEGRATION_GUIDE.md) | Step-by-step guide to integrating the SDK into your backend |
| [Example config](docs/sdk.yaml) | Annotated `sdk.yaml` |
| [Contributing](CONTRIBUTING.md) | Architecture, the layer pattern and development workflow |
| [Changelog](CHANGELOG.md) | Release history |

## Running Tests

```bash
pip install -e ".[dev]"
pytest tests
```

The test suite passes with no AGT packages installed.

## License

Released under the [MIT License](LICENSE).
