Metadata-Version: 2.4
Name: agentpm
Version: 0.1.18
Summary: AgentPM™ Python SDK
Project-URL: Homepage, https://github.com/agentpm-dev/sdk-python
Project-URL: Repository, https://github.com/agentpm-dev/sdk-python
Project-URL: Issues, https://github.com/agentpm-dev/sdk-python/issues
Project-URL: Changelog, https://github.com/agentpm-dev/sdk-python/releases
Author-email: AgentPM™ <dev@agentpm.dev>
License: MIT License
        
        Copyright (c) 2025 Zack Hine
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the “Software”), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in
        all copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        THE SOFTWARE.
License-File: LICENSE
Keywords: agentpm,agents,ai,tools
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: semver>=3.0.0
Provides-Extra: dev
Requires-Dist: black>=24.8.0; extra == 'dev'
Requires-Dist: build>=1.2.1; extra == 'dev'
Requires-Dist: mypy>=1.11.0; extra == 'dev'
Requires-Dist: pre-commit>=3.8.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
Requires-Dist: pytest>=8.3.0; extra == 'dev'
Requires-Dist: ruff>=0.6.8; extra == 'dev'
Requires-Dist: twine>=5.1.1; extra == 'dev'
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.2.0; extra == 'langchain'
Description-Content-Type: text/markdown

# AgentPM™ Python SDK

A lean, typed Python SDK for **AgentPM** tools and installed agent, Knowledge, Memory, Profile, and Loop packages. It discovers tools installed by `agentpm install`, delegates their execution to the installed AgentPM CLI, and can also inspect installed agent manifests plus their resolved dependency refs.

- 🔎 **Discovers** tools in `.agentpm/tools` (project) and `~/.agentpm/tools` (user), with `AGENTPM_TOOL_DIR` override.
- 📦 **Loads installed agents** from `.agentpm/agents` and exposes their resolved tool and skill refs from `agent.lock`.
- 📚 **Loads installed skills** from `.agentpm/skills` and exposes their manual content plus resolved tool refs.
- 🧠 **Loads installed Knowledge packages** from `.agentpm/knowledge` and exposes mode-specific metadata and canonical paths.
- ♾️ **Loads installed Memory packages** from `.agentpm/memory` and exposes authored blueprint metadata, build metadata, contract indexes, and resolved contract paths.
- 🎭 **Loads installed Profile packages** from `.agentpm/profiles` and exposes authored role, objective, and communication metadata.
- 🔁 **Loads installed Loop packages** from `.agentpm/loops` and exposes authored phase, transition, and error-policy metadata.
- 🚀 **Runs Tools** through `agentpm run --machine`, which owns Node/Python execution.
- 🧩 **Metadata-aware**: `with_meta=True` returns `func + meta` (name, version, description, inputs, outputs).
- 🧪 **Framework adapters (optional)**: e.g., a LangChain adapter you can use if installed.

> Requires Python **3.10+**.

---

## CLI and lock compatibility

SDK **0.1.17+** requires **AgentPM CLI 0.1.43+** for every Tool call,
including Node and older vendored Python Tools. Install the CLI separately and
check `agentpm --version`. Set `AGENTPM` to an absolute CLI executable path when
it is not on PATH; it is a single executable, not a shell command.

The SDK reads `agent.lock` **v2, v3 and v4** without rewriting it. Unsupported
future or malformed locks fail with update/install guidance. An installed Agent
can be loaded from a project containing just `agent.lock` and `.agentpm`; no app
`agent.json` is required. Exact locked references remain exact when other
versions coexist. A local author Tool root is not an installed Agent.

SDK 0.1.17 accepts the additive v4 `standard` and `standard_origin` fields.
For locks containing these fields, use **CLI 0.1.47+** on developer machines,
CI and container images. Older CLIs can report an `unknown field` error;
upgrade the CLI instead of removing provenance. `legacy_inferred` records
historical interpretation, not an authored declaration or conformance result.

Calls follow **app → SDK → `agentpm run --machine` → Tool**. The SDK unwraps the
CLI result and returns the Tool's original JSON data. A Tool's `ok: false` stays
ordinary returned data; runner failures raise an exception. Interpreter, schema,
target, installed-state, timeout and managed-environment checks belong to the
CLI. They happen on invocation, so metadata loading itself needs no CLI or
available Tool interpreter. The SDK retains bounded input/output transport and
passes the requested timeout to the CLI. Ctrl-C is handled by the CLI's scoped
child cleanup; SDK interruption also terminates its CLI child.

