@aws/nx-plugin 1.0.0-rc.70 → 1.0.0-rc.71
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.
- package/migrations.json +6 -1
- package/package.json +1 -1
- package/src/agentcore-gateway/__snapshots__/generator.spec.ts.snap +1 -1
- package/src/migrations/latest/py-agent-a2a-httpx-client-per-call/metadata.json +3 -0
- package/src/migrations/latest/py-agent-a2a-httpx-client-per-call/migration.d.ts +6 -0
- package/src/migrations/latest/py-agent-a2a-httpx-client-per-call/migration.js +329 -0
- package/src/migrations/latest/py-agent-a2a-httpx-client-per-call/migration.js.map +1 -0
- package/src/py/agent/__snapshots__/generator.protocols.spec.ts.snap +1 -1
- package/src/py/agent/a2a-connection/__snapshots__/generator.spec.ts.snap +55 -14
- package/src/py/agent/a2a-connection/files/agent-connection/app/__targetAgentSnakeCase___client_strands.py.template +1 -3
- package/src/py/dynamodb/__snapshots__/generator.spec.ts.snap +2 -2
- package/src/py/fast-api/__snapshots__/generator.terraform.spec.ts.snap +12 -12
- package/src/py/lambda-function/__snapshots__/generator.spec.ts.snap +2 -2
- package/src/py/mcp-server/__snapshots__/generator.spec.ts.snap +1 -1
- package/src/py/rdb/__snapshots__/generator.spec.ts.snap +1 -1
- package/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap +7 -7
- package/src/trpc/backend/__snapshots__/generator.spec.ts.snap +12 -12
- package/src/ts/agent/__snapshots__/generator.spec.ts.snap +1 -1
- package/src/ts/dcr-proxy/__snapshots__/generator.spec.ts.snap +1 -1
- package/src/ts/dynamodb/__snapshots__/generator.spec.ts.snap +2 -2
- package/src/ts/lambda-function/__snapshots__/generator.spec.ts.snap +2 -2
- package/src/ts/mcp-server/__snapshots__/generator.spec.ts.snap +1 -1
- package/src/ts/rdb/__snapshots__/generator.spec.ts.snap +4 -4
- package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +2 -2
- package/src/ts/react-website/cognito-auth/__snapshots__/generator.terraform.spec.ts.snap +1 -1
- package/src/utils/agent-connection/files/py-core-langchain/a2a/agentcore_a2a_client_langchain.py.template +26 -20
- package/src/utils/agent-connection/files/py-core-strands/a2a/agentcore_a2a_client_strands.py.template +55 -10
- package/src/utils/versions.d.ts +2 -2
- package/src/utils/versions.js +1 -1
- package/src/utils/versions.js.map +1 -1
package/migrations.json
CHANGED
|
@@ -17,6 +17,11 @@
|
|
|
17
17
|
"description": "Move py#agent A2A agent construction (Strands and LangChain) out of module import time and into a FastAPI lifespan handler, stored on app.state; also updates with_session_id/session_id_context to use Generator instead of the deprecated Iterator return type",
|
|
18
18
|
"implementation": "./src/migrations/latest/py-agent-a2a-lifespan-construction/migration"
|
|
19
19
|
},
|
|
20
|
+
"latest-py-agent-a2a-httpx-client-per-call": {
|
|
21
|
+
"version": "1.0.0-rc.71",
|
|
22
|
+
"description": "Rebuild the httpx.AsyncClient (and Strands A2AAgent) per A2A delegate call instead of reusing one built at factory time, fixing a RuntimeError: Event loop is closed on the second call through a shared client",
|
|
23
|
+
"implementation": "./src/migrations/latest/py-agent-a2a-httpx-client-per-call/migration"
|
|
24
|
+
},
|
|
20
25
|
"v1.0.0-rc.50-0001-modernize-function-props-cast": {
|
|
21
26
|
"version": "1.0.0-rc.50",
|
|
22
27
|
"description": "Replace the legacy angle-bracket FunctionProps type assertion with the modern as syntax in generated API constructs",
|
|
@@ -113,7 +118,7 @@
|
|
|
113
118
|
"implementation": "./src/migrations/v1.0.0-rc.65/0002-rolldown-code-splitting/migration"
|
|
114
119
|
},
|
|
115
120
|
"sync-vended-versions": {
|
|
116
|
-
"version": "1.0.0-rc.
|
|
121
|
+
"version": "1.0.0-rc.71",
|
|
117
122
|
"description": "Sync vended dependency versions and the tracked plugin version to those vended by this release",
|
|
118
123
|
"implementation": "./src/utils/version-upgrade-migration/migration"
|
|
119
124
|
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/
|
|
5
|
+
import { type MigrationReturnObject, type Tree } from '@nx/devkit';
|
|
6
|
+
export default function migration(tree: Tree): Promise<MigrationReturnObject>;
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/ import { visitNotIgnoredFiles } from "@nx/devkit";
|
|
5
|
+
import { applyGritQL, matchGritQL } from "../../../utils/ast.js";
|
|
6
|
+
import { formatFilesInSubtree } from "../../../utils/format.js";
|
|
7
|
+
/**
|
|
8
|
+
* Rebuild the `httpx.AsyncClient` (and, for Strands, the `A2AAgent`) fresh on
|
|
9
|
+
* every A2A delegate call, instead of reusing the one built once at factory
|
|
10
|
+
* time - fixes a reproducible `RuntimeError: Event loop is closed` on the
|
|
11
|
+
* second call through a shared client.
|
|
12
|
+
*
|
|
13
|
+
* Both frameworks' A2A clients call out through a synchronous wrapper
|
|
14
|
+
* (`_run_sync`) that runs the async call via `asyncio.run(...)` - a brand new
|
|
15
|
+
* event loop per call, closed when the call returns. `AgentCoreA2aClientConfig`
|
|
16
|
+
* builds one `httpx.AsyncClient` a single time, at factory call time, and that
|
|
17
|
+
* client's connection pool binds to whichever event loop first touches it. So
|
|
18
|
+
* call #1 creates a loop, uses the shared client, closes the loop; call #2
|
|
19
|
+
* creates a *new* loop, but the shared client's pool is still bound to the
|
|
20
|
+
* old, now-closed one.
|
|
21
|
+
*
|
|
22
|
+
* Strands hits the same failure one layer down: `A2AAgent.__call__` is itself
|
|
23
|
+
* synchronous and does its own `asyncio.run(...)` per call internally, while
|
|
24
|
+
* reusing the same factory-built `httpx.AsyncClient` via `client_config`.
|
|
25
|
+
*
|
|
26
|
+
* The fix in both `AgentCoreA2aClientLangChain`/`AgentCoreA2aClientStrands` is
|
|
27
|
+
* to stop handing out a client wired to one long-lived `httpx.AsyncClient`.
|
|
28
|
+
* Instead each call opens a fresh `httpx.AsyncClient` (reusing only the
|
|
29
|
+
* `auth`/`timeout` off the once-built shared config) scoped to that call via
|
|
30
|
+
* `async with`, so its connection pool lives and dies with the same loop that
|
|
31
|
+
* created it. For Strands this also means `AgentCoreA2aClientStrands`'s
|
|
32
|
+
* factories no longer return a raw `A2AAgent` (dropped in favour of a private
|
|
33
|
+
* `_A2AClient` built per call), so the per-target `<Agent>ClientStrands.create`
|
|
34
|
+
* wrapper's `-> A2AAgent` return annotation and its now-unused `A2AAgent`
|
|
35
|
+
* import go stale too.
|
|
36
|
+
*/ const pyMatch = (snippet)=>`language python\n\`${snippet}\``;
|
|
37
|
+
const pyRewrite = (from, to)=>{
|
|
38
|
+
const replacement = to.includes('\n') ? `raw\`${to}\`` : `\`${to}\``;
|
|
39
|
+
return `${pyMatch(from)} => ${replacement}`;
|
|
40
|
+
};
|
|
41
|
+
const allMatch = async (tree, filePath, patterns)=>{
|
|
42
|
+
for (const pattern of patterns){
|
|
43
|
+
if (!await matchGritQL(tree, filePath, pattern)) return false;
|
|
44
|
+
}
|
|
45
|
+
return true;
|
|
46
|
+
};
|
|
47
|
+
// --- agentcore_a2a_client_langchain.py (framework-agnostic core, shared) ---
|
|
48
|
+
const LANGCHAIN_IMPORT_OLD = 'from a2a.client import A2ACardResolver, ClientConfig, ClientFactory';
|
|
49
|
+
const LANGCHAIN_IMPORT_NEW = `import httpx
|
|
50
|
+
from a2a.client import A2ACardResolver, ClientConfig, ClientFactory`;
|
|
51
|
+
const LANGCHAIN_INVOKE_OLD = ` async def _invoke(self, prompt: str) -> str:
|
|
52
|
+
# AgentCoreA2aClientConfig always sets the signed httpx client.
|
|
53
|
+
httpx_client = self._config.httpx_client
|
|
54
|
+
if httpx_client is None:
|
|
55
|
+
raise RuntimeError("A2A client config is missing an httpx client")
|
|
56
|
+
card = await A2ACardResolver(
|
|
57
|
+
httpx_client=httpx_client, base_url=self._url
|
|
58
|
+
).get_agent_card()
|
|
59
|
+
client = ClientFactory(self._config).create(card)
|
|
60
|
+
message = Message(
|
|
61
|
+
kind="message",
|
|
62
|
+
role=Role.user,
|
|
63
|
+
message_id=uuid4().hex,
|
|
64
|
+
parts=[Part(TextPart(kind="text", text=prompt))],
|
|
65
|
+
)
|
|
66
|
+
# The client config uses streaming=False, so the last event carries the
|
|
67
|
+
# complete response.
|
|
68
|
+
reply = ""
|
|
69
|
+
async for event in client.send_message(message):
|
|
70
|
+
text = _text(event)
|
|
71
|
+
if text:
|
|
72
|
+
reply = text
|
|
73
|
+
return reply`;
|
|
74
|
+
const LANGCHAIN_INVOKE_NEW = `async def _invoke(self, prompt: str) -> str:
|
|
75
|
+
# AgentCoreA2aClientConfig always sets the signed httpx client.
|
|
76
|
+
shared_client = self._config.httpx_client
|
|
77
|
+
if shared_client is None:
|
|
78
|
+
raise RuntimeError("A2A client config is missing an httpx client")
|
|
79
|
+
async with httpx.AsyncClient(
|
|
80
|
+
auth=shared_client.auth, timeout=shared_client.timeout
|
|
81
|
+
) as httpx_client:
|
|
82
|
+
card = await A2ACardResolver(
|
|
83
|
+
httpx_client=httpx_client, base_url=self._url
|
|
84
|
+
).get_agent_card()
|
|
85
|
+
client = ClientFactory(
|
|
86
|
+
ClientConfig(httpx_client=httpx_client, streaming=False)
|
|
87
|
+
).create(card)
|
|
88
|
+
message = Message(
|
|
89
|
+
kind="message",
|
|
90
|
+
role=Role.user,
|
|
91
|
+
message_id=uuid4().hex,
|
|
92
|
+
parts=[Part(TextPart(kind="text", text=prompt))],
|
|
93
|
+
)
|
|
94
|
+
# The client config uses streaming=False, so the last event carries
|
|
95
|
+
# the complete response.
|
|
96
|
+
reply = ""
|
|
97
|
+
async for event in client.send_message(message):
|
|
98
|
+
text = _text(event)
|
|
99
|
+
if text:
|
|
100
|
+
reply = text
|
|
101
|
+
return reply`;
|
|
102
|
+
const migrateLangchainCoreClient = async (tree, filePath, nextSteps)=>{
|
|
103
|
+
const contents = tree.read(filePath, 'utf-8') ?? '';
|
|
104
|
+
if (!contents.includes('client = ClientFactory(self._config).create(card)')) return;
|
|
105
|
+
const ready = await allMatch(tree, filePath, [
|
|
106
|
+
pyMatch(LANGCHAIN_IMPORT_OLD),
|
|
107
|
+
pyMatch(LANGCHAIN_INVOKE_OLD)
|
|
108
|
+
]);
|
|
109
|
+
if (!ready) {
|
|
110
|
+
nextSteps.push(`${filePath}: diverged from the generated shape - left untouched. Manually rebuild a fresh httpx.AsyncClient per call in _invoke instead of reusing the one built at factory time (see the agent-connection generator's agentcore_a2a_client_langchain.py template).`);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
await applyGritQL(tree, filePath, pyRewrite(LANGCHAIN_IMPORT_OLD, LANGCHAIN_IMPORT_NEW));
|
|
114
|
+
await applyGritQL(tree, filePath, pyRewrite(LANGCHAIN_INVOKE_OLD, LANGCHAIN_INVOKE_NEW));
|
|
115
|
+
};
|
|
116
|
+
// --- agentcore_a2a_client_strands.py (Strands core client) ------------------
|
|
117
|
+
const STRANDS_IMPORT1_OLD = 'from collections.abc import Callable';
|
|
118
|
+
const STRANDS_IMPORT1_NEW = `import asyncio
|
|
119
|
+
from collections.abc import Callable
|
|
120
|
+
from concurrent.futures import ThreadPoolExecutor`;
|
|
121
|
+
const STRANDS_IMPORT2_OLD = 'from strands.agent.a2a_agent import A2AAgent';
|
|
122
|
+
const STRANDS_IMPORT2_NEW = `import httpx
|
|
123
|
+
from a2a.client import ClientConfig
|
|
124
|
+
from strands.agent.a2a_agent import A2AAgent
|
|
125
|
+
from strands.agent.agent_result import AgentResult`;
|
|
126
|
+
const STRANDS_BUILD_OLD = `def _build(
|
|
127
|
+
config: tuple, *, name: str | None, description: str | None
|
|
128
|
+
) -> A2AAgent:
|
|
129
|
+
url, client_config = config
|
|
130
|
+
kwargs: dict = {"endpoint": url, "client_config": client_config}
|
|
131
|
+
if name:
|
|
132
|
+
kwargs["name"] = name
|
|
133
|
+
if description:
|
|
134
|
+
kwargs["description"] = description
|
|
135
|
+
return A2AAgent(**kwargs)`;
|
|
136
|
+
const STRANDS_BUILD_NEW = `def _run_sync(coro):
|
|
137
|
+
# The tool is invoked from sync agent code, which under uvicorn runs inside a
|
|
138
|
+
# live event loop where asyncio.run() would raise — fall back to a worker.
|
|
139
|
+
try:
|
|
140
|
+
asyncio.get_running_loop()
|
|
141
|
+
except RuntimeError:
|
|
142
|
+
return asyncio.run(coro)
|
|
143
|
+
with ThreadPoolExecutor(max_workers=1) as pool:
|
|
144
|
+
return pool.submit(asyncio.run, coro).result()
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class _A2AClient:
|
|
148
|
+
def __init__(
|
|
149
|
+
self,
|
|
150
|
+
url: str,
|
|
151
|
+
client_config: ClientConfig,
|
|
152
|
+
*,
|
|
153
|
+
name: str | None,
|
|
154
|
+
description: str | None,
|
|
155
|
+
):
|
|
156
|
+
shared_client = client_config.httpx_client
|
|
157
|
+
if shared_client is None:
|
|
158
|
+
raise RuntimeError("A2A client config is missing an httpx client")
|
|
159
|
+
self._url = url
|
|
160
|
+
self._auth = shared_client.auth
|
|
161
|
+
self._timeout = shared_client.timeout
|
|
162
|
+
self._name = name
|
|
163
|
+
self._description = description
|
|
164
|
+
|
|
165
|
+
def __call__(self, prompt: str) -> AgentResult:
|
|
166
|
+
return _run_sync(self._invoke(prompt))
|
|
167
|
+
|
|
168
|
+
async def _invoke(self, prompt: str) -> AgentResult:
|
|
169
|
+
async with httpx.AsyncClient(
|
|
170
|
+
auth=self._auth, timeout=self._timeout
|
|
171
|
+
) as httpx_client:
|
|
172
|
+
agent = A2AAgent(
|
|
173
|
+
endpoint=self._url,
|
|
174
|
+
name=self._name,
|
|
175
|
+
description=self._description,
|
|
176
|
+
client_config=ClientConfig(httpx_client=httpx_client, streaming=False),
|
|
177
|
+
)
|
|
178
|
+
return await agent.invoke_async(prompt)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _build(
|
|
182
|
+
config: tuple, *, name: str | None, description: str | None
|
|
183
|
+
) -> _A2AClient:
|
|
184
|
+
url, client_config = config
|
|
185
|
+
return _A2AClient(url, client_config, name=name, description=description)`;
|
|
186
|
+
const STRANDS_IAM_OLD = ` @staticmethod
|
|
187
|
+
def with_iam_auth(
|
|
188
|
+
agent_runtime_arn: str,
|
|
189
|
+
*,
|
|
190
|
+
name: str | None = None,
|
|
191
|
+
description: str | None = None,
|
|
192
|
+
) -> A2AAgent:
|
|
193
|
+
"""SigV4-authenticated client for a Bedrock AgentCore runtime."""
|
|
194
|
+
return _build(
|
|
195
|
+
AgentCoreA2aClientConfig.with_iam_auth(agent_runtime_arn),
|
|
196
|
+
name=name,
|
|
197
|
+
description=description,
|
|
198
|
+
)`;
|
|
199
|
+
const STRANDS_IAM_NEW = `@staticmethod
|
|
200
|
+
def with_iam_auth(
|
|
201
|
+
agent_runtime_arn: str,
|
|
202
|
+
*,
|
|
203
|
+
name: str | None = None,
|
|
204
|
+
description: str | None = None,
|
|
205
|
+
) -> _A2AClient:
|
|
206
|
+
"""SigV4-authenticated client for a Bedrock AgentCore runtime."""
|
|
207
|
+
return _build(
|
|
208
|
+
AgentCoreA2aClientConfig.with_iam_auth(agent_runtime_arn),
|
|
209
|
+
name=name,
|
|
210
|
+
description=description,
|
|
211
|
+
)`;
|
|
212
|
+
const STRANDS_JWT_OLD = ` @staticmethod
|
|
213
|
+
def with_jwt_auth(
|
|
214
|
+
agent_runtime_arn: str,
|
|
215
|
+
access_token_provider: Callable[[], str],
|
|
216
|
+
*,
|
|
217
|
+
name: str | None = None,
|
|
218
|
+
description: str | None = None,
|
|
219
|
+
) -> A2AAgent:
|
|
220
|
+
"""Bearer-authenticated client for a Bedrock AgentCore runtime."""
|
|
221
|
+
return _build(
|
|
222
|
+
AgentCoreA2aClientConfig.with_jwt_auth(
|
|
223
|
+
agent_runtime_arn, access_token_provider
|
|
224
|
+
),
|
|
225
|
+
name=name,
|
|
226
|
+
description=description,
|
|
227
|
+
)`;
|
|
228
|
+
const STRANDS_JWT_NEW = `@staticmethod
|
|
229
|
+
def with_jwt_auth(
|
|
230
|
+
agent_runtime_arn: str,
|
|
231
|
+
access_token_provider: Callable[[], str],
|
|
232
|
+
*,
|
|
233
|
+
name: str | None = None,
|
|
234
|
+
description: str | None = None,
|
|
235
|
+
) -> _A2AClient:
|
|
236
|
+
"""Bearer-authenticated client for a Bedrock AgentCore runtime."""
|
|
237
|
+
return _build(
|
|
238
|
+
AgentCoreA2aClientConfig.with_jwt_auth(
|
|
239
|
+
agent_runtime_arn, access_token_provider
|
|
240
|
+
),
|
|
241
|
+
name=name,
|
|
242
|
+
description=description,
|
|
243
|
+
)`;
|
|
244
|
+
const STRANDS_NOAUTH_OLD = ` @staticmethod
|
|
245
|
+
def without_auth(
|
|
246
|
+
url: str,
|
|
247
|
+
*,
|
|
248
|
+
name: str | None = None,
|
|
249
|
+
description: str | None = None,
|
|
250
|
+
) -> A2AAgent:
|
|
251
|
+
"""Plain-HTTP client — for local dev."""
|
|
252
|
+
return _build(
|
|
253
|
+
AgentCoreA2aClientConfig.without_auth(url),
|
|
254
|
+
name=name,
|
|
255
|
+
description=description,
|
|
256
|
+
)`;
|
|
257
|
+
const STRANDS_NOAUTH_NEW = `@staticmethod
|
|
258
|
+
def without_auth(
|
|
259
|
+
url: str,
|
|
260
|
+
*,
|
|
261
|
+
name: str | None = None,
|
|
262
|
+
description: str | None = None,
|
|
263
|
+
) -> _A2AClient:
|
|
264
|
+
"""Plain-HTTP client — for local dev."""
|
|
265
|
+
return _build(
|
|
266
|
+
AgentCoreA2aClientConfig.without_auth(url),
|
|
267
|
+
name=name,
|
|
268
|
+
description=description,
|
|
269
|
+
)`;
|
|
270
|
+
const migrateStrandsCoreClient = async (tree, filePath, nextSteps)=>{
|
|
271
|
+
const contents = tree.read(filePath, 'utf-8') ?? '';
|
|
272
|
+
if (!contents.includes('return A2AAgent(**kwargs)')) return;
|
|
273
|
+
const ready = await allMatch(tree, filePath, [
|
|
274
|
+
pyMatch(STRANDS_IMPORT1_OLD),
|
|
275
|
+
pyMatch(STRANDS_IMPORT2_OLD),
|
|
276
|
+
pyMatch(STRANDS_BUILD_OLD),
|
|
277
|
+
pyMatch(STRANDS_IAM_OLD),
|
|
278
|
+
pyMatch(STRANDS_JWT_OLD),
|
|
279
|
+
pyMatch(STRANDS_NOAUTH_OLD)
|
|
280
|
+
]);
|
|
281
|
+
if (!ready) {
|
|
282
|
+
nextSteps.push(`${filePath}: diverged from the generated shape - left untouched. Manually rebuild a fresh httpx.AsyncClient (and A2AAgent) per call instead of reusing the ones built at factory time (see the agent-connection generator's agentcore_a2a_client_strands.py template).`);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
await applyGritQL(tree, filePath, pyRewrite(STRANDS_IMPORT1_OLD, STRANDS_IMPORT1_NEW));
|
|
286
|
+
await applyGritQL(tree, filePath, pyRewrite(STRANDS_IMPORT2_OLD, STRANDS_IMPORT2_NEW));
|
|
287
|
+
await applyGritQL(tree, filePath, pyRewrite(STRANDS_BUILD_OLD, STRANDS_BUILD_NEW));
|
|
288
|
+
await applyGritQL(tree, filePath, pyRewrite(STRANDS_IAM_OLD, STRANDS_IAM_NEW));
|
|
289
|
+
await applyGritQL(tree, filePath, pyRewrite(STRANDS_JWT_OLD, STRANDS_JWT_NEW));
|
|
290
|
+
await applyGritQL(tree, filePath, pyRewrite(STRANDS_NOAUTH_OLD, STRANDS_NOAUTH_NEW));
|
|
291
|
+
};
|
|
292
|
+
// --- <target>_client_strands.py (per-target wrapper, one per connection) ---
|
|
293
|
+
const WRAPPER_IMPORT_OLD = 'from strands.agent.a2a_agent import A2AAgent';
|
|
294
|
+
const WRAPPER_CREATE_OLD = 'def create() -> A2AAgent:\n $body';
|
|
295
|
+
const WRAPPER_CREATE_NEW = 'def create():\n $body';
|
|
296
|
+
const migrateStrandsWrapperClient = async (tree, filePath, nextSteps)=>{
|
|
297
|
+
const contents = tree.read(filePath, 'utf-8') ?? '';
|
|
298
|
+
if (!contents.includes('def create() -> A2AAgent:')) return;
|
|
299
|
+
const ready = await allMatch(tree, filePath, [
|
|
300
|
+
pyMatch(WRAPPER_IMPORT_OLD),
|
|
301
|
+
pyMatch(WRAPPER_CREATE_OLD)
|
|
302
|
+
]);
|
|
303
|
+
if (!ready) {
|
|
304
|
+
nextSteps.push(`${filePath}: diverged from the generated shape - left untouched. Manually drop the A2AAgent import and its -> A2AAgent return annotation on create() (see the py#agent#a2a-connection generator's per-target client_strands.py template).`);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
await applyGritQL(tree, filePath, `${pyMatch(WRAPPER_IMPORT_OLD)} => .`);
|
|
308
|
+
await applyGritQL(tree, filePath, pyRewrite(WRAPPER_CREATE_OLD, WRAPPER_CREATE_NEW));
|
|
309
|
+
};
|
|
310
|
+
export default async function migration(tree) {
|
|
311
|
+
const nextSteps = [];
|
|
312
|
+
const filePaths = [];
|
|
313
|
+
visitNotIgnoredFiles(tree, '', (filePath)=>filePaths.push(filePath));
|
|
314
|
+
for (const filePath of filePaths){
|
|
315
|
+
if (filePath.endsWith('/agentcore_a2a_client_langchain.py')) {
|
|
316
|
+
await migrateLangchainCoreClient(tree, filePath, nextSteps);
|
|
317
|
+
} else if (filePath.endsWith('/agentcore_a2a_client_strands.py')) {
|
|
318
|
+
await migrateStrandsCoreClient(tree, filePath, nextSteps);
|
|
319
|
+
} else if (filePath.endsWith('_client_strands.py')) {
|
|
320
|
+
await migrateStrandsWrapperClient(tree, filePath, nextSteps);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
await formatFilesInSubtree(tree);
|
|
324
|
+
return {
|
|
325
|
+
nextSteps
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
//# sourceMappingURL=migration.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../packages/nx-plugin/src/migrations/latest/py-agent-a2a-httpx-client-per-call/migration.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n type MigrationReturnObject,\n type Tree,\n visitNotIgnoredFiles,\n} from '@nx/devkit';\nimport { applyGritQL, matchGritQL } from '../../../utils/ast';\nimport { formatFilesInSubtree } from '../../../utils/format';\n\n/**\n * Rebuild the `httpx.AsyncClient` (and, for Strands, the `A2AAgent`) fresh on\n * every A2A delegate call, instead of reusing the one built once at factory\n * time - fixes a reproducible `RuntimeError: Event loop is closed` on the\n * second call through a shared client.\n *\n * Both frameworks' A2A clients call out through a synchronous wrapper\n * (`_run_sync`) that runs the async call via `asyncio.run(...)` - a brand new\n * event loop per call, closed when the call returns. `AgentCoreA2aClientConfig`\n * builds one `httpx.AsyncClient` a single time, at factory call time, and that\n * client's connection pool binds to whichever event loop first touches it. So\n * call #1 creates a loop, uses the shared client, closes the loop; call #2\n * creates a *new* loop, but the shared client's pool is still bound to the\n * old, now-closed one.\n *\n * Strands hits the same failure one layer down: `A2AAgent.__call__` is itself\n * synchronous and does its own `asyncio.run(...)` per call internally, while\n * reusing the same factory-built `httpx.AsyncClient` via `client_config`.\n *\n * The fix in both `AgentCoreA2aClientLangChain`/`AgentCoreA2aClientStrands` is\n * to stop handing out a client wired to one long-lived `httpx.AsyncClient`.\n * Instead each call opens a fresh `httpx.AsyncClient` (reusing only the\n * `auth`/`timeout` off the once-built shared config) scoped to that call via\n * `async with`, so its connection pool lives and dies with the same loop that\n * created it. For Strands this also means `AgentCoreA2aClientStrands`'s\n * factories no longer return a raw `A2AAgent` (dropped in favour of a private\n * `_A2AClient` built per call), so the per-target `<Agent>ClientStrands.create`\n * wrapper's `-> A2AAgent` return annotation and its now-unused `A2AAgent`\n * import go stale too.\n */\nconst pyMatch = (snippet: string) => `language python\\n\\`${snippet}\\``;\n\nconst pyRewrite = (from: string, to: string): string => {\n const replacement = to.includes('\\n') ? `raw\\`${to}\\`` : `\\`${to}\\``;\n return `${pyMatch(from)} => ${replacement}`;\n};\n\nconst allMatch = async (\n tree: Tree,\n filePath: string,\n patterns: string[],\n): Promise<boolean> => {\n for (const pattern of patterns) {\n if (!(await matchGritQL(tree, filePath, pattern))) return false;\n }\n return true;\n};\n\n// --- agentcore_a2a_client_langchain.py (framework-agnostic core, shared) ---\n\nconst LANGCHAIN_IMPORT_OLD =\n 'from a2a.client import A2ACardResolver, ClientConfig, ClientFactory';\nconst LANGCHAIN_IMPORT_NEW = `import httpx\nfrom a2a.client import A2ACardResolver, ClientConfig, ClientFactory`;\n\nconst LANGCHAIN_INVOKE_OLD = ` async def _invoke(self, prompt: str) -> str:\n # AgentCoreA2aClientConfig always sets the signed httpx client.\n httpx_client = self._config.httpx_client\n if httpx_client is None:\n raise RuntimeError(\"A2A client config is missing an httpx client\")\n card = await A2ACardResolver(\n httpx_client=httpx_client, base_url=self._url\n ).get_agent_card()\n client = ClientFactory(self._config).create(card)\n message = Message(\n kind=\"message\",\n role=Role.user,\n message_id=uuid4().hex,\n parts=[Part(TextPart(kind=\"text\", text=prompt))],\n )\n # The client config uses streaming=False, so the last event carries the\n # complete response.\n reply = \"\"\n async for event in client.send_message(message):\n text = _text(event)\n if text:\n reply = text\n return reply`;\n\nconst LANGCHAIN_INVOKE_NEW = `async def _invoke(self, prompt: str) -> str:\n # AgentCoreA2aClientConfig always sets the signed httpx client.\n shared_client = self._config.httpx_client\n if shared_client is None:\n raise RuntimeError(\"A2A client config is missing an httpx client\")\n async with httpx.AsyncClient(\n auth=shared_client.auth, timeout=shared_client.timeout\n ) as httpx_client:\n card = await A2ACardResolver(\n httpx_client=httpx_client, base_url=self._url\n ).get_agent_card()\n client = ClientFactory(\n ClientConfig(httpx_client=httpx_client, streaming=False)\n ).create(card)\n message = Message(\n kind=\"message\",\n role=Role.user,\n message_id=uuid4().hex,\n parts=[Part(TextPart(kind=\"text\", text=prompt))],\n )\n # The client config uses streaming=False, so the last event carries\n # the complete response.\n reply = \"\"\n async for event in client.send_message(message):\n text = _text(event)\n if text:\n reply = text\n return reply`;\n\nconst migrateLangchainCoreClient = async (\n tree: Tree,\n filePath: string,\n nextSteps: string[],\n): Promise<void> => {\n const contents = tree.read(filePath, 'utf-8') ?? '';\n if (!contents.includes('client = ClientFactory(self._config).create(card)'))\n return;\n\n const ready = await allMatch(tree, filePath, [\n pyMatch(LANGCHAIN_IMPORT_OLD),\n pyMatch(LANGCHAIN_INVOKE_OLD),\n ]);\n\n if (!ready) {\n nextSteps.push(\n `${filePath}: diverged from the generated shape - left untouched. Manually rebuild a fresh httpx.AsyncClient per call in _invoke instead of reusing the one built at factory time (see the agent-connection generator's agentcore_a2a_client_langchain.py template).`,\n );\n return;\n }\n\n await applyGritQL(\n tree,\n filePath,\n pyRewrite(LANGCHAIN_IMPORT_OLD, LANGCHAIN_IMPORT_NEW),\n );\n await applyGritQL(\n tree,\n filePath,\n pyRewrite(LANGCHAIN_INVOKE_OLD, LANGCHAIN_INVOKE_NEW),\n );\n};\n\n// --- agentcore_a2a_client_strands.py (Strands core client) ------------------\n\nconst STRANDS_IMPORT1_OLD = 'from collections.abc import Callable';\nconst STRANDS_IMPORT1_NEW = `import asyncio\nfrom collections.abc import Callable\nfrom concurrent.futures import ThreadPoolExecutor`;\n\nconst STRANDS_IMPORT2_OLD = 'from strands.agent.a2a_agent import A2AAgent';\nconst STRANDS_IMPORT2_NEW = `import httpx\nfrom a2a.client import ClientConfig\nfrom strands.agent.a2a_agent import A2AAgent\nfrom strands.agent.agent_result import AgentResult`;\n\nconst STRANDS_BUILD_OLD = `def _build(\n config: tuple, *, name: str | None, description: str | None\n) -> A2AAgent:\n url, client_config = config\n kwargs: dict = {\"endpoint\": url, \"client_config\": client_config}\n if name:\n kwargs[\"name\"] = name\n if description:\n kwargs[\"description\"] = description\n return A2AAgent(**kwargs)`;\n\nconst STRANDS_BUILD_NEW = `def _run_sync(coro):\n # The tool is invoked from sync agent code, which under uvicorn runs inside a\n # live event loop where asyncio.run() would raise — fall back to a worker.\n try:\n asyncio.get_running_loop()\n except RuntimeError:\n return asyncio.run(coro)\n with ThreadPoolExecutor(max_workers=1) as pool:\n return pool.submit(asyncio.run, coro).result()\n\n\nclass _A2AClient:\n def __init__(\n self,\n url: str,\n client_config: ClientConfig,\n *,\n name: str | None,\n description: str | None,\n ):\n shared_client = client_config.httpx_client\n if shared_client is None:\n raise RuntimeError(\"A2A client config is missing an httpx client\")\n self._url = url\n self._auth = shared_client.auth\n self._timeout = shared_client.timeout\n self._name = name\n self._description = description\n\n def __call__(self, prompt: str) -> AgentResult:\n return _run_sync(self._invoke(prompt))\n\n async def _invoke(self, prompt: str) -> AgentResult:\n async with httpx.AsyncClient(\n auth=self._auth, timeout=self._timeout\n ) as httpx_client:\n agent = A2AAgent(\n endpoint=self._url,\n name=self._name,\n description=self._description,\n client_config=ClientConfig(httpx_client=httpx_client, streaming=False),\n )\n return await agent.invoke_async(prompt)\n\n\ndef _build(\n config: tuple, *, name: str | None, description: str | None\n) -> _A2AClient:\n url, client_config = config\n return _A2AClient(url, client_config, name=name, description=description)`;\n\nconst STRANDS_IAM_OLD = ` @staticmethod\n def with_iam_auth(\n agent_runtime_arn: str,\n *,\n name: str | None = None,\n description: str | None = None,\n ) -> A2AAgent:\n \"\"\"SigV4-authenticated client for a Bedrock AgentCore runtime.\"\"\"\n return _build(\n AgentCoreA2aClientConfig.with_iam_auth(agent_runtime_arn),\n name=name,\n description=description,\n )`;\n\nconst STRANDS_IAM_NEW = `@staticmethod\ndef with_iam_auth(\n agent_runtime_arn: str,\n *,\n name: str | None = None,\n description: str | None = None,\n) -> _A2AClient:\n \"\"\"SigV4-authenticated client for a Bedrock AgentCore runtime.\"\"\"\n return _build(\n AgentCoreA2aClientConfig.with_iam_auth(agent_runtime_arn),\n name=name,\n description=description,\n )`;\n\nconst STRANDS_JWT_OLD = ` @staticmethod\n def with_jwt_auth(\n agent_runtime_arn: str,\n access_token_provider: Callable[[], str],\n *,\n name: str | None = None,\n description: str | None = None,\n ) -> A2AAgent:\n \"\"\"Bearer-authenticated client for a Bedrock AgentCore runtime.\"\"\"\n return _build(\n AgentCoreA2aClientConfig.with_jwt_auth(\n agent_runtime_arn, access_token_provider\n ),\n name=name,\n description=description,\n )`;\n\nconst STRANDS_JWT_NEW = `@staticmethod\ndef with_jwt_auth(\n agent_runtime_arn: str,\n access_token_provider: Callable[[], str],\n *,\n name: str | None = None,\n description: str | None = None,\n) -> _A2AClient:\n \"\"\"Bearer-authenticated client for a Bedrock AgentCore runtime.\"\"\"\n return _build(\n AgentCoreA2aClientConfig.with_jwt_auth(\n agent_runtime_arn, access_token_provider\n ),\n name=name,\n description=description,\n )`;\n\nconst STRANDS_NOAUTH_OLD = ` @staticmethod\n def without_auth(\n url: str,\n *,\n name: str | None = None,\n description: str | None = None,\n ) -> A2AAgent:\n \"\"\"Plain-HTTP client — for local dev.\"\"\"\n return _build(\n AgentCoreA2aClientConfig.without_auth(url),\n name=name,\n description=description,\n )`;\n\nconst STRANDS_NOAUTH_NEW = `@staticmethod\ndef without_auth(\n url: str,\n *,\n name: str | None = None,\n description: str | None = None,\n) -> _A2AClient:\n \"\"\"Plain-HTTP client — for local dev.\"\"\"\n return _build(\n AgentCoreA2aClientConfig.without_auth(url),\n name=name,\n description=description,\n )`;\n\nconst migrateStrandsCoreClient = async (\n tree: Tree,\n filePath: string,\n nextSteps: string[],\n): Promise<void> => {\n const contents = tree.read(filePath, 'utf-8') ?? '';\n if (!contents.includes('return A2AAgent(**kwargs)')) return;\n\n const ready = await allMatch(tree, filePath, [\n pyMatch(STRANDS_IMPORT1_OLD),\n pyMatch(STRANDS_IMPORT2_OLD),\n pyMatch(STRANDS_BUILD_OLD),\n pyMatch(STRANDS_IAM_OLD),\n pyMatch(STRANDS_JWT_OLD),\n pyMatch(STRANDS_NOAUTH_OLD),\n ]);\n\n if (!ready) {\n nextSteps.push(\n `${filePath}: diverged from the generated shape - left untouched. Manually rebuild a fresh httpx.AsyncClient (and A2AAgent) per call instead of reusing the ones built at factory time (see the agent-connection generator's agentcore_a2a_client_strands.py template).`,\n );\n return;\n }\n\n await applyGritQL(\n tree,\n filePath,\n pyRewrite(STRANDS_IMPORT1_OLD, STRANDS_IMPORT1_NEW),\n );\n await applyGritQL(\n tree,\n filePath,\n pyRewrite(STRANDS_IMPORT2_OLD, STRANDS_IMPORT2_NEW),\n );\n await applyGritQL(\n tree,\n filePath,\n pyRewrite(STRANDS_BUILD_OLD, STRANDS_BUILD_NEW),\n );\n await applyGritQL(\n tree,\n filePath,\n pyRewrite(STRANDS_IAM_OLD, STRANDS_IAM_NEW),\n );\n await applyGritQL(\n tree,\n filePath,\n pyRewrite(STRANDS_JWT_OLD, STRANDS_JWT_NEW),\n );\n await applyGritQL(\n tree,\n filePath,\n pyRewrite(STRANDS_NOAUTH_OLD, STRANDS_NOAUTH_NEW),\n );\n};\n\n// --- <target>_client_strands.py (per-target wrapper, one per connection) ---\n\nconst WRAPPER_IMPORT_OLD = 'from strands.agent.a2a_agent import A2AAgent';\n\nconst WRAPPER_CREATE_OLD = 'def create() -> A2AAgent:\\n $body';\nconst WRAPPER_CREATE_NEW = 'def create():\\n $body';\n\nconst migrateStrandsWrapperClient = async (\n tree: Tree,\n filePath: string,\n nextSteps: string[],\n): Promise<void> => {\n const contents = tree.read(filePath, 'utf-8') ?? '';\n if (!contents.includes('def create() -> A2AAgent:')) return;\n\n const ready = await allMatch(tree, filePath, [\n pyMatch(WRAPPER_IMPORT_OLD),\n pyMatch(WRAPPER_CREATE_OLD),\n ]);\n\n if (!ready) {\n nextSteps.push(\n `${filePath}: diverged from the generated shape - left untouched. Manually drop the A2AAgent import and its -> A2AAgent return annotation on create() (see the py#agent#a2a-connection generator's per-target client_strands.py template).`,\n );\n return;\n }\n\n await applyGritQL(tree, filePath, `${pyMatch(WRAPPER_IMPORT_OLD)} => .`);\n await applyGritQL(\n tree,\n filePath,\n pyRewrite(WRAPPER_CREATE_OLD, WRAPPER_CREATE_NEW),\n );\n};\n\nexport default async function migration(\n tree: Tree,\n): Promise<MigrationReturnObject> {\n const nextSteps: string[] = [];\n\n const filePaths: string[] = [];\n visitNotIgnoredFiles(tree, '', (filePath) => filePaths.push(filePath));\n\n for (const filePath of filePaths) {\n if (filePath.endsWith('/agentcore_a2a_client_langchain.py')) {\n await migrateLangchainCoreClient(tree, filePath, nextSteps);\n } else if (filePath.endsWith('/agentcore_a2a_client_strands.py')) {\n await migrateStrandsCoreClient(tree, filePath, nextSteps);\n } else if (filePath.endsWith('_client_strands.py')) {\n await migrateStrandsWrapperClient(tree, filePath, nextSteps);\n }\n }\n\n await formatFilesInSubtree(tree);\n\n return { nextSteps };\n}\n"],"names":["visitNotIgnoredFiles","applyGritQL","matchGritQL","formatFilesInSubtree","pyMatch","snippet","pyRewrite","from","to","replacement","includes","allMatch","tree","filePath","patterns","pattern","LANGCHAIN_IMPORT_OLD","LANGCHAIN_IMPORT_NEW","LANGCHAIN_INVOKE_OLD","LANGCHAIN_INVOKE_NEW","migrateLangchainCoreClient","nextSteps","contents","read","ready","push","STRANDS_IMPORT1_OLD","STRANDS_IMPORT1_NEW","STRANDS_IMPORT2_OLD","STRANDS_IMPORT2_NEW","STRANDS_BUILD_OLD","STRANDS_BUILD_NEW","STRANDS_IAM_OLD","STRANDS_IAM_NEW","STRANDS_JWT_OLD","STRANDS_JWT_NEW","STRANDS_NOAUTH_OLD","STRANDS_NOAUTH_NEW","migrateStrandsCoreClient","WRAPPER_IMPORT_OLD","WRAPPER_CREATE_OLD","WRAPPER_CREATE_NEW","migrateStrandsWrapperClient","migration","filePaths","endsWith"],"mappings":"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"}
|
|
@@ -42,21 +42,64 @@ class AgentCoreA2aClientConfig:
|
|
|
42
42
|
`;
|
|
43
43
|
|
|
44
44
|
exports[`py#agent#a2a-connection generator > should match snapshot for agent-connection core files > agentcore_a2a_client_strands.py 1`] = `
|
|
45
|
-
"
|
|
45
|
+
"import asyncio
|
|
46
|
+
from collections.abc import Callable
|
|
47
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
46
48
|
|
|
49
|
+
import httpx
|
|
50
|
+
from a2a.client import ClientConfig
|
|
47
51
|
from strands.agent.a2a_agent import A2AAgent
|
|
52
|
+
from strands.agent.agent_result import AgentResult
|
|
48
53
|
|
|
49
54
|
from .agentcore_a2a_client_config import AgentCoreA2aClientConfig
|
|
50
55
|
|
|
51
56
|
|
|
52
|
-
def
|
|
57
|
+
def _run_sync(coro):
|
|
58
|
+
# The tool is invoked from sync agent code, which under uvicorn runs inside a
|
|
59
|
+
# live event loop where asyncio.run() would raise — fall back to a worker.
|
|
60
|
+
try:
|
|
61
|
+
asyncio.get_running_loop()
|
|
62
|
+
except RuntimeError:
|
|
63
|
+
return asyncio.run(coro)
|
|
64
|
+
with ThreadPoolExecutor(max_workers=1) as pool:
|
|
65
|
+
return pool.submit(asyncio.run, coro).result()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _A2AClient:
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
url: str,
|
|
72
|
+
client_config: ClientConfig,
|
|
73
|
+
*,
|
|
74
|
+
name: str | None,
|
|
75
|
+
description: str | None,
|
|
76
|
+
):
|
|
77
|
+
shared_client = client_config.httpx_client
|
|
78
|
+
if shared_client is None:
|
|
79
|
+
raise RuntimeError("A2A client config is missing an httpx client")
|
|
80
|
+
self._url = url
|
|
81
|
+
self._auth = shared_client.auth
|
|
82
|
+
self._timeout = shared_client.timeout
|
|
83
|
+
self._name = name
|
|
84
|
+
self._description = description
|
|
85
|
+
|
|
86
|
+
def __call__(self, prompt: str) -> AgentResult:
|
|
87
|
+
return _run_sync(self._invoke(prompt))
|
|
88
|
+
|
|
89
|
+
async def _invoke(self, prompt: str) -> AgentResult:
|
|
90
|
+
async with httpx.AsyncClient(auth=self._auth, timeout=self._timeout) as httpx_client:
|
|
91
|
+
agent = A2AAgent(
|
|
92
|
+
endpoint=self._url,
|
|
93
|
+
name=self._name,
|
|
94
|
+
description=self._description,
|
|
95
|
+
client_config=ClientConfig(httpx_client=httpx_client, streaming=False),
|
|
96
|
+
)
|
|
97
|
+
return await agent.invoke_async(prompt)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _build(config: tuple, *, name: str | None, description: str | None) -> _A2AClient:
|
|
53
101
|
url, client_config = config
|
|
54
|
-
|
|
55
|
-
if name:
|
|
56
|
-
kwargs["name"] = name
|
|
57
|
-
if description:
|
|
58
|
-
kwargs["description"] = description
|
|
59
|
-
return A2AAgent(**kwargs)
|
|
102
|
+
return _A2AClient(url, client_config, name=name, description=description)
|
|
60
103
|
|
|
61
104
|
|
|
62
105
|
class AgentCoreA2aClientStrands:
|
|
@@ -68,7 +111,7 @@ class AgentCoreA2aClientStrands:
|
|
|
68
111
|
*,
|
|
69
112
|
name: str | None = None,
|
|
70
113
|
description: str | None = None,
|
|
71
|
-
) ->
|
|
114
|
+
) -> _A2AClient:
|
|
72
115
|
"""SigV4-authenticated client for a Bedrock AgentCore runtime."""
|
|
73
116
|
return _build(
|
|
74
117
|
AgentCoreA2aClientConfig.with_iam_auth(agent_runtime_arn),
|
|
@@ -83,7 +126,7 @@ class AgentCoreA2aClientStrands:
|
|
|
83
126
|
*,
|
|
84
127
|
name: str | None = None,
|
|
85
128
|
description: str | None = None,
|
|
86
|
-
) ->
|
|
129
|
+
) -> _A2AClient:
|
|
87
130
|
"""Bearer-authenticated client for a Bedrock AgentCore runtime."""
|
|
88
131
|
return _build(
|
|
89
132
|
AgentCoreA2aClientConfig.with_jwt_auth(agent_runtime_arn, access_token_provider),
|
|
@@ -97,7 +140,7 @@ class AgentCoreA2aClientStrands:
|
|
|
97
140
|
*,
|
|
98
141
|
name: str | None = None,
|
|
99
142
|
description: str | None = None,
|
|
100
|
-
) ->
|
|
143
|
+
) -> _A2AClient:
|
|
101
144
|
"""Plain-HTTP client — for local dev."""
|
|
102
145
|
return _build(
|
|
103
146
|
AgentCoreA2aClientConfig.without_auth(url),
|
|
@@ -110,8 +153,6 @@ class AgentCoreA2aClientStrands:
|
|
|
110
153
|
exports[`py#agent#a2a-connection generator > should match snapshot for agent-connection core files > remote_client_strands.py 1`] = `
|
|
111
154
|
"import os
|
|
112
155
|
|
|
113
|
-
from strands.agent.a2a_agent import A2AAgent
|
|
114
|
-
|
|
115
156
|
from test_agent_connection.core.agentcore_a2a_client_strands import (
|
|
116
157
|
AgentCoreA2aClientStrands,
|
|
117
158
|
)
|
|
@@ -124,7 +165,7 @@ class RemoteClientStrands:
|
|
|
124
165
|
"""Strands client for the Remote A2A agent."""
|
|
125
166
|
|
|
126
167
|
@staticmethod
|
|
127
|
-
def create()
|
|
168
|
+
def create():
|
|
128
169
|
if os.environ.get("LOCAL_DEV") == "true":
|
|
129
170
|
return AgentCoreA2aClientStrands.without_auth("http://localhost:9001/")
|
|
130
171
|
config = get_agentcore_runtime_config()
|
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import os
|
|
2
2
|
|
|
3
|
-
from strands.agent.a2a_agent import A2AAgent
|
|
4
|
-
|
|
5
3
|
from <%- agentConnectionModuleName %>.core.agentcore_a2a_client_strands import (
|
|
6
4
|
AgentCoreA2aClientStrands,
|
|
7
5
|
)
|
|
@@ -14,7 +12,7 @@ class <%- targetAgentClassName %>ClientStrands:
|
|
|
14
12
|
"""Strands client for the <%- targetAgentClassName %> A2A agent."""
|
|
15
13
|
|
|
16
14
|
@staticmethod
|
|
17
|
-
def create()
|
|
15
|
+
def create():
|
|
18
16
|
if os.environ.get("LOCAL_DEV") == "true":
|
|
19
17
|
return AgentCoreA2aClientStrands.without_auth(
|
|
20
18
|
"http://localhost:<%- targetAgentPort %>/"
|
|
@@ -35,7 +35,7 @@ exports[`py#dynamodb generator > should generate terraform modules when iac is t
|
|
|
35
35
|
required_providers {
|
|
36
36
|
aws = {
|
|
37
37
|
source = "hashicorp/aws"
|
|
38
|
-
version = "6.
|
|
38
|
+
version = "6.60.0"
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
}
|
|
@@ -192,7 +192,7 @@ exports[`py#dynamodb generator > should generate terraform modules when iac is t
|
|
|
192
192
|
required_providers {
|
|
193
193
|
aws = {
|
|
194
194
|
source = "hashicorp/aws"
|
|
195
|
-
version = "6.
|
|
195
|
+
version = "6.60.0"
|
|
196
196
|
}
|
|
197
197
|
random = {
|
|
198
198
|
source = "hashicorp/random"
|