a2acode 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
a2acode/server.py ADDED
@@ -0,0 +1,88 @@
1
+ """Server assembly.
2
+
3
+ Wires a backend through the executor into a standards-compliant A2A Starlette
4
+ app: JSON-RPC and REST bindings, the well-known agent card, and push
5
+ notifications so callers can register a webhook for long-running tasks instead
6
+ of holding a stream open.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable
12
+ from contextlib import asynccontextmanager
13
+
14
+ import httpx
15
+ from a2a.server.context import ServerCallContext
16
+ from a2a.server.request_handlers import DefaultRequestHandler
17
+ from a2a.server.routes import (
18
+ create_agent_card_routes,
19
+ create_jsonrpc_routes,
20
+ create_rest_routes,
21
+ )
22
+ from a2a.server.tasks import (
23
+ BasePushNotificationSender,
24
+ InMemoryPushNotificationConfigStore,
25
+ InMemoryTaskStore,
26
+ )
27
+ from a2a.types import AgentCard
28
+ from starlette.applications import Starlette
29
+ from starlette.middleware import Middleware
30
+
31
+ from .auth import BearerAuthMiddleware
32
+ from .backends.base import Backend
33
+ from .card import build_card
34
+ from .executor import ClaudeCodeExecutor
35
+
36
+
37
+ def build_app(
38
+ backend: Backend,
39
+ *,
40
+ url: str,
41
+ card_name: str | None = None,
42
+ card_description: str | None = None,
43
+ card_signer: Callable[[AgentCard], AgentCard] | None = None,
44
+ auth_token: str | None = None,
45
+ ) -> Starlette:
46
+ card = build_card(
47
+ url,
48
+ name=card_name or "Claude Code",
49
+ description=card_description,
50
+ streaming=True,
51
+ push_notifications=True,
52
+ require_auth=auth_token is not None,
53
+ )
54
+ if card_signer is not None:
55
+ card = card_signer(card)
56
+
57
+ push_config_store = InMemoryPushNotificationConfigStore()
58
+ push_client = httpx.AsyncClient()
59
+ push_sender = BasePushNotificationSender(
60
+ httpx_client=push_client,
61
+ config_store=push_config_store,
62
+ context=ServerCallContext(),
63
+ )
64
+
65
+ handler = DefaultRequestHandler(
66
+ agent_executor=ClaudeCodeExecutor(backend),
67
+ task_store=InMemoryTaskStore(),
68
+ agent_card=card,
69
+ push_config_store=push_config_store,
70
+ push_sender=push_sender,
71
+ )
72
+
73
+ @asynccontextmanager
74
+ async def lifespan(_app):
75
+ yield
76
+ await push_client.aclose()
77
+
78
+ routes = [
79
+ *create_agent_card_routes(card),
80
+ *create_jsonrpc_routes(handler, rpc_url="/", enable_v0_3_compat=True),
81
+ *create_rest_routes(handler, enable_v0_3_compat=True),
82
+ ]
83
+ middleware = (
84
+ [Middleware(BearerAuthMiddleware, token=auth_token)]
85
+ if auth_token is not None
86
+ else None
87
+ )
88
+ return Starlette(routes=routes, lifespan=lifespan, middleware=middleware)
a2acode/tracing.py ADDED
@@ -0,0 +1,41 @@
1
+ """Distributed tracing.
2
+
3
+ A2A runs over HTTP, so it slots into standard OpenTelemetry tracing: the SDK
4
+ already instruments its own client/server/task paths, and this adds a span for
5
+ a2acode's own protocol-mapping layer so a trace shows where time went inside
6
+ the executor, not just in the SDK.
7
+
8
+ OpenTelemetry is an optional dependency (install ``a2acode[telemetry]``). When
9
+ it is absent, ``span`` is a no-op context manager, so the core install and the
10
+ hot path stay free of the dependency. Trace context propagation over HTTP
11
+ headers is handled by the standard OTel instrumentation, not here.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Iterator
17
+ from contextlib import contextmanager
18
+ from typing import Any
19
+
20
+ try:
21
+ from opentelemetry import trace
22
+
23
+ _tracer: Any | None = trace.get_tracer("a2acode")
24
+ except ImportError: # opentelemetry not installed: tracing is a no-op
25
+ _tracer = None
26
+
27
+
28
+ @contextmanager
29
+ def span(name: str, **attributes: Any) -> Iterator[None]:
30
+ """Run the block inside a span named ``name`` if tracing is available.
31
+
32
+ ``None``-valued attributes are dropped so they do not clutter the span.
33
+ """
34
+ if _tracer is None:
35
+ yield
36
+ return
37
+ with _tracer.start_as_current_span(name) as current:
38
+ for key, value in attributes.items():
39
+ if value is not None:
40
+ current.set_attribute(key, value)
41
+ yield
@@ -0,0 +1,215 @@
1
+ Metadata-Version: 2.4
2
+ Name: a2acode
3
+ Version: 0.4.0
4
+ Summary: Serve Claude Code and other ACP coding agents over the A2A protocol.
5
+ Keywords: a2a,acp,claude-code,agent,agent2agent
6
+ Author: kanywst
7
+ License-Expression: Apache-2.0
8
+ Requires-Dist: a2a-sdk[http-server,signing]>=1.1,<2
9
+ Requires-Dist: agent-client-protocol>=0.10,<1
10
+ Requires-Dist: uvicorn>=0.49
11
+ Requires-Dist: httpx>=0.28
12
+ Requires-Dist: typer>=0.26
13
+ Requires-Dist: claude-agent-sdk>=0.2.101 ; extra == 'claude'
14
+ Requires-Dist: a2a-sdk[telemetry]>=1.1,<2 ; extra == 'telemetry'
15
+ Requires-Dist: opentelemetry-api>=1.33 ; extra == 'telemetry'
16
+ Requires-Python: >=3.13
17
+ Project-URL: Repository, https://github.com/kanywst/a2acode
18
+ Provides-Extra: claude
19
+ Provides-Extra: telemetry
20
+ Description-Content-Type: text/markdown
21
+
22
+ <img src="assets/mascot.png" alt="a2acode" width="150" align="right">
23
+
24
+ # a2acode
25
+
26
+ Serve a coding agent over the [A2A](https://a2aprotocol.ai/) protocol. Other agents call it over A2A; it drives a real coding-agent session in your project — Claude Code, or any agent that speaks Zed's [Agent Client Protocol](https://agentclientprotocol.com) (ACP): Gemini CLI, Codex, OpenHands, and more — and streams the work back as it happens.
27
+
28
+ [![CI](https://github.com/kanywst/a2acode/actions/workflows/ci.yml/badge.svg)](https://github.com/kanywst/a2acode/actions/workflows/ci.yml)
29
+ [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
30
+ [![Python 3.13+](https://img.shields.io/badge/python-3.13+-blue.svg)](https://www.python.org/)
31
+ [![Protocol: A2A 1.0](https://img.shields.io/badge/protocol-A2A%201.0-D97757.svg)](https://a2aprotocol.ai/)
32
+
33
+ ![a2acode streaming a task, then pausing on a permission prompt](assets/demo.gif)
34
+
35
+ Most adapters that put a coding agent behind A2A flatten everything to text in, text out. a2acode keeps the structure the agent produces: the tools it runs, the files it changes, what it costs, the approvals it needs, and how to continue on the next turn. It bridges two Linux Foundation interop standards — **ACP** (how editors and clients talk to coding agents) on the agent side, **A2A** (how agents delegate to each other) on the caller side — so any ACP agent becomes a peer any A2A orchestrator can call.
36
+
37
+ ## How it maps to A2A
38
+
39
+ | The coding agent produces | A2A surface it lands on |
40
+ | ------------------------- | -------------------------------------------------- |
41
+ | Assistant text | A streamed artifact (`append` / `last_chunk`) |
42
+ | A tool call (Bash, Edit) | A `working` status update for the action |
43
+ | A file edit (diff) | A named artifact carrying the diff |
44
+ | A permission request | An `input-required` pause the caller answers |
45
+ | Run result | Cost, turns, and usage on the completion message |
46
+ | Session id | Mapped to the A2A `contextId` so follow-ups resume |
47
+
48
+ The mapping is all in `executor.py`. Backends only emit normalized events; they never touch the protocol.
49
+
50
+ ## Where this fits
51
+
52
+ Anthropic now ships its own ways to run Claude Code beyond the terminal: Claude Code on the web, background agents, cloud-hosted Routines, and the Managed Agents API. These are the right choices when you want Anthropic to host the run and you live in their ecosystem, and they are typically tied to Anthropic infrastructure and a GitHub-centric flow.
53
+
54
+ a2acode solves a different problem: making any coding agent a first-class peer on a vendor-neutral [A2A](https://a2aprotocol.ai/) mesh. An orchestrator built on any framework discovers it through its agent card and delegates coding work the same way it would to any other A2A agent. The run happens on infrastructure you control, in a workspace you point it at. Reach for a2acode when:
55
+
56
+ - another agent (not a human at a prompt) is the caller, and it speaks A2A;
57
+ - you want the run on your own infrastructure and data boundary, not a vendor VM;
58
+ - you do not want to bet on one vendor's coding agent: ACP makes the backend a launch-command choice, so swapping Claude Code for Codex, Gemini CLI, or OpenHands does not touch the protocol surface your callers depend on.
59
+
60
+ ACP already standardizes the editor↔agent side and a dozen agents speak it; a2acode is the piece that exposes an ACP agent to *remote autonomous callers* over A2A, with permission round-trips and cost preserved as first-class protocol citizens — the part ACP leaves out because it assumes a human in an editor. The practical user is the platform team building that mesh, not the individual developer.
61
+
62
+ ## Requirements
63
+
64
+ - Python 3.13+
65
+ - [uv](https://docs.astral.sh/uv/)
66
+ - An ACP agent adapter for the `acp` backend, launched as a subprocess. The `claude` preset uses `npx @zed-industries/claude-agent-acp` (needs Node and a Claude credential); `gemini` uses the Gemini CLI; or point `--agent-command` at any ACP agent.
67
+
68
+ ## Quick start
69
+
70
+ Install:
71
+
72
+ ```bash
73
+ uv sync
74
+ ```
75
+
76
+ The `echo` backend needs no API key and no Claude install, so you can exercise the whole path offline first:
77
+
78
+ ```bash
79
+ uv run a2acode serve --backend echo &
80
+ # once the "Uvicorn running" line appears:
81
+ uv run a2acode call "fix the failing test"
82
+ ```
83
+
84
+ ```text
85
+ task 189b1c63-1a7b-4908-87c4-c8f3bba8f6b5
86
+ context 0b2a901e-2b6f-4c56-bba2-d0da546936e9
87
+
88
+ · Echo
89
+ fix the failing test
90
+ [completed] $0.0 · 1 turns
91
+ ```
92
+
93
+ Then point it at a real project. The default backend is `acp`, fronting Claude Code through its ACP adapter:
94
+
95
+ ```bash
96
+ uv run a2acode serve --cwd /path/to/project # acp + claude by default
97
+ uv run a2acode call "add a /health endpoint" --url http://localhost:9100/
98
+ ```
99
+
100
+ Swap the agent without touching anything else:
101
+
102
+ ```bash
103
+ uv run a2acode serve --agent gemini --cwd /path/to/project
104
+ uv run a2acode serve --agent-command "npx -y some-other-acp-agent"
105
+ ```
106
+
107
+ Continue the same conversation by passing the `context` from a previous turn:
108
+
109
+ ```bash
110
+ uv run a2acode call "now add a test for it" --context <context-id>
111
+ ```
112
+
113
+ ## Commands
114
+
115
+ | Command | Description |
116
+ | -------------------- | -------------------------------------------- |
117
+ | `a2acode serve` | Start the A2A server |
118
+ | `a2acode call TEXT` | Send a message and print the streamed events |
119
+ | `a2acode card` | Fetch and print the agent card |
120
+
121
+ The agent card is served at `/.well-known/agent-card.json` and advertises Claude Code's abilities as discrete skills (generation, refactor, debug, review, test, explain).
122
+
123
+ ## Backends
124
+
125
+ A backend turns a prompt into a stream of normalized events. Three ship today:
126
+
127
+ - `acp` (default): drives any agent that speaks Zed's Agent Client Protocol as a subprocess. `--agent claude|gemini|codex` selects a launch preset; `--agent-command` drives any other ACP agent. This is the vendor-neutral path.
128
+ - `claude`: drives Claude Code directly through the Claude Agent SDK, no subprocess. Install with `uv sync --extra claude`. Use it when you want the SDK-native path (e.g. `--max-budget-usd`) rather than ACP.
129
+ - `echo`: no dependencies, mirrors the input. For wiring checks and tests.
130
+
131
+ The split keeps the A2A layer independent of how the agent is invoked: backends emit normalized events and never import `a2a.*`; the executor maps those events onto the protocol and never imports an agent SDK. Adding a backend never touches the server or the protocol mapping.
132
+
133
+ ## Authentication
134
+
135
+ Each agent authenticates the way its own tooling does, inherited from the server's environment: the `acp` backend passes the environment through to the adapter subprocess (e.g. `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`), and the `claude` backend uses whatever the Claude CLI is configured with. When the server answers on behalf of other agents, a Claude credential has to be an Anthropic API key (or Bedrock / Vertex); Anthropic does not permit subscription credentials for third-party serving. The `claude` backend can cap per-run cost with `--max-budget-usd`.
136
+
137
+ ## Signed agent cards
138
+
139
+ A caller that discovers this server only has the agent card to go on. Sign it so the caller can confirm the card came from you and was not swapped in transit:
140
+
141
+ ```bash
142
+ uv run a2acode serve --sign-key card-signing.pem --sign-kid my-key-1 --sign-alg ES256
143
+ ```
144
+
145
+ The card is then served with a JWS signature over its canonical form. `--sign-key` is a path to a file holding the key: a PEM private key for asymmetric algorithms (`ES256`, `RS256`), or a shared secret for `HS256`. `--sign-kid` is the key id a verifier uses to look up the matching public key. Unsigned is still the default.
146
+
147
+ ## Caller authentication
148
+
149
+ A signed card proves who the server is; this proves the caller is allowed in. Require a bearer token and the server rejects any task request that does not carry it:
150
+
151
+ ```bash
152
+ uv run a2acode serve --auth-token-file caller-token.txt
153
+ ```
154
+
155
+ When `--auth-token-file` is set, callers must send `Authorization: Bearer <token>`; a request without a valid token gets `401 Unauthorized`. The agent card stays public so a caller can still fetch it to discover the requirement, and the card advertises the bearer scheme in `securitySchemes`. Without the flag the server stays open, as before.
156
+
157
+ A2A keeps the credential at the HTTP layer, so this composes with whatever your gateway already does: terminate TLS, validate OAuth, or rate-limit in front, and let the server enforce the token behind it.
158
+
159
+ ## Permissions
160
+
161
+ A tool that needs approval pauses the task in the A2A `input-required` state instead of being skipped. The caller answers with a follow-up message on the same task:
162
+
163
+ ```bash
164
+ uv run a2acode call "sudo reboot"
165
+ # ... [input-required] Permission requested for Bash: $ sudo reboot
166
+ # reply: a2acode call "allow" --task <id> --context <id>
167
+ uv run a2acode call "allow" --task <id> --context <id>
168
+ ```
169
+
170
+ `allow` (or `yes`, `approve`, `ok`) approves; anything else denies. The agent session stays alive across the pause, so it resumes exactly where it stopped. Over ACP this is the agent's `session/request_permission` call answered from the A2A caller's reply; with the `claude` backend it routes through the Claude SDK's `can_use_tool`.
171
+
172
+ Whatever the agent decides needs approval becomes an `input-required` pause rather than being silently skipped or auto-approved; the caller, not the server, holds the decision. Read-only actions the agent already treats as safe still run without a prompt.
173
+
174
+ ## Long-running tasks
175
+
176
+ The agent card advertises push notifications. A caller can register a webhook for a task and receive status and artifact updates by HTTP POST instead of holding a stream open, which helps when a run takes minutes. Streaming and polling (`tasks/get`) both work too.
177
+
178
+ ## Observability
179
+
180
+ Debugging one agent is hard; debugging a chain of them without traces is worse. Because A2A runs over HTTP, it drops straight into OpenTelemetry: install the extra and the A2A SDK's instrumentation plus a per-task `a2acode.execute` span light up, with W3C trace context propagating across the call so client and server spans share one trace.
181
+
182
+ ```bash
183
+ uv sync --extra telemetry
184
+ ```
185
+
186
+ Tracing is off unless OpenTelemetry is installed, and you configure the exporter the standard way (e.g. `OTEL_EXPORTER_OTLP_ENDPOINT`, or run under `opentelemetry-instrument`). It works against an on-prem or air-gapped collector, so traces never have to leave your network.
187
+
188
+ ## Development
189
+
190
+ ```bash
191
+ uv sync --dev
192
+ uv run ruff check src tests
193
+ uv run ruff format src tests
194
+ uv run mypy
195
+ uv run pytest
196
+ ```
197
+
198
+ CI runs these on Python 3.13 and 3.14, plus a Markdown lint, on every push and pull request.
199
+
200
+ ## Releasing
201
+
202
+ Pushing a `v*` tag builds the package, creates a GitHub release with the artifacts, and publishes to PyPI via trusted publishing:
203
+
204
+ ```bash
205
+ git tag v0.1.0
206
+ git push origin v0.1.0
207
+ ```
208
+
209
+ ## Status
210
+
211
+ The mapping is complete end to end and verified against real Claude: text round trip, tool-progress updates, streaming artifacts, file diffs as artifacts, run metadata, session continuity, the permission-to-`input-required` round trip, and push notifications. The offline `echo` backend covers every path including permissions, so it can all be exercised without an API key.
212
+
213
+ ## License
214
+
215
+ Apache 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,19 @@
1
+ a2acode/__init__.py,sha256=bBJg-86yBJzAG4GKL4rKvSUpbq5pu-IJBdtg-UDXuzw,253
2
+ a2acode/auth.py,sha256=l_38hz4r284AALo4YHYxVsk3Rp9VF1ozDe4G0FI_VcE,3251
3
+ a2acode/backends/__init__.py,sha256=yfy6-aA7jgMNFSENVlNT76P0uY22bLA1g4yn1dD_hOA,1178
4
+ a2acode/backends/acp.py,sha256=KZwRcOGlKkv8cTxoR2A34FyBnFzRe8AiZ9cy43ipivA,11933
5
+ a2acode/backends/base.py,sha256=dB0tAYBRdXfzUXqU47zHFw3aZ_CeA7XM6JTkb0tHh8E,2418
6
+ a2acode/backends/claude.py,sha256=9Gi8VH3ZRgxA7tCx4keyuyTWqjLWNmeKdX5IqlBmZeE,4659
7
+ a2acode/backends/diff.py,sha256=Xc0eZvRx2X8T7nEYX39t6AxMwXyRlB4aGqSWXFAuNBo,2568
8
+ a2acode/backends/echo.py,sha256=yYbmi-Z7abqunPCBQatuLfjK2x28c0v-medavqy3jAQ,1566
9
+ a2acode/backends/session.py,sha256=J5oLAIh_huc1YFuwy3t89Jqj3Z3vl2604v8hN5WU8Eg,5136
10
+ a2acode/card.py,sha256=7wTjTlmhJHToEUUjmlG7Q2NBEmVv5qe0bhy_ud7L890,6956
11
+ a2acode/cli.py,sha256=KhxTnrigSIkcD4TOyAD0s7_2WpmkqdoKdwHRgafmSyw,10614
12
+ a2acode/executor.py,sha256=FMazNMPvDwaWExt6fMbUW7KiI_mEmIVZRT7sm7WTrJE,15239
13
+ a2acode/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ a2acode/server.py,sha256=8thAQth0amxxs4SSBN_eIu7wzMMbNWt6eXlI8kZ4_hU,2597
15
+ a2acode/tracing.py,sha256=WG0mjpkobyHWEGH7MootxqcE8D_O-3YaM3j5yEOTVrA,1409
16
+ a2acode-0.4.0.dist-info/WHEEL,sha256=jK0lbM7sVtq70msNoYotEXYS3OJMDdns2CRgyjhimnE,81
17
+ a2acode-0.4.0.dist-info/entry_points.txt,sha256=VhgkJ4ZnjsswQYrz43gRb4M3RU5w2pCvnsEs3wqvjTg,45
18
+ a2acode-0.4.0.dist-info/METADATA,sha256=nSY3cUiG4b1qj7Mgwa4-7aTXaZakI0fI4sWnX0rN0iE,12219
19
+ a2acode-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.11.25
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ a2acode = a2acode.cli:app
3
+