Environment precedence is ambient values, defaults for missing variables,
entrypoint env, then caller env. Required variables may come from any of these
layers. Managed Python strips `PYTHONPATH` and `PYTHONHOME` after layering. Use
`AGENTPM_PYTHON` to select a compatible base interpreter **before install**, not
to bypass the managed environment. Caller options and credential values are not
printed in SDK debug output; credential values are redacted from CLI diagnostics.
Tool results are returned unchanged, so Tools must not return secrets themselves.

Run `agentpm install` explicitly to provision dependencies. If runtime state is
missing/stale, reinstall with the selected `AGENTPM_PYTHON`; use
`agentpm install --refresh` to repair damaged packages. Calls never auto-install,
resolve from an index, rewrite the lock or fall back to app/global Python.
Older SDK versions do not become v4-compatible merely because CLI install passed.

## Installation

### From PyPI (recommended)

Using **uv**:

```bash
uv pip install agentpm
```

Or with standard pip:

```bash
python -m pip install agentpm
```

If you'll use the optional LangChain adapter:

```bash
uv pip install 'agentpm[langchain]'
# or
python -m pip install 'agentpm[langchain]'
```

---

## Quick Start (with `uv`)

```bash
# create and activate a venv
uv venv
source .venv/bin/activate

# install SDK in editable dev mode (ruff/black/mypy/pytest, etc.)
uv pip install -e ".[dev]"

# sanity checks
uv run ruff check .
uv run black --check .
uv run mypy src
uv run pytest -q
```

> If you're not using `uv`, standard `python -m venv` + `pip install -e ".[dev]"` works too.

---

## Using the SDK

```python
from agentpm import load

# Spec format: "@scope/name@version"
summarize = load("@zack/summarize@0.1.0")

result = summarize({"text": "Long document content..."})
print(result["summary"])
```

### With metadata (build richer tool descriptions)

```python
from agentpm import load

tool = load("@zack/summarize@0.1.0", with_meta=True)
summarize, meta = tool["func"], tool["meta"]

rich_description = (
    f"{meta.get('description','')} "
    f"Inputs: {meta.get('inputs')}. "
    f"Outputs: {meta.get('outputs')}."
)

print(rich_description)
print(summarize({"text": "hello"})["summary"])
```

### Load an installed agent package

```python
from agentpm import (
    load,
    load_agent,
    load_knowledge,
    load_loop,
    load_memory,
    load_profile,
    load_skill,
)

agent = load_agent("@zack/support-agent@0.1.0")
docs = load_knowledge("@zack/python-docs@0.1.0")
loop = load_loop("@zack/incident-response-loop@0.3.0")
memory = load_memory("@zack/profile-memory@0.1.0")
profile = load_profile("@zack/support-style@0.1.0")
first_skill = agent["resolvedSkills"][0]
skill = load_skill(f'{first_skill["name"]}@{first_skill["version"]}')
first_tool = skill["resolvedTools"][0]
tool = load(f'{first_tool["name"]}@{first_tool["version"]}')

print(agent["resolvedKnowledge"])
print(agent["resolvedLoop"])
print(agent["resolvedMemory"])
print(agent["resolvedProfiles"])
print(loop["loop"]["transitions"])
print(docs["knowledge"]["mode"])
print(memory["contracts"])
print(profile["profile"]["communication"])
```

`load_agent()` returns:

- the installed agent manifest
- the installed agent root path
- `resolvedKnowledge` from `agent.lock`
- `resolvedLoop` from `agent.lock`
- `resolvedMemory` from `agent.lock`
- `resolvedProfiles` from `agent.lock`
- reserved refs (`knowledge`, `memory`, `profiles`) as metadata
- `resolvedTools` from `agent.lock`
- `resolvedSkills` from `agent.lock`

It does **not** execute the agent package or orchestrate the tools for you.

Compatibility note:

- `resolvedKnowledge` is populated from the modern first-class `root.knowledge` entries in `agent.lock`.
- `reserved.knowledge` is legacy pass-through metadata from older lockfile shapes. For current installs, treat `resolvedKnowledge` as the authoritative Knowledge dependency list and expect `reserved.knowledge` to usually be empty.
- If your workspace still has an older pre-Knowledge lockfile shape where Knowledge refs only exist under `reserved.knowledge`, rerun `agentpm install` to rewrite the lockfile before expecting `resolvedKnowledge` to be populated.
- `resolvedLoop` is populated from the modern first-class `root.loop` entry in `agent.lock`.
- `resolvedProfiles` is populated from the modern first-class `root.profiles` entries in `agent.lock`.
- `reserved.profiles` is legacy pass-through metadata from older lockfile shapes. For current installs, treat `resolvedProfiles` as the authoritative Profile dependency list and expect `reserved.profiles` to usually be empty.
- `manifest["loop"]` and `manifest["bindings"]` preserve the authored declarative metadata from the installed `agent.json`.

This is the Python mirror of the Node SDK’s `loadAgent()` flow:

1. load the installed agent package
2. read its resolved skill and tool refs
3. optionally load a resolved skill package
4. choose which tool packages to `load()`

### Run Harness over the machine protocol

```python
from agentpm import BeforeToolCallDecision, BeforeToolCallInput, HarnessClient

harness = HarnessClient(agent="@zack/support-agent@0.1.0")


def model_provider(request):
    return {
        "id": "turn-1",
        "assistant_content": "Handled by the host model.",
        "actions": [],
        "usage": {},
        "finish_reason": "stop",
        "provider_metadata": {"model": request["selection"]["model"]},
    }


def before_tool_call(input: BeforeToolCallInput) -> BeforeToolCallDecision:
    return {"decision": "continue", "patch": {"arguments": input["arguments"]}}


harness.register_model_provider("company-model", model_provider)
harness.on_before_tool_call(before_tool_call)
harness.on_approval(lambda checkpoint: "approve")

result = harness.run("Use the configured agent.")
harness.shutdown()

print(result)
```

`agent` is optional. When set, it is passed to `agentpm harness` as either an installed Agent package ref such as `@zack/support-agent@0.1.0` or a local Agent name recorded in the workspace lock, such as `consumer-1`; when omitted, Harness uses its normal workspace discovery/default Agent selection. Register host services before starting a run. The SDK launches `agentpm harness --machine`, correlates request/response frames, streams Harness events, and routes host-service callbacks for model providers, embedding providers, Knowledge runtimes, hooks, and approvals.

The convenience Hook helpers use contract-specific type hints. `on_before_model_request` may return `context_sections` and `provider_options`, `on_before_tool_selection` may return `candidate_ids`, `on_before_tool_call` may return replacement `arguments`, `on_before_knowledge_request` may shape the same package request options, and `on_after_knowledge_retrieval` may filter/reorder existing results or transform model-visible text while retaining result identity. Direct Memory hook helpers can shape authorized read requests or patch/reject authorized write content before runtime dispatch. A returned object must include `decision: "continue"` or `decision: "reject"`; returning `None` is treated as an explicit continue with no patch. There is no embedding Hook ID; use `register_embedding_provider` to host query embedding.

Inspect APDS support separately from runtime readiness:

```python
info = harness.initialize()
response = harness.preflight()
report = response["report"]  # Current CLI response envelope is preserved.
standards = harness.supported_standards()
# [{"id": "agentpm", "version": "1.0.0"}] when advertised by the running CLI.
print(info["preflight"], report, standards)
harness.shutdown()
```

`initialize()["preflight"]` contains the definition/readiness report; `preflight()`
retains the CLI's `{report, mcp_exports}` envelope. `supported_standards()` reads
that existing response, also accepting older flat responses. It returns `None`
when an older CLI omits the advertisement and `[]` for an explicitly empty list;
it never infers support from the unchanged machine protocol version `1`.
Definition status, Harness support and local readiness remain separate. Failed
preflight can still be inspected; starting a Run remains blocked.
Harness uses the selected Agent's exact locked Component versions. A selected
graph with multiple versions of an actively named Component is reported as a
Runner limitation rather than choosing an arbitrary installed version.

