Metadata-Version: 2.4
Name: badgerflow
Version: 0.12.0
Summary: BadgerFlow Python SDK: governed pro-code agents, the platform REST client, and the bf / agiel CLIs
License-Expression: Apache-2.0
Keywords: langgraph,agents,llm,governance,badgerflow,mlops
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic>=2.12
Requires-Dist: pyjwt[crypto]>=2.10.1
Requires-Dist: openai>=2.45
Requires-Dist: typer>=0.17.5
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: rich>=13
Requires-Dist: jsonschema>=4.23
Provides-Extra: langgraph
Requires-Dist: langgraph<2,>=1.2; extra == "langgraph"
Requires-Dist: langchain-core<2,>=1.6; extra == "langgraph"
Requires-Dist: langchain-openai<2,>=1.6; extra == "langgraph"
Provides-Extra: otel
Requires-Dist: opentelemetry-sdk>=1.40; extra == "otel"
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.40; extra == "otel"
Requires-Dist: opentelemetry-instrumentation-httpx>=0.61b0; extra == "otel"
Requires-Dist: opentelemetry-instrumentation-logging>=0.61b0; extra == "otel"
Provides-Extra: server
Requires-Dist: fastapi<0.142,>=0.117; extra == "server"
Requires-Dist: uvicorn>=0.32.1; extra == "server"
Requires-Dist: prometheus_client>=0.20; extra == "server"
Provides-Extra: plugin
Requires-Dist: mcp<3,>=2.2; extra == "plugin"
Requires-Dist: starlette>=0.48; extra == "plugin"
Requires-Dist: uvicorn>=0.32.1; extra == "plugin"
Requires-Dist: prometheus_client>=0.20; extra == "plugin"
Provides-Extra: dev
Requires-Dist: pytest>=8.2; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
Requires-Dist: respx>=0.21; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Provides-Extra: langchain
Requires-Dist: langchain>=0.2; extra == "langchain"
Requires-Dist: langchain-core>=0.2; extra == "langchain"
Provides-Extra: crewai
Requires-Dist: crewai>=0.30; extra == "crewai"
Provides-Extra: autogen
Requires-Dist: pyautogen>=0.2; extra == "autogen"
Dynamic: license-file

# badgerflow

