@aws/agentcore 1.0.0-preview.2 → 1.0.0-preview.20
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/README.md +193 -33
- package/dist/agent-inspector/index.css +1 -1
- package/dist/agent-inspector/index.js +99 -84
- package/dist/assets/__tests__/__snapshots__/assets.snapshot.test.ts.snap +3132 -366
- package/dist/assets/__tests__/__snapshots__/dockerfile-render.test.ts.snap +6 -2
- package/dist/assets/__tests__/assets.snapshot.test.ts +10 -24
- package/dist/assets/__tests__/googleadk-session-eviction.test.ts +87 -0
- package/dist/assets/__tests__/summarization-namespace.test.ts +43 -0
- package/dist/assets/agents/AGENTS.md +87 -11
- package/dist/assets/cdk/bin/cdk.ts +87 -26
- package/dist/assets/cdk/lib/cdk-stack.ts +185 -55
- package/dist/assets/cdk/package.json +1 -1
- package/dist/assets/cdk/test/cdk.test.ts +4 -0
- package/dist/assets/container/python/Dockerfile +7 -1
- package/dist/assets/container/typescript/Dockerfile +25 -0
- package/dist/assets/container/typescript/dockerignore.template +24 -0
- package/dist/assets/datasets/predefined-v1.jsonl +3 -0
- package/dist/assets/datasets/simulated-v1.jsonl +3 -0
- package/dist/assets/python/a2a/googleadk/base/main.py +24 -16
- package/dist/assets/python/a2a/googleadk/base/pyproject.toml +3 -3
- package/dist/assets/python/a2a/langchain_langgraph/base/main.py +24 -16
- package/dist/assets/python/a2a/langchain_langgraph/base/pyproject.toml +3 -2
- package/dist/assets/python/a2a/strands/base/main.py +23 -17
- package/dist/assets/python/a2a/strands/base/pyproject.toml +2 -2
- package/dist/assets/python/a2a/strands/capabilities/memory/session.py +10 -2
- package/dist/assets/python/agui/googleadk/base/main.py +62 -2
- package/dist/assets/python/agui/googleadk/base/pyproject.toml +3 -3
- package/dist/assets/python/agui/langchain_langgraph/base/main.py +56 -0
- package/dist/assets/python/agui/langchain_langgraph/base/pyproject.toml +2 -1
- package/dist/assets/python/agui/strands/base/main.py +63 -1
- package/dist/assets/python/agui/strands/base/pyproject.toml +1 -1
- package/dist/assets/python/agui/strands/capabilities/memory/session.py +10 -2
- package/dist/assets/python/http/autogen/base/main.py +60 -29
- package/dist/assets/python/http/autogen/base/pyproject.toml +1 -1
- package/dist/assets/python/http/googleadk/base/main.py +69 -24
- package/dist/assets/python/http/googleadk/base/mcp_client/client.py +7 -7
- package/dist/assets/python/http/googleadk/base/pyproject.toml +2 -1
- package/dist/assets/python/http/langchain_langgraph/base/main.py +115 -24
- package/dist/assets/python/http/langchain_langgraph/base/mcp_client/client.py +10 -8
- package/dist/assets/python/http/langchain_langgraph/base/pyproject.toml +3 -2
- package/dist/assets/python/http/openaiagents/base/main.py +61 -32
- package/dist/assets/python/http/openaiagents/base/mcp_client/client.py +4 -4
- package/dist/assets/python/http/openaiagents/base/pyproject.toml +2 -2
- package/dist/assets/python/http/strands/base/main.py +571 -47
- package/dist/assets/python/http/strands/base/mcp_client/client.py +49 -6
- package/dist/assets/python/http/strands/base/model/load.py +119 -3
- package/dist/assets/python/http/strands/base/model/mantle_compat.py +21 -0
- package/dist/assets/python/http/strands/base/pyproject.toml +9 -3
- package/dist/assets/python/http/strands/base/skills/fetcher.py +279 -0
- package/dist/assets/python/http/strands/capabilities/execution-limits/hooks/execution_limits.py +54 -0
- package/dist/assets/python/http/strands/capabilities/memory/session.py +10 -2
- package/dist/assets/python/http/strands/capabilities/payments/__init__.py +4 -0
- package/dist/assets/python/http/strands/capabilities/payments/payments.py +142 -0
- package/dist/assets/python/mcp/standalone/base/main.py +58 -0
- package/dist/assets/typescript/http/strands/base/README.md +37 -0
- package/dist/assets/typescript/http/strands/base/gitignore.template +22 -0
- package/dist/assets/typescript/http/strands/base/main.ts +144 -0
- package/dist/assets/typescript/http/strands/base/mcp_client/client.ts +11 -0
- package/dist/assets/typescript/http/strands/base/model/load.ts +102 -0
- package/dist/assets/typescript/http/strands/base/package.json +38 -0
- package/dist/assets/typescript/http/strands/base/tsconfig.json +19 -0
- package/dist/assets/typescript/http/strands/capabilities/memory/memory.ts +52 -0
- package/dist/assets/typescript/http/vercelai/base/README.md +37 -0
- package/dist/assets/typescript/http/vercelai/base/gitignore.template +22 -0
- package/dist/assets/typescript/http/vercelai/base/main.ts +64 -0
- package/dist/assets/typescript/http/vercelai/base/model/load.ts +121 -0
- package/dist/assets/typescript/http/vercelai/base/package.json +35 -0
- package/dist/assets/typescript/http/vercelai/base/tsconfig.json +19 -0
- package/dist/cli/index.mjs +1416 -568
- package/dist/lib/errors/index.d.ts +1 -1
- package/dist/lib/errors/index.d.ts.map +1 -1
- package/dist/lib/errors/index.js +1 -1
- package/dist/lib/errors/index.js.map +1 -1
- package/dist/lib/errors/types.d.ts +259 -0
- package/dist/lib/errors/types.d.ts.map +1 -0
- package/dist/lib/errors/types.js +402 -0
- package/dist/lib/errors/types.js.map +1 -0
- package/dist/lib/errors/zod.d.ts +8 -0
- package/dist/lib/errors/zod.d.ts.map +1 -0
- package/dist/lib/errors/{config.js → zod.js} +8 -81
- package/dist/lib/errors/zod.js.map +1 -0
- package/dist/lib/index.d.ts +3 -0
- package/dist/lib/index.d.ts.map +1 -1
- package/dist/lib/index.js +4 -1
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/packaging/build-args.js +2 -2
- package/dist/lib/packaging/build-args.js.map +1 -1
- package/dist/lib/packaging/container.js +5 -5
- package/dist/lib/packaging/container.js.map +1 -1
- package/dist/lib/packaging/helpers.d.ts +16 -0
- package/dist/lib/packaging/helpers.d.ts.map +1 -1
- package/dist/lib/packaging/helpers.js +127 -29
- package/dist/lib/packaging/helpers.js.map +1 -1
- package/dist/lib/packaging/index.d.ts +0 -1
- package/dist/lib/packaging/index.d.ts.map +1 -1
- package/dist/lib/packaging/index.js +4 -19
- package/dist/lib/packaging/index.js.map +1 -1
- package/dist/lib/packaging/node.d.ts +2 -2
- package/dist/lib/packaging/node.d.ts.map +1 -1
- package/dist/lib/packaging/node.js +83 -38
- package/dist/lib/packaging/node.js.map +1 -1
- package/dist/lib/packaging/python.js +12 -12
- package/dist/lib/packaging/python.js.map +1 -1
- package/dist/lib/result.d.ts +50 -0
- package/dist/lib/result.d.ts.map +1 -0
- package/dist/lib/result.js +49 -0
- package/dist/lib/result.js.map +1 -0
- package/dist/lib/schemas/io/config-io.d.ts +8 -0
- package/dist/lib/schemas/io/config-io.d.ts.map +1 -1
- package/dist/lib/schemas/io/config-io.js +21 -3
- package/dist/lib/schemas/io/config-io.js.map +1 -1
- package/dist/lib/schemas/io/global-config.d.ts +40 -0
- package/dist/lib/schemas/io/global-config.d.ts.map +1 -0
- package/dist/lib/schemas/io/global-config.js +118 -0
- package/dist/lib/schemas/io/global-config.js.map +1 -0
- package/dist/lib/schemas/io/index.d.ts +1 -2
- package/dist/lib/schemas/io/index.d.ts.map +1 -1
- package/dist/lib/schemas/io/index.js +1 -4
- package/dist/lib/schemas/io/index.js.map +1 -1
- package/dist/lib/schemas/io/path-resolver.d.ts +0 -6
- package/dist/lib/schemas/io/path-resolver.d.ts.map +1 -1
- package/dist/lib/schemas/io/path-resolver.js +3 -13
- package/dist/lib/schemas/io/path-resolver.js.map +1 -1
- package/dist/lib/secrets/cipher.d.ts +12 -0
- package/dist/lib/secrets/cipher.d.ts.map +1 -0
- package/dist/lib/secrets/cipher.js +54 -0
- package/dist/lib/secrets/cipher.js.map +1 -0
- package/dist/lib/secrets/index.d.ts +4 -0
- package/dist/lib/secrets/index.d.ts.map +1 -0
- package/dist/lib/secrets/index.js +15 -0
- package/dist/lib/secrets/index.js.map +1 -0
- package/dist/lib/secrets/key-provider.d.ts +16 -0
- package/dist/lib/secrets/key-provider.d.ts.map +1 -0
- package/dist/lib/secrets/key-provider.js +191 -0
- package/dist/lib/secrets/key-provider.js.map +1 -0
- package/dist/lib/secrets/sensitive-keys.d.ts +21 -0
- package/dist/lib/secrets/sensitive-keys.d.ts.map +1 -0
- package/dist/lib/secrets/sensitive-keys.js +67 -0
- package/dist/lib/secrets/sensitive-keys.js.map +1 -0
- package/dist/lib/time-constants.d.ts +5 -0
- package/dist/lib/time-constants.d.ts.map +1 -0
- package/dist/lib/time-constants.js +8 -0
- package/dist/lib/time-constants.js.map +1 -0
- package/dist/lib/utils/env.d.ts +8 -2
- package/dist/lib/utils/env.d.ts.map +1 -1
- package/dist/lib/utils/env.js +65 -17
- package/dist/lib/utils/env.js.map +1 -1
- package/dist/lib/utils/index.d.ts +3 -2
- package/dist/lib/utils/index.d.ts.map +1 -1
- package/dist/lib/utils/index.js +6 -1
- package/dist/lib/utils/index.js.map +1 -1
- package/dist/lib/utils/polling.d.ts +31 -0
- package/dist/lib/utils/polling.d.ts.map +1 -0
- package/dist/lib/utils/polling.js +61 -0
- package/dist/lib/utils/polling.js.map +1 -0
- package/dist/lib/utils/zod.d.ts +16 -0
- package/dist/lib/utils/zod.d.ts.map +1 -1
- package/dist/lib/utils/zod.js +45 -0
- package/dist/lib/utils/zod.js.map +1 -1
- package/dist/schema/constants.d.ts +56 -2
- package/dist/schema/constants.d.ts.map +1 -1
- package/dist/schema/constants.js +82 -7
- package/dist/schema/constants.js.map +1 -1
- package/dist/schema/schemas/agent-env.d.ts +156 -6
- package/dist/schema/schemas/agent-env.d.ts.map +1 -1
- package/dist/schema/schemas/agent-env.js +186 -13
- package/dist/schema/schemas/agent-env.js.map +1 -1
- package/dist/schema/schemas/agentcore-project.d.ts +446 -11
- package/dist/schema/schemas/agentcore-project.d.ts.map +1 -1
- package/dist/schema/schemas/agentcore-project.js +283 -18
- package/dist/schema/schemas/agentcore-project.js.map +1 -1
- package/dist/schema/schemas/auth.d.ts +174 -0
- package/dist/schema/schemas/auth.d.ts.map +1 -1
- package/dist/schema/schemas/auth.js +127 -3
- package/dist/schema/schemas/auth.js.map +1 -1
- package/dist/schema/schemas/connections.d.ts +185 -0
- package/dist/schema/schemas/connections.d.ts.map +1 -0
- package/dist/schema/schemas/connections.js +176 -0
- package/dist/schema/schemas/connections.js.map +1 -0
- package/dist/schema/schemas/deployed-state.d.ts +361 -5
- package/dist/schema/schemas/deployed-state.d.ts.map +1 -1
- package/dist/schema/schemas/deployed-state.js +105 -2
- package/dist/schema/schemas/deployed-state.js.map +1 -1
- package/dist/schema/schemas/index.d.ts +1 -0
- package/dist/schema/schemas/index.d.ts.map +1 -1
- package/dist/schema/schemas/index.js +1 -0
- package/dist/schema/schemas/index.js.map +1 -1
- package/dist/schema/schemas/mcp-defs.d.ts +2 -1
- package/dist/schema/schemas/mcp-defs.d.ts.map +1 -1
- package/dist/schema/schemas/mcp-defs.js +3 -2
- package/dist/schema/schemas/mcp-defs.js.map +1 -1
- package/dist/schema/schemas/mcp.d.ts +197 -0
- package/dist/schema/schemas/mcp.d.ts.map +1 -1
- package/dist/schema/schemas/mcp.js +342 -6
- package/dist/schema/schemas/mcp.js.map +1 -1
- package/dist/schema/schemas/primitives/ab-test.d.ts +135 -0
- package/dist/schema/schemas/primitives/ab-test.d.ts.map +1 -0
- package/dist/schema/schemas/primitives/ab-test.js +95 -0
- package/dist/schema/schemas/primitives/ab-test.js.map +1 -0
- package/dist/schema/schemas/primitives/config-bundle.d.ts +32 -0
- package/dist/schema/schemas/primitives/config-bundle.d.ts.map +1 -0
- package/dist/schema/schemas/primitives/config-bundle.js +41 -0
- package/dist/schema/schemas/primitives/config-bundle.js.map +1 -0
- package/dist/schema/schemas/primitives/dataset.d.ts +48 -0
- package/dist/schema/schemas/primitives/dataset.d.ts.map +1 -0
- package/dist/schema/schemas/primitives/dataset.js +58 -0
- package/dist/schema/schemas/primitives/dataset.js.map +1 -0
- package/dist/schema/schemas/primitives/evaluator.d.ts +8 -0
- package/dist/schema/schemas/primitives/evaluator.d.ts.map +1 -1
- package/dist/schema/schemas/primitives/evaluator.js +17 -1
- package/dist/schema/schemas/primitives/evaluator.js.map +1 -1
- package/dist/schema/schemas/primitives/harness.d.ts +377 -19
- package/dist/schema/schemas/primitives/harness.d.ts.map +1 -1
- package/dist/schema/schemas/primitives/harness.js +379 -24
- package/dist/schema/schemas/primitives/harness.js.map +1 -1
- package/dist/schema/schemas/primitives/index.d.ts +13 -7
- package/dist/schema/schemas/primitives/index.d.ts.map +1 -1
- package/dist/schema/schemas/primitives/index.js +37 -1
- package/dist/schema/schemas/primitives/index.js.map +1 -1
- package/dist/schema/schemas/primitives/knowledge-base.d.ts +104 -0
- package/dist/schema/schemas/primitives/knowledge-base.d.ts.map +1 -0
- package/dist/schema/schemas/primitives/knowledge-base.js +99 -0
- package/dist/schema/schemas/primitives/knowledge-base.js.map +1 -0
- package/dist/schema/schemas/primitives/memory.d.ts +22 -4
- package/dist/schema/schemas/primitives/memory.d.ts.map +1 -1
- package/dist/schema/schemas/primitives/memory.js +57 -16
- package/dist/schema/schemas/primitives/memory.js.map +1 -1
- package/dist/schema/schemas/primitives/online-eval-config.d.ts +21 -2
- package/dist/schema/schemas/primitives/online-eval-config.d.ts.map +1 -1
- package/dist/schema/schemas/primitives/online-eval-config.js +45 -5
- package/dist/schema/schemas/primitives/online-eval-config.js.map +1 -1
- package/dist/schema/schemas/primitives/payment.d.ts +54 -0
- package/dist/schema/schemas/primitives/payment.d.ts.map +1 -0
- package/dist/schema/schemas/primitives/payment.js +79 -0
- package/dist/schema/schemas/primitives/payment.js.map +1 -0
- package/dist/schema/schemas/primitives/policy.d.ts +26 -0
- package/dist/schema/schemas/primitives/policy.d.ts.map +1 -1
- package/dist/schema/schemas/primitives/policy.js +5 -1
- package/dist/schema/schemas/primitives/policy.js.map +1 -1
- package/npm-shrinkwrap.json +17013 -0
- package/package.json +43 -21
- package/scripts/bump-version.ts +4 -4
- package/scripts/bundle.mjs +70 -41
- package/scripts/run-e2e-dev.sh +56 -0
- package/scripts/run-e2e-local.sh +145 -0
- package/dist/lib/errors/config.d.ts +0 -49
- package/dist/lib/errors/config.d.ts.map +0 -1
- package/dist/lib/errors/config.js.map +0 -1
- package/dist/lib/packaging/errors.d.ts +0 -16
- package/dist/lib/packaging/errors.d.ts.map +0 -1
- package/dist/lib/packaging/errors.js +0 -36
- package/dist/lib/packaging/errors.js.map +0 -1
- package/dist/lib/schemas/io/cli-config.d.ts +0 -12
- package/dist/lib/schemas/io/cli-config.d.ts.map +0 -1
- package/dist/lib/schemas/io/cli-config.js +0 -35
- package/dist/lib/schemas/io/cli-config.js.map +0 -1
|
@@ -18,7 +18,10 @@ from bedrock_agentcore.identity import requires_access_token
|
|
|
18
18
|
@requires_access_token(
|
|
19
19
|
provider_name="{{credentialProviderName}}",
|
|
20
20
|
scopes=[{{#if scopes}}"{{scopes}}"{{/if}}],
|
|
21
|
-
auth_flow="M2M",
|
|
21
|
+
auth_flow="{{#if authFlow}}{{authFlow}}{{else}}M2M{{/if}}",
|
|
22
|
+
{{#if customParameters}}
|
|
23
|
+
custom_parameters={{safeJson customParameters}},
|
|
24
|
+
{{/if}}
|
|
22
25
|
)
|
|
23
26
|
def _get_bearer_token_{{snakeCase name}}(*, access_token: str):
|
|
24
27
|
"""Obtain OAuth access token via AgentCore Identity for {{name}}."""
|
|
@@ -29,18 +32,22 @@ def _get_bearer_token_{{snakeCase name}}(*, access_token: str):
|
|
|
29
32
|
{{#each gatewayProviders}}
|
|
30
33
|
def get_{{snakeCase name}}_mcp_client() -> MCPClient | None:
|
|
31
34
|
"""Returns an MCP Client connected to the {{name}} gateway."""
|
|
35
|
+
{{#if hardcodedUrl}}
|
|
36
|
+
url = {{safeJson hardcodedUrl}}
|
|
37
|
+
{{else}}
|
|
32
38
|
url = os.environ.get("{{envVarName}}")
|
|
33
39
|
if not url:
|
|
34
40
|
logger.warning("{{envVarName}} not set — {{name}} gateway tools unavailable")
|
|
35
41
|
return None
|
|
42
|
+
{{/if}}
|
|
36
43
|
{{#if (eq authType "AWS_IAM")}}
|
|
37
|
-
return MCPClient(lambda: aws_iam_streamablehttp_client(url, aws_service="bedrock-agentcore", aws_region=os.environ.get("AWS_REGION", os.environ.get("AWS_DEFAULT_REGION"))))
|
|
44
|
+
return MCPClient(lambda: aws_iam_streamablehttp_client(url, aws_service="bedrock-agentcore", aws_region=os.environ.get("AWS_REGION", os.environ.get("AWS_DEFAULT_REGION"))), prefix="{{snakeCase name}}")
|
|
38
45
|
{{else if (eq authType "CUSTOM_JWT")}}
|
|
39
46
|
token = _get_bearer_token_{{snakeCase name}}()
|
|
40
47
|
headers = {"Authorization": f"Bearer {token}"} if token else {}
|
|
41
|
-
return MCPClient(lambda: streamablehttp_client(url, headers=headers))
|
|
48
|
+
return MCPClient(lambda: streamablehttp_client(url, headers=headers), prefix="{{snakeCase name}}")
|
|
42
49
|
{{else}}
|
|
43
|
-
return MCPClient(lambda: streamablehttp_client(url))
|
|
50
|
+
return MCPClient(lambda: streamablehttp_client(url), prefix="{{snakeCase name}}")
|
|
44
51
|
{{/if}}
|
|
45
52
|
|
|
46
53
|
{{/each}}
|
|
@@ -53,7 +60,41 @@ def get_all_gateway_mcp_clients() -> list[MCPClient]:
|
|
|
53
60
|
clients.append(client)
|
|
54
61
|
{{/each}}
|
|
55
62
|
return clients
|
|
56
|
-
{{
|
|
63
|
+
{{/if}}
|
|
64
|
+
{{#if remoteMcpTools}}
|
|
65
|
+
{{#if (some remoteMcpTools "headerCredentials")}}
|
|
66
|
+
from bedrock_agentcore.identity.auth import requires_api_key
|
|
67
|
+
{{/if}}
|
|
68
|
+
{{#each remoteMcpTools}}
|
|
69
|
+
{{#if headerCredentials}}
|
|
70
|
+
{{#each headerCredentials}}
|
|
71
|
+
@requires_api_key(provider_name="{{credentialName}}")
|
|
72
|
+
def _get_{{snakeCase ../name}}_{{snakeCase headerKey}}_key(api_key: str) -> str:
|
|
73
|
+
"""Fetch {{headerKey}} credential for {{../name}} from AgentCore Identity."""
|
|
74
|
+
return api_key
|
|
75
|
+
|
|
76
|
+
{{/each}}
|
|
77
|
+
{{/if}}
|
|
78
|
+
def get_{{snakeCase name}}_mcp_client() -> MCPClient | None:
|
|
79
|
+
"""Returns an MCP Client for the {{name}} remote MCP server."""
|
|
80
|
+
url = {{safeJson url}}
|
|
81
|
+
{{#if headerCredentials}}
|
|
82
|
+
if os.getenv("LOCAL_DEV") == "1":
|
|
83
|
+
headers = { {{#each headerCredentials}}{{safeJson headerKey}}: os.environ.get("{{envVarName}}", ""){{#unless @last}}, {{/unless}}{{/each}} }
|
|
84
|
+
else:
|
|
85
|
+
headers = { {{#each headerCredentials}}{{safeJson headerKey}}: _get_{{snakeCase ../name}}_{{snakeCase headerKey}}_key(){{#unless @last}}, {{/unless}}{{/each}} }
|
|
86
|
+
return MCPClient(lambda: streamablehttp_client(url, headers=headers))
|
|
87
|
+
{{else}}
|
|
88
|
+
return MCPClient(lambda: streamablehttp_client(url))
|
|
89
|
+
{{/if}}
|
|
90
|
+
|
|
91
|
+
{{/each}}
|
|
92
|
+
def get_all_remote_mcp_clients() -> list[MCPClient]:
|
|
93
|
+
"""Returns all configured remote MCP clients."""
|
|
94
|
+
clients = [{{#each remoteMcpTools}}get_{{snakeCase name}}_mcp_client(){{#unless @last}}, {{/unless}}{{/each}}]
|
|
95
|
+
return [c for c in clients if c is not None]
|
|
96
|
+
{{/if}}
|
|
97
|
+
{{#unless (or hasGateway remoteMcpTools)}}
|
|
57
98
|
{{#if isVpc}}
|
|
58
99
|
# VPC mode: external MCP endpoints are not reachable without a NAT gateway.
|
|
59
100
|
# Add an AgentCore Gateway with `agentcore add gateway`, or configure your own endpoint below.
|
|
@@ -62,6 +103,7 @@ def get_streamable_http_mcp_client() -> MCPClient | None:
|
|
|
62
103
|
"""No MCP server configured. Add a gateway with `agentcore add gateway`."""
|
|
63
104
|
return None
|
|
64
105
|
{{else}}
|
|
106
|
+
{{#unless isExportHarness}}
|
|
65
107
|
# ExaAI provides information about code through web searches, crawling and code context searches through their platform. Requires no authentication
|
|
66
108
|
EXAMPLE_MCP_ENDPOINT = "https://mcp.exa.ai/mcp"
|
|
67
109
|
|
|
@@ -69,5 +111,6 @@ def get_streamable_http_mcp_client() -> MCPClient:
|
|
|
69
111
|
"""Returns an MCP Client compatible with Strands"""
|
|
70
112
|
# to use an MCP server that supports bearer authentication, add headers={"Authorization": f"Bearer {access_token}"}
|
|
71
113
|
return MCPClient(lambda: streamablehttp_client(EXAMPLE_MCP_ENDPOINT))
|
|
114
|
+
{{/unless}}
|
|
72
115
|
{{/if}}
|
|
73
|
-
{{/
|
|
116
|
+
{{/unless}}
|
|
@@ -1,10 +1,72 @@
|
|
|
1
1
|
{{#if (eq modelProvider "Bedrock")}}
|
|
2
|
+
{{#if bedrockMantle}}
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
from aws_bedrock_token_generator import provide_token
|
|
6
|
+
{{#if (eq mantleApiFormat "chat_completions")}}
|
|
7
|
+
from strands.models.openai import OpenAIModel
|
|
8
|
+
{{else}}
|
|
9
|
+
{{#if mantleProprietary}}
|
|
10
|
+
from strands.models.openai_responses import OpenAIResponsesModel
|
|
11
|
+
{{else}}
|
|
12
|
+
from model.mantle_compat import MantleCompatResponsesModel
|
|
13
|
+
{{/if}}
|
|
14
|
+
{{/if}}
|
|
15
|
+
|
|
16
|
+
MODEL_ID = "{{modelId}}"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def load_model():
|
|
20
|
+
"""
|
|
21
|
+
Get a Bedrock Mantle model client. These OpenAI-compatible models (e.g. openai.gpt-5.5,
|
|
22
|
+
openai.gpt-oss-120b) are served via the Bedrock Mantle endpoint, NOT the Converse API — so they
|
|
23
|
+
are invoked through an OpenAI-style client authenticated with a short-lived Bedrock bearer token.
|
|
24
|
+
Region is read from AWS_REGION (set by the AgentCore runtime).
|
|
25
|
+
"""
|
|
26
|
+
region = os.environ.get("AWS_REGION", os.environ.get("AWS_DEFAULT_REGION", "us-east-1"))
|
|
27
|
+
token = provide_token(region=region)
|
|
28
|
+
{{#if mantleProprietary}}
|
|
29
|
+
# Proprietary OpenAI models only work on the /openai/v1 Mantle path.
|
|
30
|
+
base_url = f"https://bedrock-mantle.{region}.api.aws/openai/v1"
|
|
31
|
+
{{else}}
|
|
32
|
+
# Open-source OpenAI models (gpt-oss-*) only work on the /v1 Mantle path.
|
|
33
|
+
base_url = f"https://bedrock-mantle.{region}.api.aws/v1"
|
|
34
|
+
{{/if}}
|
|
35
|
+
client_args = {"api_key": token, "base_url": base_url}
|
|
36
|
+
|
|
37
|
+
params = {}
|
|
38
|
+
{{#if modelMaxTokens}}
|
|
39
|
+
{{#if (eq mantleApiFormat "chat_completions")}}
|
|
40
|
+
params["max_completion_tokens"] = {{modelMaxTokens}}
|
|
41
|
+
{{else}}
|
|
42
|
+
params["max_output_tokens"] = {{modelMaxTokens}}
|
|
43
|
+
{{/if}}
|
|
44
|
+
{{/if}}
|
|
45
|
+
{{#if modelTemperature}}
|
|
46
|
+
params["temperature"] = {{modelTemperature}}
|
|
47
|
+
{{/if}}
|
|
48
|
+
{{#if modelTopP}}
|
|
49
|
+
params["top_p"] = {{modelTopP}}
|
|
50
|
+
{{/if}}
|
|
51
|
+
{{#if (eq mantleApiFormat "chat_completions")}}
|
|
52
|
+
return OpenAIModel(client_args=client_args, model_id=MODEL_ID, params=params)
|
|
53
|
+
{{else}}
|
|
54
|
+
# Responses API: Mantle does not persist responses, so disable server-side storage.
|
|
55
|
+
params["store"] = False
|
|
56
|
+
{{#if mantleProprietary}}
|
|
57
|
+
return OpenAIResponsesModel(client_args=client_args, model_id=MODEL_ID, params=params)
|
|
58
|
+
{{else}}
|
|
59
|
+
return MantleCompatResponsesModel(client_args=client_args, model_id=MODEL_ID, params=params)
|
|
60
|
+
{{/if}}
|
|
61
|
+
{{/if}}
|
|
62
|
+
{{else}}
|
|
2
63
|
from strands.models.bedrock import BedrockModel
|
|
3
64
|
|
|
4
65
|
|
|
5
66
|
def load_model() -> BedrockModel:
|
|
6
67
|
"""Get Bedrock model client using IAM credentials."""
|
|
7
|
-
return BedrockModel(model_id="global.anthropic.claude-sonnet-4-5-20250929-v1:0")
|
|
68
|
+
return BedrockModel(model_id="{{#if modelId}}{{modelId}}{{else}}global.anthropic.claude-sonnet-4-5-20250929-v1:0{{/if}}")
|
|
69
|
+
{{/if}}
|
|
8
70
|
{{/if}}
|
|
9
71
|
{{#if (eq modelProvider "Anthropic")}}
|
|
10
72
|
import os
|
|
@@ -80,7 +142,7 @@ def load_model() -> OpenAIModel:
|
|
|
80
142
|
"""Get authenticated OpenAI model client."""
|
|
81
143
|
return OpenAIModel(
|
|
82
144
|
client_args={"api_key": _get_api_key()},
|
|
83
|
-
model_id="gpt-4.1",
|
|
145
|
+
model_id="{{#if modelId}}{{modelId}}{{else}}gpt-4.1{{/if}}",
|
|
84
146
|
)
|
|
85
147
|
{{/if}}
|
|
86
148
|
{{#if (eq modelProvider "Gemini")}}
|
|
@@ -118,6 +180,60 @@ def load_model() -> GeminiModel:
|
|
|
118
180
|
"""Get authenticated Gemini model client."""
|
|
119
181
|
return GeminiModel(
|
|
120
182
|
client_args={"api_key": _get_api_key()},
|
|
121
|
-
model_id="gemini-2.5-flash",
|
|
183
|
+
model_id="{{#if modelId}}{{modelId}}{{else}}gemini-2.5-flash{{/if}}",
|
|
184
|
+
)
|
|
185
|
+
{{/if}}
|
|
186
|
+
{{#if (eq modelProvider "LiteLLM")}}
|
|
187
|
+
import os
|
|
188
|
+
{{#if litellmAdditionalParams}}
|
|
189
|
+
import json
|
|
190
|
+
{{/if}}
|
|
191
|
+
|
|
192
|
+
from strands.models.litellm import LiteLLMModel
|
|
193
|
+
{{#if identityProviders.[0].name}}
|
|
194
|
+
from bedrock_agentcore.identity.auth import requires_api_key
|
|
195
|
+
|
|
196
|
+
IDENTITY_PROVIDER_NAME = "{{identityProviders.[0].name}}"
|
|
197
|
+
IDENTITY_ENV_VAR = "{{identityProviders.[0].envVarName}}"
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@requires_api_key(provider_name=IDENTITY_PROVIDER_NAME)
|
|
201
|
+
def _agentcore_identity_api_key_provider(api_key: str) -> str:
|
|
202
|
+
"""Fetch API key from AgentCore Identity."""
|
|
203
|
+
return api_key
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _get_api_key() -> str:
|
|
207
|
+
"""
|
|
208
|
+
Uses AgentCore Identity for API key management in deployed environments.
|
|
209
|
+
For local development, run via 'agentcore dev' which loads agentcore/.env.
|
|
210
|
+
"""
|
|
211
|
+
if os.getenv("LOCAL_DEV") == "1":
|
|
212
|
+
api_key = os.getenv(IDENTITY_ENV_VAR)
|
|
213
|
+
if not api_key:
|
|
214
|
+
raise RuntimeError(
|
|
215
|
+
f"{IDENTITY_ENV_VAR} not found. Add {IDENTITY_ENV_VAR}=your-key to .env.local"
|
|
216
|
+
)
|
|
217
|
+
return api_key
|
|
218
|
+
return _agentcore_identity_api_key_provider()
|
|
219
|
+
{{/if}}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def load_model() -> LiteLLMModel:
|
|
225
|
+
"""Get a LiteLLM model client (proxies to the provider encoded in model_id)."""
|
|
226
|
+
client_args = {}
|
|
227
|
+
{{#if identityProviders.[0].name}}
|
|
228
|
+
client_args["api_key"] = _get_api_key()
|
|
229
|
+
{{/if}}
|
|
230
|
+
{{#if litellmApiBase}}
|
|
231
|
+
client_args["api_base"] = {{safeJson litellmApiBase}}
|
|
232
|
+
{{/if}}
|
|
233
|
+
params = {{#if litellmAdditionalParams}}json.loads({{pyJsonStr litellmAdditionalParams}}){{else}}{}{{/if}}
|
|
234
|
+
return LiteLLMModel(
|
|
235
|
+
client_args=client_args,
|
|
236
|
+
model_id="{{#if modelId}}{{modelId}}{{else}}bedrock/us.anthropic.claude-sonnet-4-5-20250514-v1:0{{/if}}",
|
|
237
|
+
params=params,
|
|
122
238
|
)
|
|
123
239
|
{{/if}}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from strands.models.openai_responses import OpenAIResponsesModel
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class MantleCompatResponsesModel(OpenAIResponsesModel):
|
|
5
|
+
"""Workaround for Bedrock Mantle rejecting output_text in EasyInputMessage content arrays.
|
|
6
|
+
|
|
7
|
+
Mantle's Pydantic validation only accepts content as a plain string for assistant messages, while
|
|
8
|
+
real OpenAI accepts both formats. Flatten assistant content arrays to strings so multi-turn works.
|
|
9
|
+
Used for open-source OpenAI models (gpt-oss-*) on the /v1 Mantle path; proprietary models use the
|
|
10
|
+
plain OpenAIResponsesModel on /openai/v1.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
@classmethod
|
|
14
|
+
def _format_request_messages(cls, messages):
|
|
15
|
+
formatted = super()._format_request_messages(messages)
|
|
16
|
+
for msg in formatted:
|
|
17
|
+
if msg.get("role") == "assistant" and isinstance(msg.get("content"), list):
|
|
18
|
+
msg["content"] = "".join(
|
|
19
|
+
part.get("text", "") for part in msg["content"] if part.get("type") == "output_text"
|
|
20
|
+
)
|
|
21
|
+
return formatted
|
|
@@ -11,13 +11,19 @@ requires-python = ">=3.10"
|
|
|
11
11
|
dependencies = [
|
|
12
12
|
{{#if (eq modelProvider "Anthropic")}}"anthropic >= 0.30.0",
|
|
13
13
|
{{/if}}"aws-opentelemetry-distro",
|
|
14
|
-
"bedrock-agentcore >= 1.
|
|
14
|
+
"bedrock-agentcore >= 1.9.1",
|
|
15
15
|
"botocore[crt] >= 1.35.0",
|
|
16
16
|
{{#if (eq modelProvider "Gemini")}}"google-genai >= 1.0.0",
|
|
17
17
|
{{/if}}"mcp >= 1.19.0",
|
|
18
18
|
{{#if (eq modelProvider "OpenAI")}}"openai >= 1.0.0",
|
|
19
|
-
{{/if}}"
|
|
20
|
-
{{
|
|
19
|
+
{{/if}}{{#if (eq modelProvider "LiteLLM")}}"litellm >= 1.0.0",
|
|
20
|
+
{{/if}}{{#if bedrockMantle}}"openai >= 1.0.0",
|
|
21
|
+
"aws-bedrock-token-generator >= 1.0.0",
|
|
22
|
+
{{/if}}"strands-agents >= 1.15.0",
|
|
23
|
+
{{#if (or hasBrowser hasCodeInterpreter)}}"strands-agents-tools >= 0.1.0",
|
|
24
|
+
{{/if}}{{#if hasBrowser}}"nest-asyncio >= 1.5.0",
|
|
25
|
+
"playwright >= 1.42.0",
|
|
26
|
+
{{/if}}{{#if hasGateway}}{{#if (includes gatewayAuthTypes "AWS_IAM")}}"mcp-proxy-for-aws >= 1.1.0",
|
|
21
27
|
{{/if}}{{/if}}
|
|
22
28
|
]
|
|
23
29
|
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Skill fetcher — downloads s3/git skills to local filesystem on first use.
|
|
2
|
+
|
|
3
|
+
Resolved paths are passed to AgentSkills(skills=...) in main.py.
|
|
4
|
+
Cache directory: <tmpdir>/.agents/skills/ — an absolute path under the system temp
|
|
5
|
+
directory (honors $TMPDIR, defaults to /tmp). The runtime working directory (e.g.
|
|
6
|
+
/var/task in a CodeZip runtime) is read-only, so the cache must live somewhere
|
|
7
|
+
guaranteed-writable.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import tempfile
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Optional
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
_SKILLS_BASE = Path(tempfile.gettempdir()) / ".agents" / "skills"
|
|
24
|
+
_GIT_TIMEOUT = 60
|
|
25
|
+
_S3_MAX_SIZE_BYTES = 1 * 1024 * 1024 * 1024 # 1 GB
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _stable_hash(value: str) -> str:
|
|
29
|
+
return hashlib.sha256(value.encode()).hexdigest()[:12]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _cleanup(path: Path) -> None:
|
|
33
|
+
"""Remove a partially-created skill directory so retries don't see stale state."""
|
|
34
|
+
shutil.rmtree(path, ignore_errors=True)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _read_map(type_dir: Path) -> dict:
|
|
38
|
+
map_file = type_dir / ".map.json"
|
|
39
|
+
return json.loads(map_file.read_text()) if map_file.exists() else {}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _write_map(type_dir: Path, mapping: dict) -> None:
|
|
43
|
+
type_dir.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
(type_dir / ".map.json").write_text(json.dumps(mapping))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _resolve_cached(type_dir: Path, source_hash: str) -> Optional[str]:
|
|
48
|
+
"""Return the cached skill directory for a source hash, or None if not on disk."""
|
|
49
|
+
mapping = _read_map(type_dir)
|
|
50
|
+
dir_name = mapping.get(source_hash)
|
|
51
|
+
if dir_name and (type_dir / dir_name).exists():
|
|
52
|
+
return str(type_dir / dir_name)
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _read_skill_name(skill_dir: Path) -> str:
|
|
57
|
+
"""Extract the skill name from SKILL.md YAML frontmatter."""
|
|
58
|
+
content = (skill_dir / "SKILL.md").read_text()
|
|
59
|
+
if not content.startswith("---"):
|
|
60
|
+
raise ValueError(f"SKILL.md in {skill_dir} has no YAML frontmatter (must start with ---)")
|
|
61
|
+
parts = content.split("---", 2)
|
|
62
|
+
if len(parts) < 3:
|
|
63
|
+
raise ValueError(f"SKILL.md in {skill_dir} has malformed frontmatter (missing closing ---)")
|
|
64
|
+
for line in parts[1].strip().splitlines():
|
|
65
|
+
if line.startswith("name:"):
|
|
66
|
+
name = line[len("name:"):].strip().strip("\"'")
|
|
67
|
+
if name:
|
|
68
|
+
return name
|
|
69
|
+
raise ValueError(f"SKILL.md in {skill_dir} is missing a 'name' field in frontmatter")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _pick_dir_name(type_dir: Path, name: str, source_hash: str) -> str:
|
|
73
|
+
"""Pick a unique directory name, appending a hash suffix on collision."""
|
|
74
|
+
if not (type_dir / name).exists():
|
|
75
|
+
return name
|
|
76
|
+
return f"{name}-{source_hash[:8]}"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _rename_and_cache_skill(type_dir: Path, temp_dir: Path, source_hash: str, skill_root: Path,
|
|
80
|
+
source_label: str = "") -> Path:
|
|
81
|
+
"""Validate SKILL.md, rename the temp dir to the skill's declared name, and update the map.
|
|
82
|
+
|
|
83
|
+
Raises ValueError if SKILL.md is missing or has invalid frontmatter.
|
|
84
|
+
"""
|
|
85
|
+
if not (skill_root / "SKILL.md").exists():
|
|
86
|
+
_cleanup(temp_dir)
|
|
87
|
+
hint = f" (source: {source_label})" if source_label else ""
|
|
88
|
+
raise ValueError(f"No SKILL.md found in fetched skill{hint}")
|
|
89
|
+
|
|
90
|
+
name = _read_skill_name(skill_root)
|
|
91
|
+
dir_name = _pick_dir_name(type_dir, name, source_hash)
|
|
92
|
+
final_dir = type_dir / dir_name
|
|
93
|
+
if final_dir != temp_dir:
|
|
94
|
+
temp_dir.rename(final_dir)
|
|
95
|
+
|
|
96
|
+
mapping = _read_map(type_dir)
|
|
97
|
+
mapping[source_hash] = dir_name
|
|
98
|
+
_write_map(type_dir, mapping)
|
|
99
|
+
return final_dir
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _fetch_s3_skill(source: str, s3_client=None) -> Path:
|
|
103
|
+
"""Download an s3:// skill prefix and return the local directory."""
|
|
104
|
+
uri = source if source.endswith("/") else source + "/"
|
|
105
|
+
source_hash = _stable_hash(uri)
|
|
106
|
+
type_dir = _SKILLS_BASE / "s3"
|
|
107
|
+
|
|
108
|
+
cached = _resolve_cached(type_dir, source_hash)
|
|
109
|
+
if cached:
|
|
110
|
+
return Path(cached)
|
|
111
|
+
|
|
112
|
+
import boto3
|
|
113
|
+
client = s3_client or boto3.client("s3")
|
|
114
|
+
bucket, _, prefix = uri[len("s3://"):].partition("/")
|
|
115
|
+
if not bucket:
|
|
116
|
+
raise ValueError(f"Invalid S3 URI (no bucket): {uri}")
|
|
117
|
+
|
|
118
|
+
temp_dir = type_dir / source_hash
|
|
119
|
+
_cleanup(temp_dir)
|
|
120
|
+
temp_dir.mkdir(parents=True, exist_ok=True)
|
|
121
|
+
temp_root = temp_dir.resolve()
|
|
122
|
+
|
|
123
|
+
paginator = client.get_paginator("list_objects_v2")
|
|
124
|
+
total = 0
|
|
125
|
+
for page in paginator.paginate(Bucket=bucket, Prefix=prefix):
|
|
126
|
+
for obj in page.get("Contents", []):
|
|
127
|
+
total += obj["Size"]
|
|
128
|
+
if total > _S3_MAX_SIZE_BYTES:
|
|
129
|
+
_cleanup(temp_dir)
|
|
130
|
+
raise ValueError(f"S3 skill {uri} exceeds 1 GB size limit")
|
|
131
|
+
rel = obj["Key"][len(prefix):].lstrip("/")
|
|
132
|
+
if not rel:
|
|
133
|
+
continue
|
|
134
|
+
dest = (temp_dir / rel).resolve()
|
|
135
|
+
if dest != temp_root and not str(dest).startswith(str(temp_root) + os.sep):
|
|
136
|
+
_cleanup(temp_dir)
|
|
137
|
+
raise ValueError(f"Path traversal detected in S3 key: {obj['Key']}")
|
|
138
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
139
|
+
client.download_file(bucket, obj["Key"], str(dest))
|
|
140
|
+
|
|
141
|
+
if total == 0:
|
|
142
|
+
_cleanup(temp_dir)
|
|
143
|
+
raise ValueError(f"No files found at S3 URI: {uri}")
|
|
144
|
+
|
|
145
|
+
return _rename_and_cache_skill(type_dir, temp_dir, source_hash, temp_dir, source_label=uri)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _resolve_credential_arn(credential_arn: str, identity_client) -> str:
|
|
149
|
+
"""Resolve a Token Vault API-key credential ARN to its secret value via AgentCore Identity.
|
|
150
|
+
|
|
151
|
+
ARN format: arn:<p>:bedrock-agentcore:<region>:<account>:token-vault/<vault>/apikeycredentialprovider/<name>
|
|
152
|
+
"""
|
|
153
|
+
from bedrock_agentcore.runtime.context import BedrockAgentCoreContext # noqa: PLC0415
|
|
154
|
+
|
|
155
|
+
provider_name = credential_arn.rsplit("/", 1)[-1]
|
|
156
|
+
if not provider_name:
|
|
157
|
+
raise ValueError(f"Invalid credential ARN: {credential_arn}")
|
|
158
|
+
workload_token = BedrockAgentCoreContext.get_workload_access_token()
|
|
159
|
+
if not workload_token:
|
|
160
|
+
raise ValueError("Credential ARN resolution requires a workload access token")
|
|
161
|
+
api_key = identity_client.dp_client.get_resource_api_key(
|
|
162
|
+
resourceCredentialProviderName=provider_name,
|
|
163
|
+
workloadIdentityToken=workload_token,
|
|
164
|
+
)["apiKey"]
|
|
165
|
+
if not api_key:
|
|
166
|
+
raise ValueError(f"Identity returned empty API key for provider: {provider_name}")
|
|
167
|
+
return api_key
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _build_git_auth_env(credential_arn: Optional[str], username: Optional[str], identity_client=None) -> dict:
|
|
171
|
+
"""Build GIT_CONFIG_* env vars for HTTP Basic auth using a Token Vault credential ARN.
|
|
172
|
+
|
|
173
|
+
Uses env vars instead of -c args to avoid leaking credentials in /proc/*/cmdline,
|
|
174
|
+
and so auth propagates to sub-commands (e.g. sparse-checkout triggering a fetch).
|
|
175
|
+
"""
|
|
176
|
+
if not credential_arn or not identity_client:
|
|
177
|
+
return {}
|
|
178
|
+
password = _resolve_credential_arn(credential_arn, identity_client)
|
|
179
|
+
user = username or "oauth2"
|
|
180
|
+
encoded = base64.b64encode(f"{user}:{password}".encode()).decode()
|
|
181
|
+
return {
|
|
182
|
+
"GIT_CONFIG_COUNT": "1",
|
|
183
|
+
"GIT_CONFIG_KEY_0": "http.extraHeader",
|
|
184
|
+
"GIT_CONFIG_VALUE_0": f"Authorization: Basic {encoded}",
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _fetch_git_skill(url: str, skill_path: str = "", credential_arn: Optional[str] = None,
|
|
189
|
+
username: Optional[str] = None, identity_client=None) -> Path:
|
|
190
|
+
"""Shallow-clone a git skill repository and return the local skill directory.
|
|
191
|
+
|
|
192
|
+
Returns the directory containing SKILL.md (the subdir itself for sparse checkouts).
|
|
193
|
+
"""
|
|
194
|
+
if skill_path and (os.path.isabs(skill_path) or ".." in Path(skill_path).parts):
|
|
195
|
+
raise ValueError(f"Path traversal detected in skill path: {skill_path}")
|
|
196
|
+
|
|
197
|
+
source_hash = _stable_hash(f"{url}:{skill_path}")
|
|
198
|
+
type_dir = _SKILLS_BASE / "git"
|
|
199
|
+
|
|
200
|
+
cached = _resolve_cached(type_dir, source_hash)
|
|
201
|
+
if cached:
|
|
202
|
+
return Path(cached) / skill_path if skill_path else Path(cached)
|
|
203
|
+
|
|
204
|
+
temp_dir = type_dir / source_hash
|
|
205
|
+
_cleanup(temp_dir)
|
|
206
|
+
temp_dir.mkdir(parents=True, exist_ok=True)
|
|
207
|
+
|
|
208
|
+
extra_env = _build_git_auth_env(credential_arn, username, identity_client)
|
|
209
|
+
git_env = {**os.environ, **extra_env} if extra_env else None
|
|
210
|
+
|
|
211
|
+
try:
|
|
212
|
+
if skill_path:
|
|
213
|
+
subprocess.run(
|
|
214
|
+
["git", "clone", "--depth", "1", "--filter=blob:none", "--sparse", url, str(temp_dir)],
|
|
215
|
+
check=True, timeout=_GIT_TIMEOUT, capture_output=True, env=git_env,
|
|
216
|
+
)
|
|
217
|
+
subprocess.run(
|
|
218
|
+
["git", "sparse-checkout", "set", skill_path],
|
|
219
|
+
check=True, timeout=_GIT_TIMEOUT, capture_output=True, cwd=str(temp_dir), env=git_env,
|
|
220
|
+
)
|
|
221
|
+
else:
|
|
222
|
+
subprocess.run(
|
|
223
|
+
["git", "clone", "--depth", "1", url, str(temp_dir)],
|
|
224
|
+
check=True, timeout=_GIT_TIMEOUT, capture_output=True, env=git_env,
|
|
225
|
+
)
|
|
226
|
+
except Exception:
|
|
227
|
+
_cleanup(temp_dir)
|
|
228
|
+
raise
|
|
229
|
+
|
|
230
|
+
if skill_path and not (temp_dir / skill_path).exists():
|
|
231
|
+
_cleanup(temp_dir)
|
|
232
|
+
raise ValueError(f"Skill path '{skill_path}' not found in repository '{url}'")
|
|
233
|
+
|
|
234
|
+
# SKILL.md lives inside the subdir for sparse checkouts.
|
|
235
|
+
skill_root = temp_dir / skill_path if skill_path else temp_dir
|
|
236
|
+
label = f"{url}:{skill_path}" if skill_path else url
|
|
237
|
+
final_dir = _rename_and_cache_skill(type_dir, temp_dir, source_hash, skill_root, source_label=label)
|
|
238
|
+
return final_dir / skill_path if skill_path else final_dir
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def resolve_s3_skills(sources: list, s3_client=None) -> list:
|
|
242
|
+
"""Resolve s3:// skill URIs to local filesystem paths.
|
|
243
|
+
|
|
244
|
+
Any fetch failure raises and fails the invocation — a partial skill set
|
|
245
|
+
would silently run the agent without capabilities the harness declared.
|
|
246
|
+
"""
|
|
247
|
+
paths = []
|
|
248
|
+
for uri in sources:
|
|
249
|
+
try:
|
|
250
|
+
skill_dir = _fetch_s3_skill(uri, s3_client)
|
|
251
|
+
except Exception as e:
|
|
252
|
+
raise ValueError(f"Failed to resolve S3 skill '{uri}': {e}") from e
|
|
253
|
+
paths.append(str(skill_dir.resolve()))
|
|
254
|
+
return paths
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def resolve_git_skills(sources: list, identity_client=None) -> list:
|
|
258
|
+
"""Resolve git skill dicts to local filesystem paths.
|
|
259
|
+
|
|
260
|
+
Each source is a dict with keys: url (required), path (optional),
|
|
261
|
+
credentialArn (optional), username (optional).
|
|
262
|
+
|
|
263
|
+
Any fetch failure raises and fails the invocation — a partial skill set
|
|
264
|
+
would silently run the agent without capabilities the harness declared.
|
|
265
|
+
"""
|
|
266
|
+
paths = []
|
|
267
|
+
for source in sources:
|
|
268
|
+
try:
|
|
269
|
+
skill_dir = _fetch_git_skill(
|
|
270
|
+
url=source["url"],
|
|
271
|
+
skill_path=source.get("path") or "",
|
|
272
|
+
credential_arn=source.get("credentialArn"),
|
|
273
|
+
username=source.get("username"),
|
|
274
|
+
identity_client=identity_client,
|
|
275
|
+
)
|
|
276
|
+
except Exception as e:
|
|
277
|
+
raise ValueError(f"Failed to resolve git skill '{source.get('url', source)}': {e}") from e
|
|
278
|
+
paths.append(str(skill_dir.resolve()))
|
|
279
|
+
return paths
|
package/dist/assets/python/http/strands/capabilities/execution-limits/hooks/execution_limits.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
from strands.hooks import BeforeModelCallEvent
|
|
5
|
+
from strands.hooks.registry import HookProvider, HookRegistry
|
|
6
|
+
from strands.types.exceptions import EventLoopException
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ExecutionLimitExceeded(Exception):
|
|
10
|
+
def __init__(self, message: str) -> None:
|
|
11
|
+
super().__init__(message)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ExecutionLimitsHook(HookProvider):
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
max_iterations: Optional[int] = None,
|
|
18
|
+
max_tokens: Optional[int] = None,
|
|
19
|
+
timeout_seconds: Optional[float] = None,
|
|
20
|
+
) -> None:
|
|
21
|
+
self._max_iterations = max_iterations
|
|
22
|
+
self._max_tokens = max_tokens
|
|
23
|
+
self._timeout_seconds = timeout_seconds
|
|
24
|
+
self._iteration_count = 0
|
|
25
|
+
self._start_time = time.monotonic()
|
|
26
|
+
|
|
27
|
+
def register_hooks(self, registry: HookRegistry, **kwargs) -> None:
|
|
28
|
+
registry.add_callback(BeforeModelCallEvent, self._check_limits)
|
|
29
|
+
|
|
30
|
+
def _check_limits(self, event: BeforeModelCallEvent) -> None:
|
|
31
|
+
self._iteration_count += 1
|
|
32
|
+
|
|
33
|
+
if self._max_iterations is not None and self._iteration_count > self._max_iterations:
|
|
34
|
+
raise EventLoopException(
|
|
35
|
+
ExecutionLimitExceeded(f"Max iterations exceeded: {self._max_iterations}")
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
if self._timeout_seconds is not None:
|
|
39
|
+
elapsed = time.monotonic() - self._start_time
|
|
40
|
+
if elapsed > self._timeout_seconds:
|
|
41
|
+
raise EventLoopException(
|
|
42
|
+
ExecutionLimitExceeded(
|
|
43
|
+
f"Timeout exceeded: {self._timeout_seconds}s (elapsed {elapsed:.1f}s)"
|
|
44
|
+
)
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
if self._max_tokens is not None:
|
|
48
|
+
used = event.agent.event_loop_metrics.accumulated_usage.get("outputTokens", 0)
|
|
49
|
+
if used >= self._max_tokens:
|
|
50
|
+
raise EventLoopException(
|
|
51
|
+
ExecutionLimitExceeded(
|
|
52
|
+
f"Max output tokens exceeded: {used}/{self._max_tokens}"
|
|
53
|
+
)
|
|
54
|
+
)
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import os
|
|
2
|
+
import uuid
|
|
2
3
|
from typing import Optional
|
|
3
4
|
|
|
4
5
|
from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig{{#if memoryProviders.[0].strategies.length}}, RetrievalConfig{{/if}}
|
|
@@ -7,10 +8,14 @@ from bedrock_agentcore.memory.integrations.strands.session_manager import AgentC
|
|
|
7
8
|
MEMORY_ID = os.getenv("{{memoryProviders.[0].envVarName}}")
|
|
8
9
|
REGION = os.getenv("AWS_REGION")
|
|
9
10
|
|
|
10
|
-
def get_memory_session_manager(session_id: str, actor_id: str) -> Optional[AgentCoreMemorySessionManager]:
|
|
11
|
+
def get_memory_session_manager(session_id: Optional[str], actor_id: str) -> Optional[AgentCoreMemorySessionManager]:
|
|
11
12
|
if not MEMORY_ID:
|
|
12
13
|
return None
|
|
13
14
|
|
|
15
|
+
# AgentCoreMemoryConfig rejects None; OAuth/CUSTOM_JWT callers can reach us
|
|
16
|
+
# without a runtime session header, so synthesize one when absent.
|
|
17
|
+
session_id = session_id or uuid.uuid4().hex
|
|
18
|
+
|
|
14
19
|
{{#if memoryProviders.[0].strategies.length}}
|
|
15
20
|
retrieval_config = {
|
|
16
21
|
{{#if (includes memoryProviders.[0].strategies "SEMANTIC")}}
|
|
@@ -19,8 +24,11 @@ def get_memory_session_manager(session_id: str, actor_id: str) -> Optional[Agent
|
|
|
19
24
|
{{#if (includes memoryProviders.[0].strategies "USER_PREFERENCE")}}
|
|
20
25
|
f"/users/{actor_id}/preferences": RetrievalConfig(top_k=3, relevance_score=0.5),
|
|
21
26
|
{{/if}}
|
|
27
|
+
{{#if (includes memoryProviders.[0].strategies "EPISODIC")}}
|
|
28
|
+
f"/episodes/{actor_id}/{session_id}": RetrievalConfig(top_k=5, relevance_score=0.5),
|
|
29
|
+
{{/if}}
|
|
22
30
|
{{#if (includes memoryProviders.[0].strategies "SUMMARIZATION")}}
|
|
23
|
-
f"/summaries/{actor_id}
|
|
31
|
+
f"/summaries/{actor_id}": RetrievalConfig(top_k=3, relevance_score=0.5),
|
|
24
32
|
{{/if}}
|
|
25
33
|
}
|
|
26
34
|
{{/if}}
|