Host capability advertisement is role-specific. `register_model_provider` automatically advertises the registry ID as `provider` plus semantic-action, structured-output, multimodal-input, and usage-reporting flags; pass model-specific overrides such as `model` or `context_window_tokens` when known. `register_embedding_provider` registers the `embed` provider contract and advertises supported embedding spaces. `register_knowledge_runtime` registers the `retrieve` runtime contract and advertises supported modes/features/package attestations. `register_host_provider` remains available for lower-level role-specific capability shapes. `on_approval` advertises approval support and optional cancellation support. After initialization, `host_service_registration(role, registry_id)` exposes the Harness registration result, including `active: false` and a reason when Harness rejects a registration.

Host model providers receive the canonical `ModelRequest`. Use `request["prompt"]` as the system/control/context material and serialize `request["ordered_turns"]` as ordered provider turns: `user_input` as a user message, `assistant_content` as an assistant message, `semantic_action_call` as the provider's native tool/function call when `provider_call_id` and `provider_alias` are present, `semantic_action_result` as the correlated native tool/function result using the same `provider_call_id`, and `repair_feedback` as one model-visible user turn. Do not also flatten the Section 6 transcript or run input into a duplicate prompt message when ordered turns are serialized.

For CLI-launched custom Knowledge runtimes, use `serve_knowledge_runtime_process(registry_id, handler, capabilities)` to serve the public `agentpm-service` JSONL process protocol from a Python provider process. The Pinecone and pgvector reference providers live in <https://github.com/agentpm-dev/agentpm-examples/tree/main/knowledge-packages/m13-reference-providers>; they are examples to copy from, not provider-specific SDK exports.

For CLI-launched custom Memory runtimes, use `serve_memory_runtime_process(registry_id, handler, capabilities)` to serve the same public process protocol for MemoryRuntime methods: `read`, `write`, `count`, `load_operation_state`, `store_operation_state`, and `commit_lifecycle`. PostgreSQL/pgvector and Redis reference providers live in <https://github.com/agentpm-dev/agentpm-examples/tree/main/memory-packages/m16-reference-providers>; they are examples to copy from, not provider-specific SDK exports.

### Load an installed skill package

```python
from agentpm import load_skill

skill = load_skill("@zack/triage-playbook@0.1.0")

print(skill["entrypointPath"])
print(skill["entrypointContent"])
print(skill["references"])
print(skill["scripts"])
print(skill["resolvedTools"])
```

`load_skill()` returns an inspectable Skill object. Skills are **not** runnable SDK objects.

### Load an installed Knowledge package

```python
from agentpm import load_knowledge

knowledge = load_knowledge("@zack/python-docs@0.1.0")

print(knowledge["knowledge"]["mode"])
print(knowledge["documentPaths"])
print(knowledge["chunksPath"])
print(knowledge["sourcesPath"])
print(knowledge["vectorsPath"])
print(knowledge["indexPaths"])
```

`load_knowledge()` returns an inspectable Knowledge object with:

- the installed knowledge manifest
- the installed package root path
- parsed `knowledge` metadata
- absolute paths for declared context documents, chunks, sources, vectors, indexes, and provenance when present

### Load an installed Memory package

```python
from agentpm import load_memory, load_memory_contract

memory = load_memory("@zack/profile-memory@0.1.0")
profile_contract = load_memory_contract(
    memory,
    space="profile",
    record_type="user_preference",
)

print(memory["memory"]["spaces"])
print(memory["build"])
print(memory["contractIndex"])
print(memory["contracts"])
print(profile_contract)
```

`load_memory()` returns an inspectable Memory Blueprint object with:

- the installed memory manifest
- the installed package root path
- parsed `memory` metadata
- parsed `memory/build.json`
- parsed `memory/contracts/index.json`
- absolute paths for declared source schemas and indexed resolved contracts

It is a metadata and contract loader only. It does not provide live record CRUD, retention enforcement, trigger execution, or a hosted memory runtime.

`load_memory_contract()` loads one indexed resolved contract on demand by `space` + `record_type`.

### Load an installed Profile package

```python
from agentpm import load_profile

profile = load_profile("@zack/support-style@0.1.0")

print(profile["profile"]["identity"]["role"])
print(profile["profile"]["objectives"])
print(profile["profile"]["communication"])
```

`load_profile()` returns an inspectable Instruction Profile object with:

- the installed profile manifest
- the installed package root path
- parsed authored `profile` metadata

### Load an installed Loop package