The Python SDK for building **pro-code agents** that run as your own service and
are governed by [BadgerFlow](https://github.com/facileai/agiel) anyway.

You deploy the container. BadgerFlow holds the release, the approval, the
guardrail profile, the spend and the audit trail. Your agent never handles a
credential and is never called by anyone but the platform.

## Install

```bash
pip install 'badgerflow[server,langgraph,otel]'
```

Install the extras the scaffold's Dockerfile will install — `server` and `otel`,
plus `langgraph` for `bf init --langgraph` — before `bf init`: the lock it
writes pins what this interpreter has, and `bf lock` refuses to write a lock
that would leave a requirement unpinned.

The developer guide, the pro-code support matrix and the Helm chart guide ship
inside the wheel: `bf docs` lists them and `bf docs developer-guide` prints the
one for the SDK version you installed (`--raw` for the Markdown, `--path` for
its location). They describe that version, not a later one.

Help and reporting: `bf support` prints where to report a problem and
`bf support bundle` writes the redacted report to send with it (`bf docs support`
for the full page). A security problem goes privately to your platform
operator's security contact — `bf docs security` says what counts and what to
expect. The SDK's repository is private and the package names no public
tracker; those pages ship in the wheel so the route you read is the one for the
version you installed.

## A LangGraph agent in one command

```bash
bf init claims-triage --langgraph
cd claims-triage
bf dev                      # serve it locally; the model call still needs a gateway
```

`bf init` writes `agent.py`, `badgerflow.yaml`, a `Dockerfile` pinned to this SDK
version, `tests/test_agent.py`, a CI workflow and a `.dockerignore`. `bf dev`
serves the agent with no platform; a node that calls a model reaches the model
gateway, so set `BADGERFLOW_GATEWAY_URL` and `BADGERFLOW_MODEL_KEY` (below) or
run the generated tests, which answer the model with a `FakeLLM`. The agent is
an ordinary `StateGraph`; the only BadgerFlow addition is a `@node(uses=...)`
decorator declaring what each node may touch:

```python
@node(uses=Uses(knowledge=["claims-manual"]), determinism="recorded_effect")
async def retrieve(state: State) -> State:
    chunks = await ctx.knowledge.retrieve(state["input"]["description"], top_k=4)
    return {"excerpts": [c.text for c in chunks]}

app = Agent.from_langgraph(build_graph(), name="claims-triage", version="0.1.0",
                           input=Claim, output=Triage)
```

Those declarations are the contract. The platform compiles them into a graph it
can render — every node, every conditional edge as a router with its branch
labels, and the END your graph declares — checks them against what exists in
your namespace at release time, and denies a node at runtime that reaches for
something it never declared. `bf compile` shows that graph before you register.

`settings` is the half a reviewer reads rather than the platform enforces: what
the node is configured with, shown read-only on its card and inspector.

```python
@node(
    uses=Uses(model="gpt-4o"),
    determinism="recorded_inference",
    settings={"model": "gpt-4o", "temperature": 0, "system_prompt": TRIAGE_SYSTEM,
              "output": "_Triage"},
)
async def triage(state: State) -> State: ...
```

Any JSON object (or a pydantic model) up to 64 KB. It is pinned by the release
hash like the rest of the node's config, so what the approver read is what
runs — and it is declared, because the compiler cannot see a prompt that is
built inside the function.

## Work that outlives a request

An invocation is an HTTP request, and some agents run longer than one should be
held open. Call `ctx.accept()` and the platform stops waiting on the reply:

```python
@app.run
async def triage(ctx: Context, claim: Claim) -> Triage:
    ctx.accept()                 # answered 202; the platform now waits on events
    await slow_work(claim)       # minutes, not seconds
    return Triage(...)           # becomes the run's `complete` event
```

Nothing else changes. `ctx.step`, the governed clients and cancellation behave
identically, and the return value still becomes the run's result — it reaches
the platform as the terminal event rather than as the response body.

Two things to know. The platform's clock keeps running, so silence past the
`timeout_seconds` you registered fails the run; raise it at registration if the
work takes longer. And once you accept, you have accepted: the reply is 202 even
if the handler happens to finish first, so the same code cannot take one
governance path on a fast machine and another on a slow one.

## Human review in a LangGraph agent

Use LangGraph's own `interrupt()` — nothing BadgerFlow-specific:

```python
def gate(state):
    decision = interrupt({"question": f"Approve {state['amount']}?"})
    return {"decision": decision}
```

The run pauses, appears in the platform's Paused Inbox, and resumes when a
reviewer answers; `interrupt()` returns their answer. `interrupt_before=[...]`
works the same way, with the prompt naming the node it stopped before.

In a chat agent, a question for the *user* rather than a reviewer says so, and
their next message is what `interrupt()` returns:

```python
def clarify(state):
    account = interrupt({"kind": "user_reply", "question": "Current or savings?"})
    return {"account": account}
```

LangGraph needs a checkpointer to resume, and your pods are stateless: the pod
that resumes is usually not the pod that paused, often days later. So the SDK
binds `BadgerFlowCheckpointSaver`, which exports the graph's checkpoint into
the pause and restores it on the resume. You never configure it, and your
compiled graph is never modified.

Keep large values out of the graph state. The checkpoint travels with the pause
and is capped; a state that is too big fails the run with a clear reason rather
than producing a pause the platform cannot file. Hold a reference instead.

## Answering a chat

A chat-triggered agent receives each turn as text. The platform puts that text
in `input` and, when your input model has one place for it, under that field's
name in `structured` too: a field named `input`; else the one required string
field; else one named `message`, `text`, `query`, `question`, `prompt` or
`content`; else the one string field. So `Input(problem: str, attempt: str =
"")` receives the turn as `problem`, and `Input(message: str = "", problem: str
= "", attempt: str = "")` as `message`. Several optional string fields with
none of those names is left to your model, which then sees them all empty.

Going back, the bubble shows one field of your output model: the one you mark
with `Field(json_schema_extra={"x-badgerflow-reply": True})`, else one named
`reply`, `answer`, `response`, `message`, `text` or `content`, else the single
string field. An output that names none of those shows as its JSON, which is
the cue to mark the field. A streamed agent's deltas are always the reply.

## Streaming a run

Ask for `text/event-stream` and the invocation answers with the run's event
frames as they happen, the last one terminal:

```
data: {"seq":1,"type":"step_started","payload":{"node_id":"retrieve",...}}
data: {"seq":2,"type":"step_completed",...}
data: {"seq":3,"type":"complete","payload":{"output":{...}}}
```

Nothing in the handler changes: the same `ctx.step` blocks and the same return
value. What changes is where the evidence goes. On a streamed invocation the
frames ride the response instead of being posted to the platform's event
ingest, because both would record the run twice.

## Test it offline

`badgerflow.procode.testing.AgentTestClient` invokes the agent's own server in
process — a run token minted by a key the client generates, the contract
request, every event frame the run emitted — with fakes in place of the
platform's clients:

<!-- snippet: exec -->
```python
from badgerflow.procode.testing import AgentTestClient, FakeLLM

async def test_answers():
    async with AgentTestClient(app, llm=FakeLLM(replies=["Yes."])) as client:
        result = await client.invoke({"text": "Is it raining?"})
        assert result.status == "completed" and result.output["answer"] == "Yes."
        assert "step_completed" in result.event_types

async def test_review():
    async with AgentTestClient(app, llm=FakeLLM(replies=["Yes."])) as client:
        paused = await client.invoke({"text": "..."})
        assert paused.status == "paused" and paused.pause["kind"] == "review"
        done = await client.resume(paused, {"decision": "approved"})
```

`bf init` generates these. Every governed client has a fake for tests: `FakeLLM`
for `ctx.llm` — `chat`/`chat_stream`, the raw `ctx.llm.openai()` client (plain,
streamed, `with_raw_response`) and `ChatBadgerFlow` all answer from its scripted
replies over its own transport, a reply being text or
`{"tool_calls": [{"name": ..., "arguments": {...}}]}` — and `FakeKnowledge`,
`FakeOntology`, `FakeGuardrails`, `FakeTools` and `FakeConnectors` from
`badgerflow.procode.testing` for the other five, each scripted at construction
(`FakeKnowledge(chunks={"claims-manual": ["Deductibles apply."]})`,
`FakeGuardrails(rails={"pii": "redact"}, redactions={...})`,
`FakeTools(tools={"lookup": lambda args: {...}})`), answering in the real result
types, recording every call in `.calls`, and refusing what was not scripted with
a `FakeCallError` that names the fake — except that an empty `FakeKnowledge`
finds nothing and `FakeTools` refuses an unknown tool as the gateway does.
`FakeTools` emits the real `tool.*` event frames, so `result.event_types` reads
as in a deployment. The fakes replace the platform's answers, not its
enforcement: a fake serves whatever a handler names whether or not `requires`
declared it. What the client does not do is the platform's half — no release
rules, no per-node enforcement, no inbox — so `bf validate --against <ingress>`
is the other half of the preflight: it previews the release scorecard.

## Register and release

Deploy the container, then point the platform at it:

```bash
bf sync --wait-for-endpoint 120 --image "$IMAGE@$DIGEST"
```

The platform fetches `/.well-known/badgerflow-agent.json` from your endpoint and
records what **it** saw, so a registration is evidence rather than a claim.
`bf sync` exits non-zero when what the platform fetched is not what your
checkout compiles to, which is what makes it safe in CI.

Registering does not change what runs. A governed release does:

```bash
bf release submit --wait     # then a second human approves it in the UI
bf release status --strict   # in CI: 0 only when every rule was evaluated and passed
```

Without `--strict` the exit code answers "did a gate fail?": a verdict not yet
written, or a rule an authority could not answer, exits 0 with a warning. A
pipeline that reads only the exit code wants `--strict`, where those exit 2.

Each environment runs its own BadgerFlow with its own approvers, so run this
once per environment. Pass the image **digest**, never a tag: it is what a
rollback names and what makes "the same build" promoted from UAT to production
provable.

A project registered with more than one platform declares each under
`environments:` in `badgerflow.yaml`: a profile may set `base_url`,
`workflow_url`, `platform_url`, `namespace` and `api_key_env` (the name of the
variable holding that platform's credential; a key value in the file is
refused), and carries its own `workflow_id` and `image`. Select one with
`bf --profile prod <command>` or `BADGERFLOW_PROFILE=prod`; an explicit
`BADGERFLOW_*` variable still overrides the profile, `bf --profile prod register`
writes the id back under `environments.prod`, and `bf profiles` prints every
profile resolved, saying whether its credential variable is set but never its
value. Without `--profile` the top-level keys and the variables apply as before.

`bf release status --json` and `bf release submit [--wait] --json` print one
JSON document on stdout — `release`, `scorecard` (`null` when not waited for),
`verdict` (`gate`, `status`, the `rules` with name, status, message and
observed value, the passed/failed/skipped counts, `pending`, `strict_ok`,
`warnings`, `errors`) and `exit_code` — and nothing else there, so a pipeline
can `jq '.verdict.strict_ok'`; the human lines go to stderr. The exit code is
the same the rendering gives, `--strict` included, because both read one
verdict.

```yaml
environments:
  uat:
    base_url: https://uat.badgerflow.example
    api_key_env: BADGERFLOW_API_KEY_UAT
  prod:
    base_url: https://badgerflow.example
    namespace: claims
    api_key_env: BADGERFLOW_API_KEY_PROD
```

The build itself is pinned by `requirements.lock`, which `bf init` and `bf lock`
write: the SDK and every distribution its extras pull in, at the versions
installed in the environment that validated the agent, with markers judged for
the Linux CPython 3.11 image. The Dockerfile installs it and the generated CI
runs `bf lock --check`. A lock is complete or it is not written: when this
interpreter lacks a distribution the extras need, `bf lock` exits 1 naming the
`pip install 'badgerflow[server,otel]==<version>'` that completes it, `bf init`
warns about the same lines, and `--check` fails such a lock wherever it runs —
a CI job that installed the extras must not pass what the laptop could not pin.
Regenerate it with `bf lock` after upgrading badgerflow or any dependency, and
commit the result.

Your application's own dependencies go in `requirements.in`, one PEP 508 line
each (`requests>=2.32`, a marker allowed; no `-r`, `-e`, URL or path lines,
since a lock must name every version it installs). `bf init` writes the file
empty. To add a dependency: add the line, `pip install -r requirements.in`, run
`bf lock`, and commit both files; the lock then pins the SDK's closure and your
application's together, and records the `requirements.in` lines it was built
from so `bf lock --check` fails on an edit even when the pinned body did not
move. To upgrade one, change the specifier or `pip install -U` it, then
`bf lock` again. `bf lock` refuses a line whose installed version falls outside
its own specifier — the tests ran against a version the line excludes — and a
line not installed here, naming the install that completes it. It also refuses
an installed graph that disagrees with itself (a pinned distribution outside
what another pinned one requires, the set `pip check` would report): an image
could not install such a lock, so it is not written. A specifier pip cannot
read (`httpx>=not-a-version`, `>=1.o`) is refused on the `requirements.in` line
that carries it, by `bf lock` and `--check` alike — never read loosely and
pinned over — and inside the installed graph counts as not held. The image
installs `requirements.lock` only; `requirements.in` is the declaration, never
what runs.

## Models from any Python code

A LangGraph app does not have to be a registered agent to use the models your
BadgerFlow workspace pays for. Create a model key in **Workspace settings →
Model keys**, then:

```bash
export BADGERFLOW_GATEWAY_URL=https://<platform>/api/gateway/ws/<workspace>
export BADGERFLOW_MODEL_KEY=sk-...
bf models                      # what this key may call, and the price per million tokens
```

```python
from badgerflow.langgraph import ChatBadgerFlow

llm = ChatBadgerFlow(model="claims-chat")   # outside a run: the model key
```

`badgerflow.llm.openai_client()` gives the same access as an `AsyncOpenAI`.
Every call is billed to the key's workspace and held to the key's model list and
budget. Inside a registered agent's run the run token is used instead, even when
a model key is set, so a release's attribution never depends on what a pod's
environment happens to contain. The Helm chart refuses to put a model key in a
governed agent at all.

## Tool plugins

A plugin gives BadgerFlow agents and workflows a new tool without changing the
platform. It is a standard MCP server plus a signed manifest, and both are built
from typed Python:

```bash
pip install 'badgerflow[plugin]' pytest
bf plugin init acme-crm && cd acme-crm
bf plugin test && bf plugin validate
```

<!-- snippet: exec -->
```python
from pydantic import BaseModel, SecretStr
from badgerflow.plugin import Plugin, Permissions, ToolContext, credential

plugin = Plugin(
    name="acme-crm",
    version="0.1.0",
    description="Read customers in Acme CRM.",
    permissions=Permissions(egress=["api.acme.com"], models=["any-allowed"], storage_bytes=1_000_000),
)

class AcmeCredentials(BaseModel):
    api_key: SecretStr = credential(label="API key", kind="secret")

class Customer(BaseModel):
    id: str
    name: str
    tier: str

@plugin.tool(credentials=AcmeCredentials, effect="read")
async def find_customer(ctx: ToolContext[AcmeCredentials], email: str) -> Customer:
    """Look up a customer by email."""
    resp = await ctx.http.get("https://api.acme.com/customers", params={"email": email},
                              headers={"Authorization": f"Bearer {ctx.credentials.api_key.get_secret_value()}"})
    return Customer.model_validate(resp.json())

app = plugin.asgi()     # MCP streamable HTTP + /.well-known/badgerflow-plugin.json + /healthz
```

The tool's schemas come from its signature and return type and its description
from the docstring; `badgerflow-plugin.yaml` is generated from them by
`bf plugin manifest` and never edited. A plugin the platform would refuse fails
when the module imports.

`bf plugin validate --against <ingress>` adds the platform's preflight to the
local checks: it sends the manifest and the bundle's file names with their sizes
— never the files — and the platform answers every refusal a `submit --source`
would get that it can judge without building, from the platform that would
issue it:
no base image for this SDK, a pin with no dependency image, a pin that would
replace a base distribution, a requirement nothing declares or a version
conflict, the bundle limits, plus two warnings the submit itself does not make —
a `permissions.models` alias outside this workspace's model catalogue (what the
`procode_models_allowed` release rule will say) and `instance_support` on a
platform with instances off. A blocking finding fails validate; the rest print
as warnings. Two states are *unchecked* rather than passed — the platform's
registry was unreachable (`plugin_registry_unreachable`), or the model catalogue
could not be read (`plugin_models_unchecked`) — and print as warnings too, so
that a flaky registry does not fail a laptop run; `validate --against URL
--strict` fails on them, which is the mode for CI, where an unchecked bundle is
not a checked one. It needs the submit's credential (`plugins.install`), and it
cannot preview the release: the `plugin_*` rules and the approval come after the
submit.

