ovos-a2a-solver-plugin 0.0.0a5__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.
@@ -0,0 +1,16 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+
13
+ from ovos_a2a_solver.engine import A2AChatEngine
14
+ from ovos_a2a_solver.client import A2AClient, AgentCard, AgentSkill
15
+
16
+ __all__ = ["A2AChatEngine", "A2AClient", "AgentCard", "AgentSkill"]
@@ -0,0 +1,307 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+
13
+ """A2A protocol client — agent-card discovery and task submission."""
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import uuid
19
+ from dataclasses import dataclass, field
20
+ from typing import Any, Dict, Generator, List, Optional
21
+ from urllib.parse import urljoin
22
+
23
+ import httpx
24
+
25
+ from ovos_utils.log import LOG
26
+
27
+
28
+ @dataclass
29
+ class AgentSkill:
30
+ """A capability advertised in an agent card."""
31
+ id: str
32
+ name: str
33
+ description: str = ""
34
+ tags: List[str] = field(default_factory=list)
35
+ examples: List[str] = field(default_factory=list)
36
+
37
+ @classmethod
38
+ def from_dict(cls, d: Dict[str, Any]) -> "AgentSkill":
39
+ return cls(
40
+ id=d.get("id", ""),
41
+ name=d.get("name", ""),
42
+ description=d.get("description", ""),
43
+ tags=d.get("tags", []),
44
+ examples=d.get("examples", []),
45
+ )
46
+
47
+
48
+ @dataclass
49
+ class AgentCard:
50
+ """
51
+ Parsed representation of an A2A agent card (``/.well-known/agent.json``).
52
+
53
+ The A2A agent-card is the discovery document that every compliant A2A server
54
+ exposes. It describes the agent's identity, supported capabilities, and the
55
+ URL at which tasks are accepted.
56
+ """
57
+ name: str
58
+ description: str
59
+ url: str
60
+ version: str = "1.0"
61
+ skills: List[AgentSkill] = field(default_factory=list)
62
+ streaming: bool = False
63
+ raw: Dict[str, Any] = field(default_factory=dict)
64
+
65
+ @classmethod
66
+ def from_dict(cls, d: Dict[str, Any]) -> "AgentCard":
67
+ skills = [AgentSkill.from_dict(s) for s in d.get("skills", [])]
68
+ caps = d.get("capabilities", {})
69
+ return cls(
70
+ name=d.get("name", ""),
71
+ description=d.get("description", ""),
72
+ url=d.get("url", ""),
73
+ version=d.get("version", "1.0"),
74
+ skills=skills,
75
+ streaming=caps.get("streaming", False),
76
+ raw=d,
77
+ )
78
+
79
+
80
+ class A2AClient:
81
+ """
82
+ Minimal A2A JSON-RPC 2.0 client.
83
+
84
+ Handles:
85
+ - Agent-card discovery (``GET /.well-known/agent.json``)
86
+ - Task submission via ``tasks/send`` (blocking)
87
+ - Streaming via ``tasks/sendSubscribe`` (SSE)
88
+
89
+ Args:
90
+ base_url: Root URL of the A2A server (e.g. ``https://agent.example.com``).
91
+ auth_header: Optional ``Authorization`` header value (e.g. ``Bearer <token>``).
92
+ timeout: HTTP timeout in seconds (default 60).
93
+ streaming: Prefer SSE streaming when True.
94
+ """
95
+
96
+ AGENT_CARD_PATH = "/.well-known/agent.json"
97
+ JSONRPC_VERSION = "2.0"
98
+
99
+ def __init__(
100
+ self,
101
+ base_url: str,
102
+ auth_header: Optional[str] = None,
103
+ timeout: float = 60.0,
104
+ streaming: bool = False,
105
+ ) -> None:
106
+ self.base_url = base_url.rstrip("/")
107
+ self.timeout = timeout
108
+ self.streaming = streaming
109
+ headers: Dict[str, str] = {"Content-Type": "application/json"}
110
+ if auth_header:
111
+ headers["Authorization"] = auth_header
112
+ self._http = httpx.Client(headers=headers, timeout=timeout)
113
+
114
+ # ------------------------------------------------------------------
115
+ # Agent-card discovery
116
+ # ------------------------------------------------------------------
117
+
118
+ def fetch_agent_card(self) -> AgentCard:
119
+ """
120
+ Fetch and parse the agent card from ``/.well-known/agent.json``.
121
+
122
+ Returns:
123
+ Parsed :class:`AgentCard`.
124
+
125
+ Raises:
126
+ httpx.HTTPError: On network/HTTP failure.
127
+ ValueError: If the response body is not valid JSON.
128
+ """
129
+ url = self.base_url + self.AGENT_CARD_PATH
130
+ LOG.debug(f"A2AClient: fetching agent card from {url}")
131
+ resp = self._http.get(url)
132
+ resp.raise_for_status()
133
+ data = resp.json()
134
+ card = AgentCard.from_dict(data)
135
+ LOG.debug(f"A2AClient: discovered agent '{card.name}' at {card.url}")
136
+ return card
137
+
138
+ # ------------------------------------------------------------------
139
+ # Task send (blocking)
140
+ # ------------------------------------------------------------------
141
+
142
+ def send_task(
143
+ self,
144
+ message_text: str,
145
+ session_id: Optional[str] = None,
146
+ history: Optional[List[Dict[str, str]]] = None,
147
+ ) -> str:
148
+ """
149
+ Submit a task to the agent and return the final text response.
150
+
151
+ Constructs a ``tasks/send`` JSON-RPC 2.0 request, sends it, and
152
+ extracts the assistant-role ``text`` part from the response.
153
+
154
+ Args:
155
+ message_text: The user's message text.
156
+ session_id: Conversation context identifier (optional).
157
+ history: Prior turns as ``[{"role": ..., "content": ...}]`` (optional).
158
+
159
+ Returns:
160
+ The agent's response text.
161
+
162
+ Raises:
163
+ httpx.HTTPError: On network failure.
164
+ RuntimeError: If the RPC response contains an error object.
165
+ """
166
+ rpc_id = str(uuid.uuid4())
167
+ parts: List[Dict[str, Any]] = [{"type": "text", "text": message_text}]
168
+ msg: Dict[str, Any] = {"role": "user", "parts": parts}
169
+ params: Dict[str, Any] = {
170
+ "id": rpc_id,
171
+ "message": msg,
172
+ }
173
+ if session_id:
174
+ params["sessionId"] = session_id
175
+ if history:
176
+ params["history"] = [
177
+ {"role": t["role"], "parts": [{"type": "text", "text": t["content"]}]}
178
+ for t in history
179
+ ]
180
+
181
+ payload = {
182
+ "jsonrpc": self.JSONRPC_VERSION,
183
+ "id": rpc_id,
184
+ "method": "tasks/send",
185
+ "params": params,
186
+ }
187
+
188
+ url = urljoin(self.base_url + "/", "")
189
+ # A2A servers accept JSON-RPC at their root or at a /tasks path.
190
+ # Try root first; callers can override by subclassing.
191
+ resp = self._http.post(self.base_url, content=json.dumps(payload))
192
+ resp.raise_for_status()
193
+ body = resp.json()
194
+ return self._extract_text(body, rpc_id)
195
+
196
+ # ------------------------------------------------------------------
197
+ # Streaming (SSE) send
198
+ # ------------------------------------------------------------------
199
+
200
+ def stream_task(
201
+ self,
202
+ message_text: str,
203
+ session_id: Optional[str] = None,
204
+ history: Optional[List[Dict[str, str]]] = None,
205
+ ) -> Generator[str, None, None]:
206
+ """
207
+ Submit a task and yield text chunks as they arrive (SSE streaming).
208
+
209
+ Uses ``tasks/sendSubscribe``. Each SSE ``data:`` line is expected to be
210
+ a JSON-RPC response fragment with an ``artifact`` or ``delta`` payload.
211
+
212
+ Args:
213
+ message_text: The user's message text.
214
+ session_id: Conversation context identifier (optional).
215
+ history: Prior turns (optional).
216
+
217
+ Yields:
218
+ Text chunks from the streaming response.
219
+ """
220
+ rpc_id = str(uuid.uuid4())
221
+ parts: List[Dict[str, Any]] = [{"type": "text", "text": message_text}]
222
+ msg: Dict[str, Any] = {"role": "user", "parts": parts}
223
+ params: Dict[str, Any] = {
224
+ "id": rpc_id,
225
+ "message": msg,
226
+ }
227
+ if session_id:
228
+ params["sessionId"] = session_id
229
+ if history:
230
+ params["history"] = [
231
+ {"role": t["role"], "parts": [{"type": "text", "text": t["content"]}]}
232
+ for t in history
233
+ ]
234
+
235
+ payload = {
236
+ "jsonrpc": self.JSONRPC_VERSION,
237
+ "id": rpc_id,
238
+ "method": "tasks/sendSubscribe",
239
+ "params": params,
240
+ }
241
+
242
+ with self._http.stream("POST", self.base_url,
243
+ content=json.dumps(payload),
244
+ headers={"Accept": "text/event-stream"}) as resp:
245
+ resp.raise_for_status()
246
+ for line in resp.iter_lines():
247
+ line = line.strip()
248
+ if not line or not line.startswith("data:"):
249
+ continue
250
+ data_str = line[len("data:"):].strip()
251
+ if data_str == "[DONE]":
252
+ break
253
+ try:
254
+ event = json.loads(data_str)
255
+ except json.JSONDecodeError:
256
+ continue
257
+ chunk = self._extract_stream_chunk(event)
258
+ if chunk:
259
+ yield chunk
260
+
261
+ # ------------------------------------------------------------------
262
+ # Internal helpers
263
+ # ------------------------------------------------------------------
264
+
265
+ @staticmethod
266
+ def _extract_text(body: Dict[str, Any], rpc_id: str) -> str:
267
+ """Extract the assistant text from a ``tasks/send`` response."""
268
+ if "error" in body:
269
+ err = body["error"]
270
+ raise RuntimeError(
271
+ f"A2A RPC error {err.get('code')}: {err.get('message')}"
272
+ )
273
+ result = body.get("result", {})
274
+ # Navigate: result → artifacts[] → parts[] → text
275
+ for artifact in result.get("artifacts", []):
276
+ for part in artifact.get("parts", []):
277
+ if part.get("type") == "text":
278
+ return part["text"]
279
+ # Fallback: some servers put the answer directly in result.message
280
+ msg = result.get("message", {})
281
+ for part in msg.get("parts", []):
282
+ if part.get("type") == "text":
283
+ return part["text"]
284
+ LOG.warning(f"A2AClient: could not extract text from response: {body}")
285
+ return ""
286
+
287
+ @staticmethod
288
+ def _extract_stream_chunk(event: Dict[str, Any]) -> str:
289
+ """Extract incremental text from a streaming SSE event."""
290
+ result = event.get("result", {})
291
+ # streaming events carry delta or artifact
292
+ for key in ("delta", "artifact"):
293
+ artifact = result.get(key, {})
294
+ for part in artifact.get("parts", []):
295
+ if part.get("type") == "text":
296
+ return part["text"]
297
+ return ""
298
+
299
+ def close(self) -> None:
300
+ """Close the underlying HTTP client."""
301
+ self._http.close()
302
+
303
+ def __enter__(self) -> "A2AClient":
304
+ return self
305
+
306
+ def __exit__(self, *_: Any) -> None:
307
+ self.close()
@@ -0,0 +1,218 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+
13
+ """A2AChatEngine — OPM ChatEngine plugin that delegates to an A2A agent."""
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Any, Dict, Iterable, List, Optional
18
+
19
+ from ovos_plugin_manager.templates.agents import AgentMessage, ChatEngine, MessageRole
20
+ from ovos_utils.log import LOG
21
+
22
+ from ovos_a2a_solver.client import A2AClient, AgentCard
23
+
24
+
25
+ class A2AChatEngine(ChatEngine):
26
+ """
27
+ ``ChatEngine`` plugin that proxies all conversations to an external
28
+ `Agent2Agent (A2A) <https://google.github.io/A2A/>`_ agent.
29
+
30
+ The plugin discovers the remote agent via its agent card
31
+ (``/.well-known/agent.json``), converts the OVOS message history to the
32
+ A2A task format, and returns the agent's response as an
33
+ :class:`~ovos_plugin_manager.templates.agents.AgentMessage`.
34
+
35
+ **Entry point group:** ``opm.agents.chat``
36
+ **Entry point id:** ``ovos-a2a-solver``
37
+
38
+ Configuration keys (``persona["engine_config"]``):
39
+
40
+ .. code-block:: yaml
41
+
42
+ engine: ovos-a2a-solver
43
+ engine_config:
44
+ agent_url: "https://my-a2a-agent.example.com"
45
+ auth_header: "Bearer <token>" # optional
46
+ timeout: 60 # seconds, default 60
47
+ streaming: false # set true to use SSE streaming
48
+
49
+ Multiple agents can be chained by stacking personas; each plugin instance
50
+ targets one ``agent_url``.
51
+ """
52
+
53
+ def __init__(self, config: Optional[Dict[str, Any]] = None) -> None:
54
+ super().__init__(config=config)
55
+ agent_url: str = self.config.get("agent_url", "")
56
+ if not agent_url:
57
+ raise ValueError(
58
+ "A2AChatEngine: 'agent_url' is required in engine_config"
59
+ )
60
+ auth_header: Optional[str] = self.config.get("auth_header")
61
+ timeout: float = float(self.config.get("timeout", 60))
62
+ streaming: bool = bool(self.config.get("streaming", False))
63
+
64
+ self._client = A2AClient(
65
+ base_url=agent_url,
66
+ auth_header=auth_header,
67
+ timeout=timeout,
68
+ streaming=streaming,
69
+ )
70
+ self._card: Optional[AgentCard] = None
71
+ self._streaming = streaming
72
+ self._fetch_card()
73
+
74
+ # ------------------------------------------------------------------
75
+ # Agent-card bootstrap
76
+ # ------------------------------------------------------------------
77
+
78
+ def _fetch_card(self) -> None:
79
+ try:
80
+ self._card = self._client.fetch_agent_card()
81
+ LOG.info(
82
+ f"A2AChatEngine: connected to A2A agent '{self._card.name}' "
83
+ f"(streaming={self._card.streaming})"
84
+ )
85
+ # Honour server-side streaming capability; local config can disable it.
86
+ if self._streaming and not self._card.streaming:
87
+ LOG.warning(
88
+ "A2AChatEngine: streaming requested but agent card reports "
89
+ "streaming=False; falling back to blocking send"
90
+ )
91
+ self._streaming = False
92
+ except Exception as exc: # noqa: BLE001
93
+ LOG.warning(
94
+ f"A2AChatEngine: could not fetch agent card: {exc}; "
95
+ "continuing without it — tasks will still be attempted"
96
+ )
97
+
98
+ # ------------------------------------------------------------------
99
+ # ChatEngine contract
100
+ # ------------------------------------------------------------------
101
+
102
+ def continue_chat(
103
+ self,
104
+ messages: List[AgentMessage],
105
+ session_id: str = "default",
106
+ lang: Optional[str] = None,
107
+ units: Optional[str] = None,
108
+ ) -> AgentMessage:
109
+ """
110
+ Send the conversation to the A2A agent and return the response.
111
+
112
+ The last ``user`` message becomes the A2A task message; prior turns are
113
+ forwarded as ``history``.
114
+
115
+ Args:
116
+ messages: Full conversation history (system + user + assistant turns).
117
+ session_id: Session identifier forwarded to the A2A server.
118
+ lang: Ignored (A2A agents handle language internally).
119
+ units: Ignored.
120
+
121
+ Returns:
122
+ :class:`AgentMessage` with ``role=ASSISTANT`` containing the
123
+ agent's response.
124
+ """
125
+ user_text, history = self._split_messages(messages)
126
+ if not user_text:
127
+ LOG.warning("A2AChatEngine.continue_chat: no user message found")
128
+ return AgentMessage(role=MessageRole.ASSISTANT, content="")
129
+
130
+ try:
131
+ text = self._client.send_task(
132
+ message_text=user_text,
133
+ session_id=session_id,
134
+ history=history,
135
+ )
136
+ except Exception as exc: # noqa: BLE001
137
+ LOG.error(f"A2AChatEngine: task failed: {exc}")
138
+ raise
139
+
140
+ return AgentMessage(role=MessageRole.ASSISTANT, content=text)
141
+
142
+ def stream_tokens(
143
+ self,
144
+ messages: List[AgentMessage],
145
+ session_id: str = "default",
146
+ lang: Optional[str] = None,
147
+ units: Optional[str] = None,
148
+ ) -> Iterable[str]:
149
+ """
150
+ Stream response tokens from the A2A agent.
151
+
152
+ Falls back to :meth:`continue_chat` when streaming is disabled.
153
+
154
+ Args:
155
+ messages: Full conversation history.
156
+ session_id: Session identifier.
157
+ lang: Ignored.
158
+ units: Ignored.
159
+
160
+ Yields:
161
+ Text chunks as they arrive.
162
+ """
163
+ if not self._streaming:
164
+ reply = self.continue_chat(messages, session_id, lang, units)
165
+ yield reply.content
166
+ return
167
+
168
+ user_text, history = self._split_messages(messages)
169
+ if not user_text:
170
+ return
171
+
172
+ try:
173
+ yield from self._client.stream_task(
174
+ message_text=user_text,
175
+ session_id=session_id,
176
+ history=history,
177
+ )
178
+ except Exception as exc: # noqa: BLE001
179
+ LOG.error(f"A2AChatEngine: streaming task failed: {exc}")
180
+ raise
181
+
182
+ # ------------------------------------------------------------------
183
+ # Helpers
184
+ # ------------------------------------------------------------------
185
+
186
+ @staticmethod
187
+ def _split_messages(
188
+ messages: List[AgentMessage],
189
+ ) -> tuple[str, List[Dict[str, str]]]:
190
+ """
191
+ Extract the latest user message text and build a history list.
192
+
193
+ System messages are prepended as a first user turn (many A2A servers do
194
+ not have a dedicated system role). Returns ``(user_text, history)``
195
+ where ``history`` excludes the final user message.
196
+ """
197
+ history: List[Dict[str, str]] = []
198
+ user_text = ""
199
+ system_parts: List[str] = []
200
+
201
+ for msg in messages:
202
+ if msg.role == MessageRole.SYSTEM:
203
+ system_parts.append(msg.content)
204
+ elif msg.role == MessageRole.USER:
205
+ if user_text:
206
+ history.append({"role": "user", "content": user_text})
207
+ user_text = msg.content
208
+ elif msg.role == MessageRole.ASSISTANT:
209
+ if user_text:
210
+ history.append({"role": "user", "content": user_text})
211
+ user_text = ""
212
+ history.append({"role": "assistant", "content": msg.content})
213
+
214
+ if system_parts:
215
+ system_turn = {"role": "user", "content": "\n".join(system_parts)}
216
+ history.insert(0, system_turn)
217
+
218
+ return user_text, history
@@ -0,0 +1,20 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+
13
+ # START_VERSION_BLOCK
14
+ VERSION_MAJOR = 0
15
+ VERSION_MINOR = 0
16
+ VERSION_BUILD = 0
17
+ VERSION_ALPHA = 5
18
+ # END_VERSION_BLOCK
19
+
20
+ __version__ = f"{VERSION_MAJOR}.{VERSION_MINOR}.{VERSION_BUILD}" + (f"a{VERSION_ALPHA}" if VERSION_ALPHA else "")
@@ -0,0 +1,200 @@
1
+ Metadata-Version: 2.4
2
+ Name: ovos-a2a-solver-plugin
3
+ Version: 0.0.0a5
4
+ Summary: Consume external A2A agents as OVOS persona solvers
5
+ Author-email: OpenVoiceOS <openvoiceos@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/TigreGotico/ovos-a2a-solver-plugin
8
+ Project-URL: Repository, https://github.com/TigreGotico/ovos-a2a-solver-plugin
9
+ Project-URL: Bug Tracker, https://github.com/OpenVoiceOS/ovos-persona/issues/164
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: ovos-plugin-manager<3.0.0,>=2.3.0a1
14
+ Requires-Dist: httpx>=0.25.0
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest; extra == "test"
17
+ Requires-Dist: pytest-cov; extra == "test"
18
+ Requires-Dist: respx; extra == "test"
19
+ Requires-Dist: fastapi; extra == "test"
20
+ Requires-Dist: uvicorn; extra == "test"
21
+ Requires-Dist: httpx; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ # ovos-a2a-solver-plugin
25
+
26
+ An [OVOS](https://openvoiceos.org) `ChatEngine` plugin that lets an [ovos-persona](https://github.com/OpenVoiceOS/ovos-persona) delegate its reasoning to any external agent that speaks the [Agent2Agent (A2A) protocol](https://google.github.io/A2A/).
27
+
28
+ Implements the consumer side of [OpenVoiceOS/ovos-persona#164](https://github.com/OpenVoiceOS/ovos-persona/issues/164).
29
+
30
+ ---
31
+
32
+ ## What is A2A?
33
+
34
+ Agent2Agent (A2A) is an open protocol that lets software agents interoperate regardless of their internal implementation. An A2A-compliant server:
35
+
36
+ 1. Exposes a discovery document at `GET /.well-known/agent.json` (the *agent card*) that describes its identity, skills, and capabilities.
37
+ 2. Accepts tasks at its root URL as [JSON-RPC 2.0](https://www.jsonrpc.org/specification) requests (`tasks/send` for blocking, `tasks/sendSubscribe` for SSE streaming).
38
+ 3. Returns structured responses with typed *artifact parts* (text, file, data).
39
+
40
+ This plugin implements the **client (consumer) side** only — it calls remote A2A agents from within an OVOS persona.
41
+
42
+ ---
43
+
44
+ ## Installation
45
+
46
+ ```bash
47
+ pip install ovos-a2a-solver-plugin
48
+ ```
49
+
50
+ Requires Python ≥ 3.10 and `ovos-plugin-manager >= 2.3.0a1`.
51
+
52
+ ---
53
+
54
+ ## Configuration
55
+
56
+ Add the plugin as the engine for an ovos-persona persona:
57
+
58
+ ```yaml
59
+ # ~/.config/mycroft/personas/my-a2a-persona.yaml
60
+ name: my-a2a-persona
61
+ engine: ovos-a2a-solver
62
+ engine_config:
63
+ agent_url: "https://my-a2a-agent.example.com" # required
64
+ auth_header: "Bearer <token>" # optional
65
+ timeout: 60 # seconds (default 60)
66
+ streaming: false # set true to use SSE streaming
67
+ ```
68
+
69
+ | Key | Type | Default | Description |
70
+ |-----|------|---------|-------------|
71
+ | `agent_url` | `str` | — | **Required.** Root URL of the A2A server. |
72
+ | `auth_header` | `str` | `None` | Full `Authorization` header value, e.g. `Bearer <token>`. |
73
+ | `timeout` | `float` | `60` | HTTP timeout in seconds. |
74
+ | `streaming` | `bool` | `False` | Use `tasks/sendSubscribe` (SSE) instead of blocking `tasks/send`. Server must advertise `capabilities.streaming: true`. |
75
+
76
+ ---
77
+
78
+ ## Persona wiring example
79
+
80
+ ```python
81
+ from ovos_persona import PersonaService
82
+
83
+ # PersonaService loads persona YAML files automatically.
84
+ # Once the plugin is installed, setting engine: ovos-a2a-solver in the
85
+ # persona YAML is all that is needed.
86
+ svc = PersonaService(config={})
87
+ reply = svc.chat("What is the capital of Portugal?", persona="my-a2a-persona")
88
+ print(reply) # "Lisbon."
89
+ ```
90
+
91
+ Or use the engine directly:
92
+
93
+ ```python
94
+ from ovos_a2a_solver import A2AChatEngine
95
+ from ovos_plugin_manager.templates.agents import AgentMessage, MessageRole
96
+
97
+ engine = A2AChatEngine(config={
98
+ "agent_url": "https://my-a2a-agent.example.com",
99
+ })
100
+
101
+ messages = [
102
+ AgentMessage(role=MessageRole.SYSTEM, content="You are a helpful assistant."),
103
+ AgentMessage(role=MessageRole.USER, content="Hello!"),
104
+ ]
105
+ reply = engine.continue_chat(messages)
106
+ print(reply.content)
107
+ ```
108
+
109
+ For streaming:
110
+
111
+ ```python
112
+ engine = A2AChatEngine(config={
113
+ "agent_url": "https://my-a2a-agent.example.com",
114
+ "streaming": True,
115
+ })
116
+
117
+ for chunk in engine.stream_tokens(messages):
118
+ print(chunk, end="", flush=True)
119
+ ```
120
+
121
+ ---
122
+
123
+ ## A2AClient — low-level usage
124
+
125
+ The `A2AClient` class can be used independently of OPM:
126
+
127
+ ```python
128
+ from ovos_a2a_solver import A2AClient
129
+
130
+ with A2AClient("https://my-a2a-agent.example.com") as client:
131
+ card = client.fetch_agent_card()
132
+ print(card.name, card.skills)
133
+
134
+ answer = client.send_task(
135
+ "Summarise the A2A spec in one sentence.",
136
+ session_id="my-session",
137
+ )
138
+ print(answer)
139
+ ```
140
+
141
+ ---
142
+
143
+ ## Protocol notes
144
+
145
+ ### Agent-card discovery
146
+
147
+ On `__init__` the engine fetches `GET {agent_url}/.well-known/agent.json` and
148
+ logs the agent's name. A failure is non-fatal — the engine continues and will
149
+ attempt tasks anyway (useful when the card endpoint is behind auth).
150
+
151
+ ### Message history
152
+
153
+ OVOS `ChatEngine` receives the full conversation list. The plugin maps it to
154
+ A2A history as follows:
155
+
156
+ | OVOS role | A2A mapping |
157
+ |-----------|-------------|
158
+ | `system` | Injected as the first `user`-role history turn (A2A has no system role) |
159
+ | `user` | `user` history turns; the **last** user message becomes the task message |
160
+ | `assistant` | `assistant` history turns |
161
+
162
+ ### Streaming
163
+
164
+ When `streaming: true` the plugin calls `tasks/sendSubscribe` and yields text
165
+ chunks via SSE. If the server's agent card reports `capabilities.streaming: false`
166
+ the plugin falls back to blocking `tasks/send` and warns.
167
+
168
+ ---
169
+
170
+ ## Development
171
+
172
+ ```bash
173
+ git clone https://github.com/TigreGotico/ovos-a2a-solver-plugin
174
+ cd ovos-a2a-solver-plugin
175
+ pip install -e ".[test]"
176
+ pytest test/ -v
177
+ ```
178
+
179
+ ---
180
+
181
+ ---
182
+
183
+ ## Credits
184
+
185
+ Developed by [TigreGótico](https://tigregotico.pt) for
186
+ [OpenVoiceOS](https://openvoiceos.org).
187
+
188
+ [![NGI0 Commons Fund](./ngi.png)](https://nlnet.nl/project/OpenVoiceOS)
189
+
190
+ This project was funded through the [NGI0 Commons Fund](https://nlnet.nl/commonsfund),
191
+ a fund established by [NLnet](https://nlnet.nl) with financial support from the
192
+ European Commission's [Next Generation Internet](https://ngi.eu) programme, under
193
+ the aegis of [DG Communications Networks, Content and Technology](https://commission.europa.eu/about-european-commission/departments-and-executive-agencies/communications-networks-content-and-technology_en)
194
+ under grant agreement No [101135429](https://cordis.europa.eu/project/id/101135429).
195
+
196
+ ---
197
+
198
+ ## License
199
+
200
+ Apache License 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,10 @@
1
+ ovos_a2a_solver/__init__.py,sha256=XaHUC3QbWZYwE3DJY9vF4R8dtQXQOyXPpbLcOT3cmoU,730
2
+ ovos_a2a_solver/client.py,sha256=p7MqSzfuTx5N4-5XK5ckUZXi2ND5TY4YMtI5IPCw47s,10673
3
+ ovos_a2a_solver/engine.py,sha256=3vgFodeV6XenrqGWuDsAu0Py1-pWBfoxbYA73drB3oY,8028
4
+ ovos_a2a_solver/version.py,sha256=nZH7mMe8UHGoaSx_DER15hdHaEMiMtylArefCQyTmBw,773
5
+ ovos_a2a_solver_plugin-0.0.0a5.dist-info/licenses/LICENSE,sha256=diMg1nN8U1k1xwt21iM4oy1f-blxps2DUYh1zTOdpdI,11347
6
+ ovos_a2a_solver_plugin-0.0.0a5.dist-info/METADATA,sha256=E2a-xgNbaBIyf55zGpp_bPpOn5Ff75dTeOLdS8mNVnQ,6433
7
+ ovos_a2a_solver_plugin-0.0.0a5.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
8
+ ovos_a2a_solver_plugin-0.0.0a5.dist-info/entry_points.txt,sha256=qEo0UtyMBrgffrR-poGsP7e679bZ6ncNUyAuU0ho19k,73
9
+ ovos_a2a_solver_plugin-0.0.0a5.dist-info/top_level.txt,sha256=ovblhi0DvAenWchQcu6kSFbvF23sxr42kmmrYl3EQ8k,16
10
+ ovos_a2a_solver_plugin-0.0.0a5.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [opm.agents.chat]
2
+ ovos-a2a-solver = ovos_a2a_solver.engine:A2AChatEngine
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2022 Casimiro Ferreira
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ ovos_a2a_solver