```python
from agentpm import load_loop

loop = load_loop("@zack/incident-response-loop@0.3.0")

print(loop["loop"]["entry_phase"])
print(loop["loop"]["phases"])
print(loop["loop"]["transitions"])
print(loop["loop"]["error_policy"])
```

`load_loop()` returns an inspectable Loop object with:

- the installed loop manifest
- the installed package root path
- parsed authored `loop` metadata

### `load()` stays tool-only

```python
from agentpm import load

load("@zack/triage-playbook@0.1.0")
# raises: use load_skill("@zack/triage-playbook@0.1.0") instead

load("@zack/python-docs@0.1.0")
# raises: use load_knowledge("@zack/python-docs@0.1.0") instead

load("@zack/profile-memory@0.1.0")
# raises: use load_memory("@zack/profile-memory@0.1.0") instead

load("@zack/support-style@0.1.0")
# raises: use load_profile("@zack/support-style@0.1.0") instead

load("@zack/incident-response-loop@0.3.0")
# raises: use load_loop("@zack/incident-response-loop@0.3.0") instead
```

### Optional: LangChain adapter

The adapter is lazy-imported and only needed if you call it.

```python
from agentpm import load, to_langchain_tool  # to_langchain_tool is loaded on first access

loaded = load("@zack/summarize@0.1.0", with_meta=True)
tool = to_langchain_tool(loaded)  # requires `langchain-core` installed
```

If you use the adapter, install LangChain core:

```bash
uv pip install langchain-core
```

---

## Where tools are discovered

Resolution order:

1. `AGENTPM_TOOL_DIR` (environment variable)
2. `./.agentpm/tools` (project-local)
3. `~/.agentpm/tools` (user-local)

Each tool lives in a directory like:

```
.agentpm/
  tools/
    @zack/summarize/
      0.1.0/
        agent.json
        (tool files…)
```

Installed registry agent packages live separately:

```
.agentpm/
  agents/
    @zack/support-agent/
      0.1.0/
        agent.json
        README.md
```

Installed registry skill packages live separately:

```
.agentpm/
  skills/
    @zack/triage-playbook/
      0.1.0/
        agent.json
        SKILL.md
```

Installed registry Knowledge packages live separately:

```
.agentpm/
  knowledge/
    @zack/python-docs/
      0.1.0/
        agent.json
        knowledge/
```

Installed registry Memory packages live separately:

```
.agentpm/
  memory/
    @zack/profile-memory/
      0.1.0/
        agent.json
        schemas/
        memory/
```

## Where installed agents are discovered

Resolution order for `load_agent()`:

1. `AGENTPM_AGENT_DIR` (environment variable)
2. `./.agentpm/agents` (project-local)
3. `~/.agentpm/agents` (user-local)

You can also override per call:

```python
load_agent("@zack/support-agent@0.1.0", agent_dir_override="/path/to/agents")
```

## Where installed skills are discovered

Resolution order for `load_skill()`:

1. `AGENTPM_SKILL_DIR` (environment variable)
2. `./.agentpm/skills` (project-local)
3. `~/.agentpm/skills` (user-local)

You can also override per call:

```python
load_skill("@zack/triage-playbook@0.1.0", skill_dir_override="/path/to/skills")
```

## Where installed Knowledge packages are discovered

Resolution order for `load_knowledge()`:

1. `AGENTPM_KNOWLEDGE_DIR` (environment variable)
2. `./.agentpm/knowledge` (project-local)
3. `~/.agentpm/knowledge` (user-local)

You can also override per call:

```python
load_knowledge("@zack/python-docs@0.1.0", knowledge_dir_override="/path/to/knowledge")
```

## Where installed Memory packages are discovered

Resolution order for `load_memory()`:

1. `AGENTPM_MEMORY_DIR` (environment variable)
2. `./.agentpm/memory` (project-local)
3. `~/.agentpm/memory` (user-local)

You can also override per call:

```python
load_memory("@zack/profile-memory@0.1.0", memory_dir_override="/path/to/memory")
```

---

## Manifest & Runtime Contract

**`agent.json` (minimal fields used by the SDK):**