Each workspace's credential reaches the tool only inside the platform's call.
`ctx.http` refuses a host outside `egress` before sending, `ctx.llm` refuses a
model outside `models`, and `ctx.knowledge.retrieve(...)` reads only the
`collections` the release granted (the calling workspace's, on the call's own
token). A `ToolError` is the message the model reads; any other exception
reaches the caller as its type alone, never its text. Test tools in-process
with `badgerflow.plugin.testing.PluginTestClient` (`FakeLLM`, `FakeKnowledge`,
in-memory storage, and a `binding=` for instance-bound calls).

`bf plugin init` scaffolds an *instance-aware* plugin: `instance_support`,
credentials classified by `instance_role`, and a `check_connection` tool the
platform runs under `connection_check` before binding an instance and on every
key rotation. `bf plugin validate` reports whether a plugin is instance-ready.

Before shipping, serve the plugin and call a tool the way the platform would:

```bash
uvicorn plugin:app --port 8080 &
bf plugin call find_customer --url http://localhost:8080/mcp \
    --args '{"email": "ada@example.com"}' --credentials @creds.json
```

`call` sends the platform's call envelope, credentials included. `ctx.llm` and
`ctx.storage` have no local platform there; in the cluster `ctx.http` is fenced to
`egress` by the platform's proxy.

