ai37-agent-host 0.1.0a1__tar.gz

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.
Files changed (34) hide show
  1. ai37_agent_host-0.1.0a1/LICENSE +201 -0
  2. ai37_agent_host-0.1.0a1/PKG-INFO +45 -0
  3. ai37_agent_host-0.1.0a1/README.md +21 -0
  4. ai37_agent_host-0.1.0a1/pyproject.toml +53 -0
  5. ai37_agent_host-0.1.0a1/src/ai37_agent_host/__init__.py +143 -0
  6. ai37_agent_host-0.1.0a1/src/ai37_agent_host/a2a_executor.py +202 -0
  7. ai37_agent_host-0.1.0a1/src/ai37_agent_host/a2ui.py +69 -0
  8. ai37_agent_host-0.1.0a1/src/ai37_agent_host/agui.py +642 -0
  9. ai37_agent_host-0.1.0a1/src/ai37_agent_host/als.py +108 -0
  10. ai37_agent_host-0.1.0a1/src/ai37_agent_host/auth_guard.py +85 -0
  11. ai37_agent_host-0.1.0a1/src/ai37_agent_host/build_task.py +66 -0
  12. ai37_agent_host-0.1.0a1/src/ai37_agent_host/create_agent_host.py +108 -0
  13. ai37_agent_host-0.1.0a1/src/ai37_agent_host/llm.py +77 -0
  14. ai37_agent_host-0.1.0a1/src/ai37_agent_host/mcp/__init__.py +71 -0
  15. ai37_agent_host-0.1.0a1/src/ai37_agent_host/mcp/bridge.py +96 -0
  16. ai37_agent_host-0.1.0a1/src/ai37_agent_host/mcp/challenge_guard.py +106 -0
  17. ai37_agent_host-0.1.0a1/src/ai37_agent_host/mcp/mcp_server.py +173 -0
  18. ai37_agent_host-0.1.0a1/src/ai37_agent_host/mcp/mount.py +151 -0
  19. ai37_agent_host-0.1.0a1/src/ai37_agent_host/mcp/resource_metadata.py +85 -0
  20. ai37_agent_host-0.1.0a1/src/ai37_agent_host/mcp/types.py +89 -0
  21. ai37_agent_host-0.1.0a1/src/ai37_agent_host/observability/__init__.py +19 -0
  22. ai37_agent_host-0.1.0a1/src/ai37_agent_host/observability/langfuse.py +218 -0
  23. ai37_agent_host-0.1.0a1/src/ai37_agent_host/output_modes.py +129 -0
  24. ai37_agent_host-0.1.0a1/src/ai37_agent_host/parse.py +129 -0
  25. ai37_agent_host-0.1.0a1/src/ai37_agent_host/relay/__init__.py +33 -0
  26. ai37_agent_host-0.1.0a1/src/ai37_agent_host/relay/execute.py +222 -0
  27. ai37_agent_host-0.1.0a1/src/ai37_agent_host/relay/extract.py +84 -0
  28. ai37_agent_host-0.1.0a1/src/ai37_agent_host/relay/task_store.py +53 -0
  29. ai37_agent_host-0.1.0a1/src/ai37_agent_host/store_backend/__init__.py +40 -0
  30. ai37_agent_host-0.1.0a1/src/ai37_agent_host/store_backend/attachments_store_backend.py +287 -0
  31. ai37_agent_host-0.1.0a1/src/ai37_agent_host/store_backend/chat_store_backend.py +336 -0
  32. ai37_agent_host-0.1.0a1/src/ai37_agent_host/store_backend/file_context.py +40 -0
  33. ai37_agent_host-0.1.0a1/src/ai37_agent_host/store_backend/types.py +106 -0
  34. ai37_agent_host-0.1.0a1/src/ai37_agent_host/types.py +191 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 AI37
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai37-agent-host
3
+ Version: 0.1.0a1
4
+ Summary: AI37 agent host (Python): A2A + AG-UI + MCP + file-aware store backends поверх a2a-sdk и ai37-agent-sdk. Порт @ai37/agent-host.
5
+ License: Apache-2.0
6
+ License-File: LICENSE
7
+ Author: AI37
8
+ Requires-Python: >=3.11,<4.0
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Requires-Dist: a2a-sdk (>=1.0.0)
16
+ Requires-Dist: ai37-agent-sdk (>=0.1.0a1,<0.2.0)
17
+ Requires-Dist: anyio (>=4.4)
18
+ Requires-Dist: fastapi (>=0.110)
19
+ Requires-Dist: httpx (>=0.27,<0.29)
20
+ Requires-Dist: sse-starlette (>=2.0)
21
+ Requires-Dist: starlette (>=0.37)
22
+ Description-Content-Type: text/markdown
23
+
24
+ # ai37-agent-host (Python)
25
+
26
+ Host-слой A2A-агентов экосистемы **AI37** (Python). Порт TS-пакета `@ai37/agent-host`
27
+ поверх официального **`a2a-sdk`** (Starlette) и базового **`ai37-agent-sdk`** (auth/billing/context).
28
+
29
+ Разработчик агента реализует **один** контракт `AgentHandler.run(req) -> AgentResult` и вызывает
30
+ `create_agent_host(...)`, а host даёт весь транспорт (A2A JSON-RPC/REST, AG-UI SSE, опц. MCP),
31
+ JWT-guard, content-negotiation A2UI, file-aware store-backends и Langfuse-трассировку.
32
+
33
+ > Base-SDK (`ai37-agent-sdk`) — синхронный; host — async. На стыке billing/auth sync-вызовы
34
+ > оборачиваются в `anyio.to_thread.run_sync`, чтобы не блокировать event-loop.
35
+
36
+ ## Статус
37
+
38
+ Порт в работе (Фаза 2). Готово:
39
+
40
+ - `types` — контракты (`AgentHandler`/`AgentInput`/`AgentEvent`/`AgentResult`/`ContextFile`/`A2uiComponent`/…);
41
+ - `als` — request-scope на `contextvars` (`current_ctx`/`current_bearer`/`current_supported_catalog_ids`/…).
42
+
43
+ В работе: `parse`, `build_task`, `a2a_executor`, `auth_guard`, `output_modes`, `a2ui`,
44
+ `create_agent_host`, `store_backend` (+`read_raw`), `agui`, `mcp`, `relay`, `observability/langfuse`.
45
+
@@ -0,0 +1,21 @@
1
+ # ai37-agent-host (Python)
2
+
3
+ Host-слой A2A-агентов экосистемы **AI37** (Python). Порт TS-пакета `@ai37/agent-host`
4
+ поверх официального **`a2a-sdk`** (Starlette) и базового **`ai37-agent-sdk`** (auth/billing/context).
5
+
6
+ Разработчик агента реализует **один** контракт `AgentHandler.run(req) -> AgentResult` и вызывает
7
+ `create_agent_host(...)`, а host даёт весь транспорт (A2A JSON-RPC/REST, AG-UI SSE, опц. MCP),
8
+ JWT-guard, content-negotiation A2UI, file-aware store-backends и Langfuse-трассировку.
9
+
10
+ > Base-SDK (`ai37-agent-sdk`) — синхронный; host — async. На стыке billing/auth sync-вызовы
11
+ > оборачиваются в `anyio.to_thread.run_sync`, чтобы не блокировать event-loop.
12
+
13
+ ## Статус
14
+
15
+ Порт в работе (Фаза 2). Готово:
16
+
17
+ - `types` — контракты (`AgentHandler`/`AgentInput`/`AgentEvent`/`AgentResult`/`ContextFile`/`A2uiComponent`/…);
18
+ - `als` — request-scope на `contextvars` (`current_ctx`/`current_bearer`/`current_supported_catalog_ids`/…).
19
+
20
+ В работе: `parse`, `build_task`, `a2a_executor`, `auth_guard`, `output_modes`, `a2ui`,
21
+ `create_agent_host`, `store_backend` (+`read_raw`), `agui`, `mcp`, `relay`, `observability/langfuse`.
@@ -0,0 +1,53 @@
1
+ [tool.poetry]
2
+ name = "ai37-agent-host"
3
+ version = "0.1.0a1"
4
+ description = "AI37 agent host (Python): A2A + AG-UI + MCP + file-aware store backends поверх a2a-sdk и ai37-agent-sdk. Порт @ai37/agent-host."
5
+ authors = ["AI37"]
6
+ license = "Apache-2.0"
7
+ readme = "README.md"
8
+ packages = [{ include = "ai37_agent_host", from = "src" }]
9
+
10
+ [tool.poetry.dependencies]
11
+ python = "^3.11"
12
+ # Базовый SDK (auth/billing/a2a/context/output-modes).
13
+ # Версионное ограничение (не path!): при сборке wheel даёт валидный Requires-Dist для PyPI.
14
+ # `>=…a1` явно разрешает предрелиз, иначе pip не поставит 0.1.0a1 без --pre.
15
+ ai37-agent-sdk = ">=0.1.0a1,<0.2.0"
16
+ # Несущий A2A-протокол (Starlette-сервер, AgentExecutor, TaskUpdater, TaskStore).
17
+ a2a-sdk = ">=1.0.0"
18
+ fastapi = ">=0.110"
19
+ starlette = ">=0.37"
20
+ sse-starlette = ">=2.0"
21
+ httpx = ">=0.27,<0.29"
22
+ anyio = ">=4.4"
23
+
24
+ [tool.poetry.group.dev.dependencies]
25
+ pytest = "^8.3"
26
+ pytest-asyncio = ">=0.24,<0.26"
27
+ ruff = ">=0.6,<0.13"
28
+ mypy = "^1.11"
29
+
30
+ # Опциональные группы подключаются по мере реализации модулей:
31
+ # mcp (python mcp SDK), observability (langfuse + opentelemetry),
32
+ # agui (ag-ui protocol / самописный SSE), files (deepagents CompositeBackend).
33
+
34
+ [build-system]
35
+ requires = ["poetry-core"]
36
+ build-backend = "poetry.core.masonry.api"
37
+
38
+ [tool.ruff]
39
+ line-length = 100
40
+ target-version = "py311"
41
+
42
+ [tool.ruff.lint]
43
+ select = ["E", "F", "I", "UP", "B"]
44
+
45
+ [tool.mypy]
46
+ python_version = "3.11"
47
+ strict = false
48
+ ignore_missing_imports = true
49
+ warn_unused_ignores = false
50
+
51
+ [tool.pytest.ini_options]
52
+ testpaths = ["tests"]
53
+ asyncio_mode = "auto"
@@ -0,0 +1,143 @@
1
+ """ai37-agent-host (Python): A2A + AG-UI + MCP + file-aware store backends поверх a2a-sdk.
2
+
3
+ Порт ``@ai37/agent-host``. Публичный API расширяется по мере реализации модулей (Фаза 2).
4
+ """
5
+
6
+ from .a2a_executor import HostExecutor
7
+ from .a2ui import A2uiMessage, component_to_a2ui_operations
8
+ from .agui import agui_routes
9
+ from .als import (
10
+ HostLangfuseScope,
11
+ HostScope,
12
+ current_accepted_output_modes,
13
+ current_bearer,
14
+ current_ctx,
15
+ current_langfuse_callbacks,
16
+ current_langfuse_handler,
17
+ current_langfuse_trace,
18
+ current_scope,
19
+ current_supported_catalog_ids,
20
+ current_trace_id,
21
+ reset_scope,
22
+ scope_context,
23
+ set_scope,
24
+ )
25
+ from .auth_guard import AuthGuardMiddleware
26
+ from .create_agent_host import create_agent_host
27
+ from .llm import (
28
+ LITELLM_BASE_URL_ENV,
29
+ LlmConfig,
30
+ LlmConfigurationError,
31
+ create_openai_client,
32
+ resolve_llm_config,
33
+ )
34
+ from .output_modes import (
35
+ A2UI_CAPABILITIES_VERSION,
36
+ client_supports_catalog,
37
+ filter_a2ui_by_catalog,
38
+ filter_a2ui_components,
39
+ negotiate_catalog,
40
+ negotiate_catalogs,
41
+ negotiate_output,
42
+ negotiate_text,
43
+ read_client_capabilities,
44
+ )
45
+ from .store_backend import (
46
+ AttachmentsStoreBackendBase,
47
+ ChatAttachmentsStoreBackend,
48
+ ChatStoreBackend,
49
+ ProjectAttachmentsStoreBackend,
50
+ StoreBackend,
51
+ context_file_path,
52
+ render_context_files_manifest,
53
+ )
54
+ from .types import (
55
+ A2uiAction,
56
+ A2uiComponent,
57
+ A2uiEvent,
58
+ AgentChannel,
59
+ AgentEvent,
60
+ AgentHandler,
61
+ AgentInput,
62
+ AgentRequest,
63
+ AgentResult,
64
+ AgentStatus,
65
+ Ai37Metadata,
66
+ ContextFile,
67
+ IntentEnvelope,
68
+ NodeEvent,
69
+ OutputNegotiation,
70
+ ReasoningEvent,
71
+ TextEvent,
72
+ ToolEvent,
73
+ )
74
+
75
+ __all__ = [
76
+ # types
77
+ "AgentChannel",
78
+ "OutputNegotiation",
79
+ "IntentEnvelope",
80
+ "ContextFile",
81
+ "Ai37Metadata",
82
+ "A2uiComponent",
83
+ "AgentStatus",
84
+ "A2uiAction",
85
+ "AgentInput",
86
+ "AgentEvent",
87
+ "NodeEvent",
88
+ "TextEvent",
89
+ "A2uiEvent",
90
+ "ReasoningEvent",
91
+ "ToolEvent",
92
+ "AgentResult",
93
+ "AgentRequest",
94
+ "AgentHandler",
95
+ # als
96
+ "HostScope",
97
+ "HostLangfuseScope",
98
+ "set_scope",
99
+ "reset_scope",
100
+ "scope_context",
101
+ "current_scope",
102
+ "current_ctx",
103
+ "current_bearer",
104
+ "current_accepted_output_modes",
105
+ "current_supported_catalog_ids",
106
+ "current_trace_id",
107
+ "current_langfuse_trace",
108
+ "current_langfuse_handler",
109
+ "current_langfuse_callbacks",
110
+ # output-modes (host negotiation)
111
+ "A2UI_CAPABILITIES_VERSION",
112
+ "negotiate_text",
113
+ "negotiate_catalog",
114
+ "negotiate_catalogs",
115
+ "negotiate_output",
116
+ "read_client_capabilities",
117
+ "client_supports_catalog",
118
+ "filter_a2ui_components",
119
+ "filter_a2ui_by_catalog",
120
+ # a2ui
121
+ "A2uiMessage",
122
+ "component_to_a2ui_operations",
123
+ # llm (client from ctx.llm_key + LITELLM_BASE_URL)
124
+ "LITELLM_BASE_URL_ENV",
125
+ "LlmConfig",
126
+ "LlmConfigurationError",
127
+ "resolve_llm_config",
128
+ "create_openai_client",
129
+ # host app
130
+ "create_agent_host",
131
+ "HostExecutor",
132
+ "AuthGuardMiddleware",
133
+ # agui (AG-UI SSE adapter)
134
+ "agui_routes",
135
+ # store-backend (file-aware)
136
+ "StoreBackend",
137
+ "AttachmentsStoreBackendBase",
138
+ "ChatAttachmentsStoreBackend",
139
+ "ProjectAttachmentsStoreBackend",
140
+ "ChatStoreBackend",
141
+ "context_file_path",
142
+ "render_context_files_manifest",
143
+ ]
@@ -0,0 +1,202 @@
1
+ """A2A-адаптер host'а — порт ``ts-host/src/a2a-executor.ts`` на ``a2a-sdk`` 1.x.
2
+
3
+ ``HostExecutor`` парсит A2A-сообщение → вызывает ``AgentHandler`` с verified ``AgentContext``
4
+ (из ALS) → финализирует таск через ``TaskUpdater``. Когниции не содержит.
5
+
6
+ Отличия от TS (обусловлены async/protobuf-природой a2a-sdk):
7
+ * события агента ``emit`` — СИНХРОННЫЕ, а публикация в a2a-sdk — async: мост через
8
+ ``asyncio.Queue`` (sync ``put_nowait``) + фоновый async-drain, порядок сохраняется;
9
+ * финализация — через ``TaskUpdater`` (submit/start_work/add_artifact/complete/failed/
10
+ requires_input), а не построением Task-dict;
11
+ * ``node``/``reasoning`` → ``update_status(WORKING, metadata={'ai37/node'|'ai37/reasoning'})``
12
+ (стрим-событие ``TaskStatusUpdateEvent``); persist-state — в data-part финального артефакта
13
+ (``TaskStatus`` не имеет metadata; ``TaskUpdater`` не пишет ``Task.metadata``).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import asyncio
19
+ from typing import Any
20
+
21
+ from a2a.server.agent_execution import AgentExecutor, RequestContext
22
+ from a2a.server.events import EventQueue
23
+ from a2a.server.tasks import TaskUpdater
24
+ from a2a.types import TaskState
25
+ from google.protobuf.json_format import MessageToDict
26
+
27
+ from .als import current_accepted_output_modes, current_ctx
28
+ from .build_task import data_part, resolve_result_a2ui, text_part
29
+ from .output_modes import negotiate_output
30
+ from .parse import parse_a2a_message
31
+ from .types import AgentEvent, AgentHandler, AgentInput, AgentRequest, AgentResult
32
+
33
+ _STOP = object()
34
+
35
+
36
+ class HostExecutor(AgentExecutor):
37
+ """A2A-адаптер: сообщение → ``AgentHandler.run`` → таск через ``TaskUpdater``.
38
+
39
+ ``agent_text_modes`` — текстовые форматы агента (agent-card ``defaultOutputModes``);
40
+ ``agent_catalog_ids`` — каталог(и) A2UI агента. Для content-negotiation (РЕШЕНИЕ 10).
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ handler: AgentHandler,
46
+ agent_text_modes: list[str] | None = None,
47
+ agent_catalog_ids: str | list[str] | None = None,
48
+ ) -> None:
49
+ self._handler = handler
50
+ self._agent_text_modes = list(agent_text_modes or [])
51
+ self._agent_catalog_ids = agent_catalog_ids
52
+
53
+ async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
54
+ ctx = current_ctx()
55
+ parsed = parse_a2a_message(context)
56
+ accepted = _read_accepted_output_modes(context)
57
+ supported = parsed.supported_catalog_ids or None
58
+ negotiation = negotiate_output(
59
+ accepted_output_modes=accepted,
60
+ agent_text_modes=self._agent_text_modes,
61
+ supported_catalog_ids=supported,
62
+ agent_catalog_ids=self._agent_catalog_ids,
63
+ )
64
+ task_id = context.task_id
65
+ context_id = context.context_id
66
+ updater = TaskUpdater(event_queue, task_id, context_id)
67
+ # На первом ходу публикуем initial submitted-таск; на продолжении (current_task) — нет.
68
+ if getattr(context, "current_task", None) is None:
69
+ await updater.submit()
70
+
71
+ agent_input = AgentInput(
72
+ data=parsed.data,
73
+ metadata=parsed.metadata,
74
+ task_id=task_id,
75
+ context_id=context_id,
76
+ negotiation=negotiation,
77
+ text=parsed.text,
78
+ action=parsed.action,
79
+ claims=ctx.claims if ctx else None,
80
+ billing_org_id=ctx.billing_org_id if ctx else None,
81
+ accepted_output_modes=accepted,
82
+ supported_catalog_ids=supported,
83
+ task_state=_read_prior_state(context),
84
+ )
85
+
86
+ # sync emit → async TaskUpdater: очередь + фоновый drain (порядок сохраняется).
87
+ queue: asyncio.Queue[Any] = asyncio.Queue()
88
+
89
+ def emit(event: AgentEvent) -> None:
90
+ if getattr(event, "type", None) in ("node", "reasoning"):
91
+ queue.put_nowait(event)
92
+
93
+ async def drain() -> None:
94
+ started = False
95
+ while True:
96
+ event = await queue.get()
97
+ if event is _STOP:
98
+ return
99
+ if not started:
100
+ started = True
101
+ await updater.start_work()
102
+ metadata = (
103
+ {"ai37/node": event.node}
104
+ if event.type == "node"
105
+ else {"ai37/reasoning": event.delta}
106
+ )
107
+ await updater.update_status(TaskState.TASK_STATE_WORKING, metadata=metadata)
108
+
109
+ drain_task = asyncio.create_task(drain())
110
+ try:
111
+ result = await self._run_handler(agent_input, ctx, emit)
112
+ finally:
113
+ queue.put_nowait(_STOP)
114
+ await drain_task
115
+
116
+ await self._finalize(updater, result, negotiation)
117
+
118
+ async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
119
+ # Host не знает про доменную отмену; агенты со специфической отменой переопределяют.
120
+ return None
121
+
122
+ async def _run_handler(
123
+ self,
124
+ agent_input: AgentInput,
125
+ ctx: Any,
126
+ emit: Any,
127
+ ) -> AgentResult:
128
+ try:
129
+ return await self._handler.run(AgentRequest(input=agent_input, emit=emit, ctx=ctx))
130
+ except Exception as exc: # noqa: BLE001 - ошибку хода сворачиваем в failed, не пробрасываем
131
+ return AgentResult(status="failed", message=f"INTERNAL: {exc}")
132
+
133
+ async def _finalize(
134
+ self,
135
+ updater: TaskUpdater,
136
+ result: AgentResult,
137
+ negotiation: Any,
138
+ ) -> None:
139
+ a2ui, followup = resolve_result_a2ui(result, negotiation)
140
+
141
+ if result.status == "failed":
142
+ await updater.failed(message=self._agent_msg(updater, result.message or "Ошибка"))
143
+ return
144
+
145
+ if result.status == "input-required":
146
+ payload: dict[str, Any] = {"a2ui": followup or a2ui}
147
+ if result.state is not None:
148
+ payload["state"] = result.state
149
+ await updater.add_artifact(parts=[data_part(payload)], name="input-required")
150
+ await updater.requires_input(
151
+ message=self._agent_msg(updater, result.message or "Уточните")
152
+ )
153
+ return
154
+
155
+ # completed
156
+ completed: dict[str, Any] = {"a2ui": a2ui, "result": result.result}
157
+ if result.state is not None:
158
+ completed["state"] = result.state
159
+ await updater.add_artifact(
160
+ parts=[data_part(completed)], artifact_id="result", name="result"
161
+ )
162
+ await updater.complete(
163
+ message=self._agent_msg(updater, result.message) if result.message else None
164
+ )
165
+
166
+ @staticmethod
167
+ def _agent_msg(updater: TaskUpdater, text: str) -> Any:
168
+ return updater.new_agent_message(parts=[text_part(text)])
169
+
170
+
171
+ def _read_accepted_output_modes(context: RequestContext) -> list[str] | None:
172
+ """Формат текста из нативного configuration.accepted_output_modes (fallback ALS)."""
173
+ config = getattr(context, "configuration", None)
174
+ if config is not None:
175
+ try:
176
+ data = MessageToDict(config, preserving_proto_field_name=False)
177
+ modes = data.get("acceptedOutputModes")
178
+ if isinstance(modes, list):
179
+ return [m for m in modes if isinstance(m, str)]
180
+ except Exception: # noqa: BLE001 - defensive: конфиг может быть не-protobuf
181
+ pass
182
+ return current_accepted_output_modes()
183
+
184
+
185
+ def _read_prior_state(context: RequestContext) -> dict[str, Any] | None:
186
+ """Persist-state прошлого хода: из data-part артефакта current_task."""
187
+ task = getattr(context, "current_task", None)
188
+ if task is None:
189
+ return None
190
+ try:
191
+ data = MessageToDict(task, preserving_proto_field_name=False)
192
+ except Exception: # noqa: BLE001
193
+ return None
194
+ for artifact in data.get("artifacts", []) or []:
195
+ for part in artifact.get("parts", []) or []:
196
+ payload = part.get("data")
197
+ if isinstance(payload, dict) and isinstance(payload.get("state"), dict):
198
+ return payload["state"]
199
+ metadata = data.get("metadata")
200
+ if isinstance(metadata, dict) and isinstance(metadata.get("state"), dict):
201
+ return metadata["state"]
202
+ return None