```json
{
  "name": "@zack/summarize",
  "version": "0.1.0",
  "description": "Summarize long text.",
  "inputs": {
    "type": "object",
    "properties": {
      "text": { "type": "string", "description": "Text to summarize" }
    },
    "required": ["text"]
  },
  "outputs": {
    "type": "object",
    "properties": {
      "summary": { "type": "string", "description": "Summarized text" }
    },
    "required": ["summary"]
  },
  "entrypoint": {
    "command": "python",
    "args": ["main.py"],
    "cwd": ".",
    "timeout_ms": 60000,
    "env": {}
  }
}
```

**Execution contract:**

- SDK writes **inputs JSON** to the process **stdin**.
- Tool writes a single **outputs JSON** object to **stdout**.
- Non-JSON logs should go to **stderr**.
- Process must exit with **code 0** on success.

**Interpreter whitelist:** `node`, `nodejs`, `python`, `python3`.
The CLI validates the interpreter at invocation and checks its runtime and installed environment.

---

## Development

### Project layout

```
src/
  agentpm/
    __init__.py           # re-exports: load, load_agent, load_knowledge, load_memory, load_skill, to_langchain_tool (lazy)
    core.py               # read-only discovery and composition
    _cli.py               # CLI machine transport
    types.py              # JsonValue, TypedDicts
    adapters/
      __init__.py
      langchain.py        # optional adapter
    py.typed              # marks package as typed
tests/
  test_basic.py
  test_load_agent.py
  test_load_memory.py
  test_load_skill.py
```

### Common tasks (via `uv`)

```bash
uv run ruff check .
uv run black --check .
uv run mypy src
uv run pytest -q

# run hooks locally on all files
uv run pre-commit run --all-files
```

---

## Building & Publishing

```bash
# build wheel & sdist
uv run python -m build

# verify metadata
uv run twine check dist/*

# upload (PyPI)
uv run twine upload dist/*

# or TestPyPI first
uv run twine upload -r testpypi dist/*
```

---

## Running mixed-runtime Agent apps with Docker

Some AgentPM tools run on Node, some on Python—and your agent may need to spawn both. Using Docker gives you a single, reproducible environment where both interpreters are installed and on PATH, which avoids the common “interpreter not found” issues that pop up on PaaS/CI or IDEs.

Why Docker?

✅ Both interpreters: Python and Node are available in the same image.

✅ No PATH drama: node/python are present and discoverable.

✅ Prod/CI parity: the same image runs on your laptop, CI, and servers.

✅ Easy secrets: pass API keys via env at docker run/Compose time.

✅ Fewer surprises: consistent OS libs for LLM clients, SSL, etc.

### When to use it

- You deploy to platforms that don’t let you apt-get both runtimes.
- Your agent uses tools with different interpreters (Node + Python).
- Your local dev/IDE PATH differs from production and causes failures.
- You want reproducible builds and easy rollback.

### How to use it