A served plugin has the agent server's observability: `GET /metrics` exposes
`badgerflow_plugin_calls_total{tool,status}` (status `ok`, `error`, `refused`,
`deadline`), `badgerflow_plugin_call_seconds{tool}` for every call that reached
the tool, and `badgerflow_plugin_inflight`; `PluginTestClient.metrics` is the
same registry for assertions. With the `otel` extra each `tools/call` is a
SERVER span `plugin.call <tool>` carrying the plugin's name, version and tool,
the run id and the instance id — never a token, credential or argument —
parented to the `traceparent` the caller sent beside the envelope, and every
call completion logs one INFO line with the tool, status, milliseconds and run
id. The served app configures both at startup from the agent server's
variables: spans go where `BADGERFLOW_OTLP_ENDPOINT` points (the platform's
`plugin-base` image carries the `otel` extra, and plugin-controller sets the
variable from its `PLUGIN_OTLP_ENDPOINT`), `BADGERFLOW_SERVICE_NAME` renames
the service, `BADGERFLOW_OTEL_DISABLED` turns tracing off and
`BADGERFLOW_LOG_JSON` switches the log line to JSON. A return value the tool's
declaration refuses (wrong type, not serialisable) reaches the caller as
`isError` and is counted as `error`, not `ok`.

The platform builds every container plugin: `bf plugin submit --source` sends
the generated manifest, every lowercase Python module and package directory in
the project, and its text resources (JSON, YAML, text, Markdown, CSV, SQL,
Jinja, HTML, XML, TOML) at any depth, by relative path — `tests/`,
`conftest.py`, `test_*.py`, binaries and names outside `[a-z_][a-z0-9_]*` stay
behind, with a cap of 128 files and 4 MiB — and agent-platform-api lays them
over its base image for the manifest's SDK version exactly as laid out (so
`Path(__file__).parent / "schemas/x.json"` works in the image), signs the result
with its own key and imports it. `bf plugin validate` (and `submit`, before
sending) imports exactly that bundle on its own in a subprocess that cannot see
the project, requires the `app = plugin.asgi()` the image serves (`uvicorn
plugin:app`; without it the pod crash-loops), and classifies every import as the standard library's, the
bundle's, the base image's (`badgerflow[plugin]` and its closure) or a pinned
requirement the manifest declares; an undeclared third-party import, a relative
import that escapes the bundle, a pin not installed locally, or a pin at another
version than the one installed (what was tested is not what the image gets)
fails there, not after the build; a pin nothing imports is a warning. A
third-party library is declared as
`Plugin(..., requirements=["requests==2.32.3"])` — the PEP 503 normalised name
pinned to one exact version, with the library's own requirements declared
beside it — and the platform lays the dependency layer its operator built for
exactly that pin over the base image; it resolves nothing and refuses a pin it
has no layer for (`plugin_requirement_unavailable`, naming the operator's
command), a pin whose own requirements are neither declared nor in the base
(`plugin_requirement_incomplete`), a pin naming a distribution the base already
carries (`plugin_requirement_replaces_base`), a pin whose requirement is provided
— by the base or another pin — at a version outside its specifier
(`plugin_requirement_conflict`), and any pin on a platform with no dependency
repository (`plugin_requirements_unsupported`). There is no Dockerfile,
registry or signing key on your side, and no other way in for a container plugin
(a vendor-hosted MCP endpoint is `submit --url` with a manifest you sign).
`bf plugin init` also writes a CI workflow that submits on a version tag. `ctx.storage` is a JSON key-value store per calling
workspace under `storage_bytes`, in memory under `PluginTestClient` and on the
platform (`BADGERFLOW_PLATFORM_URL`) when served.