1. Copy the provided Dockerfile and `.dockerignore` from the [container scaffold](https://github.com/agentpm-dev/sdk-python/tree/main/examples/python-agent) into your repo.
2. Install a compatible Linux AgentPM CLI in the image and check `agentpm --version`.
   The linked Dockerfiles are app scaffolds; add the CLI executable for your
   supported Linux x86-64 glibc target to the build context as `agentpm`; the
   scaffold copies it onto PATH. The app dependency manifest must require SDK
   0.1.17+. Supply the app source/build output referenced by its final command.
3. Copy the authored manifest/portable `agent.lock`, then run `agentpm install`
   inside the image with its selected Python. Do not commit `.agentpm/` or copy
   host-managed environments into a different platform/container. For an app
   that loads an installed Agent without a local manifest, change the scaffold
   install command to `agentpm install @your-namespace/your-agent@1.0.0`. CLI 0.1.43 cannot
   replay direct non-Tool package references with `--frozen`; use the exact
   Agent reference and review the resulting lock rather than editing it.
4. Build & run:

```bash
docker build --platform linux/amd64 -t agent-app .
docker run --rm --platform linux/amd64 -e OPENAI_API_KEY agent-app
```

The released Linux CLI 0.1.43 needs glibc 2.39 or newer. These scaffolds use
matching Debian Trixie bases and target Linux x86-64; a different Docker host
needs its own container emulation support. This does not add a native Linux
arm64 or musl CLI release.

Running amd64 images on Apple Silicon depends on Docker's emulator. Container
verification encountered a TLS error under Rosetta and a verified uv 0.13.5
startup crash under QEMU; both SDK container checks passed on native Linux
x86-64. Use a native Linux build runner when emulation blocks installation.
See [container emulation troubleshooting](https://www.agentpackagemanager.com/docs/v0.1/advanced/mixed-runtimes-with-docker#apple-silicon-and-amd64-emulation).

5. For development, use the docker-compose.yml snippet to mount your source and pass env vars conveniently.

### Troubleshooting

- Set `AGENTPM_DEBUG=1` to print the SDK’s project root and package search paths. Environment values are not logged.
- You can force interpreters via:

```ini
AGENTPM_NODE=/usr/bin/node
AGENTPM_PYTHON=/usr/local/bin/python3.13
```

- Use portable `node`/`python` entrypoint commands. Select host-specific executables with the CLI interpreter overrides; the CLI owns managed Python selection.

---

## Troubleshooting

- **`No JSON object found on stdout.`**
  Ensure your tool prints a single JSON object as the last thing on stdout, and writes logs to stderr.

- **`Unsupported agent.json.entrypoint.command`**
  Only `node` / `python` are allowed (including `nodejs` / `python3`). Update `entrypoint.command`.

- **`Interpreter "... " not found on PATH`**
  Install the interpreter or adjust `entrypoint.command`. The CLI checks interpreter availability at invocation.

- **PEP 668 / “externally managed”**
  Use a venv (we recommend `uv venv`) and install with `uv pip install -e ".[dev]"`.

- **IDE can’t import `agentpm`**
  Ensure your interpreter is the project’s `.venv/bin/python`, and that you ran the editable install.

---

## License

MIT — see `LICENSE`.

## Releases, locks and migration

SDK **0.1.17+** reads supported v2/v3/v4 locks and delegates all Python and Node
Tool calls to CLI **0.1.43+**. Older SDKs are not made compatible by upgrading
only the CLI. An unsupported future lock version fails instead of being
rewritten. Keep portable `agent.lock` in source control and local `.agentpm/`
install/runtime state out of it.

For new Python releases, lock integrity identifies the logical release, which
binds every target artifact. CLI install chooses the exact consumer target
before an `any` fallback and verifies provenance, archive bytes and locked Python
wheels. Source-only Tools can use `any` even with native dependencies. Legacy
Python/Node Tools keep their release semantics while using the same CLI bridge.

Use `agentpm install` to update AgentPM package references/install state and
`agentpm install --refresh` for damaged packages. Use the language package manager
to upgrade this SDK. SDK calls do not install, rebuild or repair environments.
Containers and CI jobs need the compatible CLI in addition to this package.

See the public [Python dependency and migration guide](https://www.agentpackagemanager.com/docs/v0.1/advanced/python-dependencies),
[release integrity](https://www.agentpackagemanager.com/docs/v0.1/advanced/release-integrity),
[environment settings](https://www.agentpackagemanager.com/docs/v0.1/advanced/environment-variables)
and [maintained examples](https://github.com/agentpm-dev/agentpm-examples).
Minimal anonymous CLI telemetry is enabled by default; set `AGENTPM_TELEMETRY=0`
for opt-out. See [privacy and feedback](https://www.agentpackagemanager.com/docs/v0.1/advanced/analytics-and-feedback).

## Contributor verification

Build CLI 0.1.43+ from the matching CLI revision, then set `AGENTPM` and
`AGENTPM_TEST_CLI` to that executable. Set `AGENTPM_TEST_UV` to the verified
pinned uv 0.13.5 binary and `AGENTPM_TEST_PYTHON` to a Python 3.11+ executable
to include the no-model native dependency test. The local Registry fixture
serves test archives only; uv verifies the checked-in pydantic resolution's
wheels. No publication or real Registry credentials are needed. Without these
test variables the explicitly marked native integration is skipped.

CI runs the suites and native integration on Linux x64, both macOS architectures
and Windows x64. It compares the byte-identical `fixtures/sdk-v1` snapshots with
`agentpm-dev/cli`'s `crates/agentpm-sdk/contracts/sdk-v1`. Before CLI main contains the compatible
bridge, dispatch CI with `cli_ref` or set repository variable `AGENTPM_CLI_REF`
to the proposed CLI ref. Release workflows always use CLI main; merge the CLI
prerequisite before publishing SDK tags. Hosted passes and published-package
consumer smokes are separate from local source/build checks.