## Commands

| | |
|---|---|
| `bf --profile NAME <command>` / `bf profiles` | run against one `environments:` profile of `badgerflow.yaml`; list them resolved |
| `bf init [--langgraph]` | scaffold a project, its tests, CI and `requirements.lock` |
| `bf lock [--check]` | regenerate the lock from the installed SDK and `requirements.in`; `--check` exits 1 when stale or incomplete |
| `bf dev` | serve locally, run-token verification off |
| `bf validate` | build the manifest offline, print its hash |
| `bf compile [--check]` | the graph the platform will see, and its hash |
| `bf register` / `bf sync` | register a build; `sync` is the CI form |
| `bf status` | registration, release, and hash agreement |
| `bf release submit \| status [--strict] [--json]` | the governed release and its scorecard; `--strict` exits 0 only when every rule was evaluated and passed; `--json` prints one document for pipelines |
| `bf models` | the models your model key may call, with prices |
| `bf plugin init \| manifest \| test \| validate` | author and check a tool plugin: conformance, instance readiness, and that the submitted bundle imports on its own |
| `bf plugin call <tool> --url` | one call with the platform's envelope and credentials |
| `bf plugin submit --source \| --url`, `sign`, `dev` | submit it (the platform builds it); sign a remote or dev manifest |
| `bf plugin-catalog` | curated package versions; availability is separate from instance access |
| `bf plugin-instances [--plugin NAME]` | instances visible to the current author |
| `bf plugin-bindings` | explicit approved instance/revision/action pins for local binding selection |
| `bf mcp [--http]` | the authoring tools over MCP, as you — design, check and *propose* workflows from Claude Code, Codex or Cursor; nothing is applied until a person accepts it |
| `bf skills install \| check` | teach a coding tool this SDK: `.agents/skills`, `.claude/skills`, an `AGENTS.md` block; `check` fails after an upgrade until you re-install |
| `bf docs [NAME] [--raw \| --path]` | the developer guide, support matrix, chart guide, support and security pages bundled with this version |
| `bf support [bundle --out DIR]` | where to report, and a redacted diagnostic bundle (settings, lock, validate output; no credential values) |

## Coding tools

`bf init` and `bf plugin init` also install the SDK's agent skills — for Claude Code, Codex,
Cursor and any tool that reads `.agents/skills` or `AGENTS.md` — so the tool knows the commands,
the declarations and the rules without reading this SDK's source. Commit them. After upgrading
`badgerflow`, run `bf skills install`; `bf skills check` in CI fails while they describe another
version. `--no-skills` opts out. Claude Code users with access to the BadgerFlow repository can
also add it as a plugin marketplace: `/plugin marketplace add facileai/agiel`, then
`/plugin install badgerflow@badgerflow`.

## Versioning

The SDK follows semantic versioning. Its version is not decoration: it lands in
every manifest's `sdk` block and the platform stores it with the release, so it
is part of what an auditor sees. The wire contract is versioned **separately**
as `contract_version` — an SDK major bump does not imply a contract bump, and a
contract bump is announced on its own.

## Requires

Python 3.11+. The `server` extra pulls FastAPI and uvicorn, `langgraph` pulls
LangGraph and langchain-core, `otel` pulls the OpenTelemetry SDK, `plugin` pulls the
official MCP SDK. Without an
extra the corresponding surface is inert rather than broken.

## The REST client, and the names it kept

`badgerflow.client.AgiellClient` is the platform's REST client. Four resources
answer typed records: `client.workflows.*` return `Workflow` and `WorkflowRun`
(`signal` returns a `SignalAck` — the delivery, not the run; read the run
afterwards), `client.releases.*` return `Release` and `Scorecard` (whose
`rules` are `RuleResult`s), `client.plugins.*` return `PluginPackage` (its
`manifest_kind` is the manifest's `kind`, `install_kind` is `image`, `remote`
or `dev`, and `package_kind` reads `source` for a platform-built package and
`install_kind` otherwise), `client.plugin_instances.*` return `PluginInstance`,
and `diagnose` a `DiagnoseReport` with `ok` and `problems`. The other resources
— `agents`, `auth`, `dependencies`, `guardrails`, `guardrail_profiles`,
`models`, `namespaces`, `rag`, `webhooks` — still answer the platform's plain
dicts. A record is still the dict the
platform sent — `row["id"]`, `row.get(...)`, `json.dumps(row)` and `**row` keep
working, and it compares equal to the plain row — with read-only properties for
the fields the SDK promises (`run.output`, `run.active`, `release.image_digest`,
`scorecard.gate`); a field an older platform lacks reads as `None` rather than
raising. All of them, and `StreamEvent`, import from `badgerflow.client`. The
client covers agents and
sessions, models, knowledge, guardrails, releases, the workflow runs of a
registered pro-code agent (`client.workflows.execute`, `run`, `wait`,
`cancel_run`, `signal` — which a pro-code run answers with 409, since signals
are a graph-engine feature — and `stream`, which yields `StreamEvent`s — the
service's `id`, the cursor `after=` resumes from, the `type` and the payload
`data`, readable like the dict) and the whole plugin lifecycle: `client.plugins`
submits a source bundle or a signed remote manifest, installs a package
(platform scope or one workspace), enables and disables it per workspace, sets
this workspace's credential (values go one way; `credentials()` answers
metadata only) and retires a runtime on the evidence hash it showed, while
`client.plugin_instances` creates, revises, submits, rotates, grants, checks,
patches and deletes instances, drives operation reconcile and placement state,
and `diagnose(instance_id)` gathers the instance, its check choices, placements
and dependencies into one mapping, with any sub-call the caller may not make,
or that the network does not deliver (`unreachable: ConnectError`), recorded
under `problems` rather than raised. It predates the `bf` CLI and
kept its names so that nothing written against it broke:

| Legacy | Current | Note |
|---|---|---|
| `from agiel import AgiellClient` | `from badgerflow.client import AgiellClient` | the `agiel` shim warns once and stays until the platform's export generator moves |
| `AgiellClient` (double `l`) | the same name | it is the public import; there is no `AgielClient` |
| `AGIEL_BASE_URL`, `AGIEL_API_KEY` | the `base_url=` / `api_key=` arguments | the REST client reads `AGIEL_*`; the `bf` CLI and a served agent read `BADGERFLOW_*` — two tools, two prefixes, by design |
| per-service NodePort defaults (`:8082`, `:8083` …) | `agent_api_url=f"{base}/api/agents"` and the other `*_url` arguments | the defaults are for a cluster reached without an ingress; through one, name the prefix |
| `AgiellError` and its subclasses | unchanged | the REST client's errors are HTTP; the governed clients on `Context` raise `BadgerFlowError`, and the two never mix |

New code: the `bf` CLI and `badgerflow.procode` for an agent, `AgiellClient`
for what a platform operation needs from Python, and never `agiel`.

## Licence

Apache-2.0, and it covers **this SDK only**. The BadgerFlow platform the SDK
talks to is not open source and is licensed separately. See `LICENSE` and
`NOTICE`.

### Instance discovery and OAuth readiness

The REST client exposes `client.plugin_instances.catalog(namespace=...)`,
`list(plugin=..., namespace=...)`, `bindings(namespace=...)` and
`oauth_readiness(instance_id, binding, namespace=...)`. Pass a selected binding from
`bindings`; there is no implicit default or newest-version lookup. Refusals and service
outages raise the SDK's normal exceptions, rather than returning an empty catalogue.

The authoring MCP tools `list_plugin_catalog`, `list_plugin_instances`,
`list_plugin_bindings` and `get_plugin_oauth_readiness` use the author's credentials.
They discover and observe; they cannot connect accounts, publish, approve or release.
OAuth status is for that caller and the exact binding's package scopes. Accounts remain
shared per workspace/provider/user. Expired access tokens report `refresh_required`;
the read neither decrypts nor refreshes tokens and does not guarantee runtime admission.
Connect/reconnect from the instance's setup UI to consent to that package's scopes.
