@aws/agentcore 1.0.0-preview.2 → 1.0.0-preview.21
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 +1443 -569
- package/dist/lib/constants.d.ts +8 -4
- package/dist/lib/constants.d.ts.map +1 -1
- package/dist/lib/constants.js +13 -7
- package/dist/lib/constants.js.map +1 -1
- 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.d.ts +6 -0
- package/dist/lib/packaging/build-args.d.ts.map +1 -1
- package/dist/lib/packaging/build-args.js +11 -2
- package/dist/lib/packaging/build-args.js.map +1 -1
- package/dist/lib/packaging/build-context-dockerignore.d.ts +23 -0
- package/dist/lib/packaging/build-context-dockerignore.d.ts.map +1 -0
- package/dist/lib/packaging/build-context-dockerignore.js +63 -0
- package/dist/lib/packaging/build-context-dockerignore.js.map +1 -0
- package/dist/lib/packaging/build-context.d.ts +21 -0
- package/dist/lib/packaging/build-context.d.ts.map +1 -0
- package/dist/lib/packaging/build-context.js +21 -0
- package/dist/lib/packaging/build-context.js.map +1 -0
- package/dist/lib/packaging/container.d.ts.map +1 -1
- package/dist/lib/packaging/container.js +20 -9
- 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 +2 -1
- package/dist/lib/packaging/index.d.ts.map +1 -1
- package/dist/lib/packaging/index.js +9 -20
- 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 +178 -6
- package/dist/schema/schemas/agent-env.d.ts.map +1 -1
- package/dist/schema/schemas/agent-env.js +302 -27
- package/dist/schema/schemas/agent-env.js.map +1 -1
- package/dist/schema/schemas/agentcore-project.d.ts +450 -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/aws-targets.d.ts +12 -0
- package/dist/schema/schemas/aws-targets.d.ts.map +1 -1
- package/dist/schema/schemas/aws-targets.js +4 -0
- package/dist/schema/schemas/aws-targets.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 +199 -0
- package/dist/schema/schemas/mcp.d.ts.map +1 -1
- package/dist/schema/schemas/mcp.js +343 -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/extract-cli-model.mjs +228 -0
- package/scripts/render_adoc.py +274 -0
- 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
|
@@ -1,51 +1,290 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
from collections import OrderedDict
|
|
3
|
+
{{#if inlineFunctionTools}}
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
from strands.tools.tools import PythonAgentTool
|
|
7
|
+
from strands.types.tools import ToolResult, ToolUse
|
|
8
|
+
{{/if}}
|
|
1
9
|
from strands import Agent, tool
|
|
10
|
+
{{#if hasSkillsFetcher}}
|
|
11
|
+
from strands import AgentSkills
|
|
12
|
+
{{#if hasFetchedSkills}}
|
|
13
|
+
from skills.fetcher import resolve_s3_skills, resolve_git_skills
|
|
14
|
+
{{/if}}
|
|
15
|
+
{{#if (some gitSkills "credentialArn")}}
|
|
16
|
+
from bedrock_agentcore.services.identity import IdentityClient
|
|
17
|
+
{{/if}}
|
|
18
|
+
{{/if}}
|
|
19
|
+
import asyncio
|
|
20
|
+
{{#if hasShell}}
|
|
21
|
+
import subprocess
|
|
22
|
+
{{/if}}
|
|
23
|
+
{{#if hasFileOperations}}
|
|
24
|
+
import os
|
|
25
|
+
{{/if}}
|
|
26
|
+
{{#if hasExecutionLimits}}
|
|
27
|
+
from strands.tools.executors import SequentialToolExecutor
|
|
28
|
+
from strands.types.exceptions import EventLoopException
|
|
29
|
+
from hooks.execution_limits import ExecutionLimitExceeded, ExecutionLimitsHook
|
|
30
|
+
{{/if}}
|
|
31
|
+
{{#if hasConfigBundle}}
|
|
32
|
+
from strands.hooks import HookProvider, HookRegistry, BeforeInvocationEvent, BeforeToolCallEvent
|
|
33
|
+
{{/if}}
|
|
34
|
+
{{#if truncationStrategy}}
|
|
35
|
+
{{#if (eq truncationStrategy "sliding_window")}}
|
|
36
|
+
from strands.agent.conversation_manager.sliding_window_conversation_manager import SlidingWindowConversationManager
|
|
37
|
+
{{/if}}
|
|
38
|
+
{{#if (eq truncationStrategy "summarization")}}
|
|
39
|
+
from strands.agent.conversation_manager.summarizing_conversation_manager import SummarizingConversationManager
|
|
40
|
+
{{/if}}
|
|
41
|
+
{{else}}
|
|
42
|
+
from strands.agent.conversation_manager.null_conversation_manager import NullConversationManager
|
|
43
|
+
{{/if}}
|
|
44
|
+
{{#if hasConfigBundle}}
|
|
45
|
+
from bedrock_agentcore.runtime.context import BedrockAgentCoreContext
|
|
46
|
+
{{/if}}
|
|
47
|
+
{{#if hasBrowser}}
|
|
48
|
+
from strands_tools.browser import AgentCoreBrowser
|
|
49
|
+
{{/if}}
|
|
50
|
+
{{#if hasCodeInterpreter}}
|
|
51
|
+
from strands_tools.code_interpreter import AgentCoreCodeInterpreter
|
|
52
|
+
{{/if}}
|
|
2
53
|
from bedrock_agentcore.runtime import BedrockAgentCoreApp
|
|
3
54
|
from model.load import load_model
|
|
4
55
|
{{#if hasGateway}}
|
|
5
56
|
from mcp_client.client import get_all_gateway_mcp_clients
|
|
6
|
-
{{else}}
|
|
7
|
-
from mcp_client.client import get_streamable_http_mcp_client
|
|
8
57
|
{{/if}}
|
|
58
|
+
{{#if remoteMcpTools}}
|
|
59
|
+
from mcp_client.client import get_all_remote_mcp_clients
|
|
60
|
+
{{/if}}
|
|
61
|
+
{{#unless (or hasGateway remoteMcpTools)}}
|
|
62
|
+
{{#unless isExportHarness}}
|
|
63
|
+
from mcp_client.client import get_streamable_http_mcp_client
|
|
64
|
+
{{/unless}}
|
|
65
|
+
{{/unless}}
|
|
9
66
|
{{#if hasMemory}}
|
|
10
67
|
from memory.session import get_memory_session_manager
|
|
11
68
|
{{/if}}
|
|
12
|
-
{{#
|
|
69
|
+
{{#unless hasFileOperations}}
|
|
70
|
+
{{#if (or needsOs browserIdentifierEnvVar codeInterpreterIdentifierEnvVar (some gitSkills "credentialArn"))}}
|
|
13
71
|
import os
|
|
14
72
|
{{/if}}
|
|
73
|
+
{{/unless}}
|
|
74
|
+
{{#if hasPayment}}
|
|
75
|
+
from capabilities.payments.payments import create_payments_plugin, PAYMENT_SYSTEM_PROMPT
|
|
76
|
+
{{/if}}
|
|
15
77
|
|
|
16
78
|
app = BedrockAgentCoreApp()
|
|
17
79
|
log = app.logger
|
|
18
80
|
|
|
19
|
-
#
|
|
81
|
+
{{#if (or hasGateway remoteMcpTools)}}
|
|
82
|
+
# Define MCP clients for all configured MCP servers (gateways and/or remote MCP)
|
|
83
|
+
mcp_clients = []
|
|
20
84
|
{{#if hasGateway}}
|
|
21
|
-
mcp_clients
|
|
85
|
+
mcp_clients += get_all_gateway_mcp_clients()
|
|
86
|
+
{{/if}}
|
|
87
|
+
{{#if remoteMcpTools}}
|
|
88
|
+
mcp_clients += get_all_remote_mcp_clients()
|
|
89
|
+
{{/if}}
|
|
22
90
|
{{else}}
|
|
91
|
+
{{#unless isExportHarness}}
|
|
92
|
+
# Define a Streamable HTTP MCP Client
|
|
23
93
|
mcp_clients = [get_streamable_http_mcp_client()]
|
|
94
|
+
{{/unless}}
|
|
95
|
+
{{/if}}
|
|
96
|
+
|
|
97
|
+
{{#if systemPromptText}}
|
|
98
|
+
DEFAULT_SYSTEM_PROMPT = """{{escapePyStr systemPromptText}}"""
|
|
99
|
+
{{else}}
|
|
100
|
+
DEFAULT_SYSTEM_PROMPT = """
|
|
101
|
+
You are a helpful assistant. Use tools when appropriate.
|
|
102
|
+
{{#if needsOs}}{{#unless isExportHarness}}
|
|
103
|
+
You have access to the following mounted filesystems. Use file_read, file_write, and list_files with full absolute paths:
|
|
104
|
+
{{#if sessionStorageMountPath}}- {{sessionStorageMountPath}}: ephemeral session storage (lost when session ends)
|
|
105
|
+
{{/if}}{{#each efsMounts}}- {{mountPath}}: EFS persistent storage (persists across sessions and agent restarts)
|
|
106
|
+
{{/each}}{{#each s3Mounts}}- {{mountPath}}: S3 Files persistent storage (durable, backed by S3)
|
|
107
|
+
{{/each}}{{/unless}}{{/if}}
|
|
108
|
+
"""
|
|
109
|
+
{{/if}}
|
|
110
|
+
|
|
111
|
+
{{#if hasConfigBundle}}
|
|
112
|
+
DEFAULT_TOOL_DESC = "Return the sum of two numbers"
|
|
24
113
|
{{/if}}
|
|
25
114
|
|
|
26
115
|
# Define a collection of tools used by the model
|
|
27
116
|
tools = []
|
|
28
117
|
|
|
118
|
+
{{#if inlineFunctionTools}}
|
|
119
|
+
# Inline function tools — stop the agent loop so the tool call streams back to the caller
|
|
120
|
+
def _make_inline_tool(name: str, spec: dict) -> PythonAgentTool:
|
|
121
|
+
def _handler(tool: ToolUse, **kwargs: Any) -> ToolResult:
|
|
122
|
+
kwargs.get("request_state", {})["stop_event_loop"] = True
|
|
123
|
+
return {"toolUseId": tool["toolUseId"], "status": "success", "content": [{"text": " "}]}
|
|
124
|
+
_handler.__name__ = name
|
|
125
|
+
return PythonAgentTool(tool_name=name, tool_spec=spec, tool_func=_handler)
|
|
126
|
+
|
|
127
|
+
{{#each inlineFunctionTools}}
|
|
128
|
+
_INLINE_SPEC_{{snakeCase name}} = {
|
|
129
|
+
"name": "{{name}}",
|
|
130
|
+
"description": {{safeJson description}},
|
|
131
|
+
"inputSchema": {"json": json.loads({{pyJsonStr inputSchema}}) },
|
|
132
|
+
}
|
|
133
|
+
tools.append(_make_inline_tool("{{name}}", _INLINE_SPEC_{{snakeCase name}}))
|
|
134
|
+
{{/each}}
|
|
135
|
+
|
|
136
|
+
_INLINE_FUNCTION_NAMES = { {{#each inlineFunctionTools}}"{{name}}"{{#unless @last}}, {{/unless}}{{/each}} }
|
|
137
|
+
|
|
138
|
+
{{else}}
|
|
139
|
+
_INLINE_FUNCTION_NAMES = set()
|
|
140
|
+
|
|
141
|
+
{{#unless isExportHarness}}
|
|
29
142
|
# Define a simple function tool
|
|
143
|
+
{{#if hasConfigBundle}}
|
|
144
|
+
@tool(description=DEFAULT_TOOL_DESC)
|
|
145
|
+
{{else}}
|
|
30
146
|
@tool
|
|
147
|
+
{{/if}}
|
|
31
148
|
def add_numbers(a: int, b: int) -> int:
|
|
32
149
|
"""Return the sum of two numbers"""
|
|
33
150
|
return a+b
|
|
34
151
|
tools.append(add_numbers)
|
|
35
152
|
|
|
36
|
-
{{
|
|
37
|
-
|
|
153
|
+
{{/unless}}
|
|
154
|
+
{{/if}}
|
|
155
|
+
{{#if hasBrowser}}
|
|
156
|
+
{{#if browserIdentifierEnvVar}}
|
|
157
|
+
_browser_id = os.getenv("{{browserIdentifierEnvVar}}")
|
|
158
|
+
tools.append(AgentCoreBrowser(**({"identifier": _browser_id} if _browser_id else {})).browser)
|
|
159
|
+
{{else}}
|
|
160
|
+
tools.append(AgentCoreBrowser().browser)
|
|
161
|
+
{{/if}}
|
|
162
|
+
{{/if}}
|
|
163
|
+
{{#if hasCodeInterpreter}}
|
|
164
|
+
{{#if codeInterpreterIdentifierEnvVar}}
|
|
165
|
+
_code_interpreter_id = os.getenv("{{codeInterpreterIdentifierEnvVar}}")
|
|
166
|
+
tools.append(AgentCoreCodeInterpreter(**({"identifier": _code_interpreter_id} if _code_interpreter_id else {})).code_interpreter)
|
|
167
|
+
{{else}}
|
|
168
|
+
tools.append(AgentCoreCodeInterpreter().code_interpreter)
|
|
169
|
+
{{/if}}
|
|
170
|
+
{{/if}}
|
|
171
|
+
{{#if hasShell}}
|
|
172
|
+
@tool
|
|
173
|
+
def shell(command: str, timeout: int = 300) -> dict:
|
|
174
|
+
"""Execute a bash command and return the results.
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
command: The bash command to execute
|
|
178
|
+
timeout: Timeout in seconds (default: 300)
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
Dict with stdout, stderr, and exit_code
|
|
182
|
+
"""
|
|
183
|
+
result = subprocess.run(
|
|
184
|
+
command, shell=True, capture_output=True, text=True, timeout=timeout
|
|
185
|
+
)
|
|
186
|
+
return {"stdout": result.stdout, "stderr": result.stderr, "exit_code": result.returncode}
|
|
187
|
+
|
|
188
|
+
tools.append(shell)
|
|
189
|
+
{{/if}}
|
|
190
|
+
{{#if hasFileOperations}}
|
|
191
|
+
@tool
|
|
192
|
+
def file_operations(
|
|
193
|
+
command: str,
|
|
194
|
+
path: str,
|
|
195
|
+
old_str: str = None,
|
|
196
|
+
new_str: str = None,
|
|
197
|
+
file_text: str = None,
|
|
198
|
+
insert_line: int = None,
|
|
199
|
+
view_range: list = None,
|
|
200
|
+
) -> str:
|
|
201
|
+
"""Text editor tool for viewing and modifying files.
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
command: The command to execute ("view", "str_replace", "create", "insert")
|
|
205
|
+
path: Path to the file or directory
|
|
206
|
+
old_str: Text to replace (for str_replace command)
|
|
207
|
+
new_str: Replacement text (for str_replace and insert commands)
|
|
208
|
+
file_text: Content for new file (for create command)
|
|
209
|
+
insert_line: Line number to insert after (for insert command)
|
|
210
|
+
view_range: [start_line, end_line] for viewing specific lines (for view command)
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
Result of the operation
|
|
214
|
+
"""
|
|
215
|
+
try:
|
|
216
|
+
if command == "view":
|
|
217
|
+
if not os.path.exists(path):
|
|
218
|
+
return f"Error: Path '{path}' does not exist"
|
|
219
|
+
if os.path.isdir(path):
|
|
220
|
+
return "\n".join(os.listdir(path))
|
|
221
|
+
with open(path) as f:
|
|
222
|
+
lines = f.read().splitlines()
|
|
223
|
+
if view_range:
|
|
224
|
+
start, end = view_range
|
|
225
|
+
start_idx = max(0, start - 1)
|
|
226
|
+
end_idx = len(lines) if end == -1 else min(len(lines), end)
|
|
227
|
+
lines = lines[start_idx:end_idx]
|
|
228
|
+
start_num = start_idx + 1
|
|
229
|
+
else:
|
|
230
|
+
start_num = 1
|
|
231
|
+
return "\n".join(f"{start_num + i}: {line}" for i, line in enumerate(lines))
|
|
232
|
+
elif command == "str_replace":
|
|
233
|
+
if old_str is None or new_str is None:
|
|
234
|
+
return "Error: str_replace requires both old_str and new_str parameters"
|
|
235
|
+
if not os.path.exists(path):
|
|
236
|
+
return f"Error: File '{path}' does not exist"
|
|
237
|
+
content = open(path).read()
|
|
238
|
+
if old_str not in content:
|
|
239
|
+
return "Error: Text not found in file"
|
|
240
|
+
count = content.count(old_str)
|
|
241
|
+
if count > 1:
|
|
242
|
+
return f"Error: Text appears {count} times in file. Please be more specific."
|
|
243
|
+
open(path, "w").write(content.replace(old_str, new_str, 1))
|
|
244
|
+
return f"Successfully replaced text in '{path}'"
|
|
245
|
+
elif command == "create":
|
|
246
|
+
if file_text is None:
|
|
247
|
+
return "Error: create requires file_text parameter"
|
|
248
|
+
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
|
249
|
+
open(path, "w").write(file_text)
|
|
250
|
+
return f"Successfully created file '{path}'"
|
|
251
|
+
elif command == "insert":
|
|
252
|
+
if new_str is None or insert_line is None:
|
|
253
|
+
return "Error: insert requires both new_str and insert_line parameters"
|
|
254
|
+
if not os.path.exists(path):
|
|
255
|
+
return f"Error: File '{path}' does not exist"
|
|
256
|
+
lines = open(path).read().splitlines(True)
|
|
257
|
+
if insert_line == 0:
|
|
258
|
+
lines.insert(0, new_str + "\n")
|
|
259
|
+
elif insert_line >= len(lines):
|
|
260
|
+
lines.append(new_str + "\n")
|
|
261
|
+
else:
|
|
262
|
+
lines.insert(insert_line, new_str + "\n")
|
|
263
|
+
open(path, "w").write("".join(lines))
|
|
264
|
+
return f"Successfully inserted text in '{path}' at line {insert_line + 1}"
|
|
265
|
+
else:
|
|
266
|
+
return f"Error: Unknown command '{command}'"
|
|
267
|
+
except Exception as e:
|
|
268
|
+
return f"Error: {e}"
|
|
269
|
+
|
|
270
|
+
tools.append(file_operations)
|
|
271
|
+
{{/if}}
|
|
272
|
+
{{#if needsOs}}{{#unless isExportHarness}}
|
|
273
|
+
_MOUNT_PATHS = [
|
|
274
|
+
{{#if sessionStorageMountPath}}"{{sessionStorageMountPath}}",{{/if}}
|
|
275
|
+
{{#each efsMounts}}"{{mountPath}}",{{/each}}
|
|
276
|
+
{{#each s3Mounts}}"{{mountPath}}",{{/each}}
|
|
277
|
+
]
|
|
38
278
|
|
|
39
279
|
def _safe_resolve(path: str) -> str:
|
|
40
|
-
|
|
41
|
-
resolved
|
|
42
|
-
|
|
43
|
-
raise ValueError(f"Path '{path}' is outside the storage boundary")
|
|
280
|
+
resolved = os.path.realpath(path)
|
|
281
|
+
if not any(resolved == os.path.realpath(m) or resolved.startswith(os.path.realpath(m) + os.sep) for m in _MOUNT_PATHS):
|
|
282
|
+
raise ValueError(f"Path '{path}' is not within any configured mount ({', '.join(_MOUNT_PATHS)})")
|
|
44
283
|
return resolved
|
|
45
284
|
|
|
46
285
|
@tool
|
|
47
286
|
def file_read(path: str) -> str:
|
|
48
|
-
"""Read a file from
|
|
287
|
+
"""Read a file from a mounted filesystem. Use the absolute path (e.g. /mnt/tools/data.txt)."""
|
|
49
288
|
try:
|
|
50
289
|
full_path = _safe_resolve(path)
|
|
51
290
|
with open(full_path) as f:
|
|
@@ -57,7 +296,7 @@ def file_read(path: str) -> str:
|
|
|
57
296
|
|
|
58
297
|
@tool
|
|
59
298
|
def file_write(path: str, content: str) -> str:
|
|
60
|
-
"""Write
|
|
299
|
+
"""Write a file to a mounted filesystem. Use the absolute path (e.g. /mnt/tools/data.txt)."""
|
|
61
300
|
try:
|
|
62
301
|
full_path = _safe_resolve(path)
|
|
63
302
|
parent = os.path.dirname(full_path)
|
|
@@ -72,82 +311,367 @@ def file_write(path: str, content: str) -> str:
|
|
|
72
311
|
return f"Error writing '{path}': {e.strerror}"
|
|
73
312
|
|
|
74
313
|
@tool
|
|
75
|
-
def list_files(
|
|
76
|
-
"""List files in
|
|
314
|
+
def list_files(path: str) -> str:
|
|
315
|
+
"""List files in a mounted filesystem directory. Use the absolute path (e.g. /mnt/tools)."""
|
|
77
316
|
try:
|
|
78
|
-
|
|
79
|
-
entries = os.listdir(
|
|
317
|
+
full_path = _safe_resolve(path)
|
|
318
|
+
entries = os.listdir(full_path)
|
|
80
319
|
return "\n".join(entries) if entries else "(empty directory)"
|
|
81
320
|
except ValueError as e:
|
|
82
321
|
return str(e)
|
|
83
322
|
except OSError as e:
|
|
84
|
-
return f"Error listing '{
|
|
323
|
+
return f"Error listing '{path}': {e.strerror}"
|
|
85
324
|
|
|
86
325
|
tools.extend([file_read, file_write, list_files])
|
|
87
|
-
{{/if}}
|
|
326
|
+
{{/unless}}{{/if}}
|
|
88
327
|
|
|
328
|
+
{{#if (or hasGateway remoteMcpTools)}}
|
|
329
|
+
# Add MCP clients to tools
|
|
330
|
+
for mcp_client in mcp_clients:
|
|
331
|
+
if mcp_client:
|
|
332
|
+
tools.append(mcp_client)
|
|
333
|
+
{{else}}
|
|
334
|
+
{{#unless isExportHarness}}
|
|
89
335
|
# Add MCP client to tools if available
|
|
90
336
|
for mcp_client in mcp_clients:
|
|
91
337
|
if mcp_client:
|
|
92
338
|
tools.append(mcp_client)
|
|
339
|
+
{{/unless}}
|
|
340
|
+
{{/if}}
|
|
341
|
+
|
|
342
|
+
{{#if hasConfigBundle}}
|
|
343
|
+
|
|
344
|
+
class ConfigBundleHook(HookProvider):
|
|
345
|
+
"""Injects config bundle values (system prompt, tool descriptions) before each invocation.
|
|
346
|
+
|
|
347
|
+
BedrockAgentCoreContext.get_config_bundle() fetches the component configuration
|
|
348
|
+
for the current runtime ARN from the config bundle service. The SDK caches the
|
|
349
|
+
result and refreshes on bundle version changes.
|
|
350
|
+
"""
|
|
351
|
+
|
|
352
|
+
def register_hooks(self, registry: HookRegistry, **kwargs: Any) -> None:
|
|
353
|
+
registry.add_callback(BeforeInvocationEvent, self._inject_system_prompt)
|
|
354
|
+
registry.add_callback(BeforeToolCallEvent, self._override_tool_desc)
|
|
355
|
+
|
|
356
|
+
def _inject_system_prompt(self, event: BeforeInvocationEvent) -> None:
|
|
357
|
+
config = BedrockAgentCoreContext.get_config_bundle()
|
|
358
|
+
prompt = config.get("systemPrompt", DEFAULT_SYSTEM_PROMPT)
|
|
359
|
+
|
|
360
|
+
if prompt != event.agent.system_prompt:
|
|
361
|
+
event.agent.system_prompt = prompt
|
|
362
|
+
|
|
363
|
+
def _override_tool_desc(self, event: BeforeToolCallEvent) -> None:
|
|
364
|
+
config = BedrockAgentCoreContext.get_config_bundle()
|
|
365
|
+
tool_descs = config.get("toolDescriptions", {})
|
|
366
|
+
|
|
367
|
+
tool_name = event.tool_use["name"]
|
|
368
|
+
override = tool_descs.get(tool_name)
|
|
369
|
+
if override and event.selected_tool:
|
|
370
|
+
spec = event.selected_tool.tool_spec
|
|
371
|
+
if spec and "description" in spec:
|
|
372
|
+
spec["description"] = override
|
|
93
373
|
|
|
94
|
-
SYSTEM_PROMPT = """
|
|
95
|
-
You are a helpful assistant. Use tools when appropriate.
|
|
96
|
-
{{#if sessionStorageMountPath}}
|
|
97
|
-
You have persistent storage at {{sessionStorageMountPath}}. Use file tools to read and write files. Data persists across sessions.
|
|
98
374
|
{{/if}}
|
|
99
|
-
|
|
375
|
+
|
|
376
|
+
def _make_conversation_manager():
|
|
377
|
+
{{#if truncationStrategy}}
|
|
378
|
+
{{#if (eq truncationStrategy "sliding_window")}}
|
|
379
|
+
{{#if truncationConfig}}
|
|
380
|
+
return SlidingWindowConversationManager(**{{safeJson truncationConfig}}, per_turn=True)
|
|
381
|
+
{{else}}
|
|
382
|
+
return SlidingWindowConversationManager(per_turn=True)
|
|
383
|
+
{{/if}}
|
|
384
|
+
{{else}}
|
|
385
|
+
{{#if truncationConfig}}
|
|
386
|
+
return SummarizingConversationManager(**{{safeJson truncationConfig}})
|
|
387
|
+
{{else}}
|
|
388
|
+
return SummarizingConversationManager()
|
|
389
|
+
{{/if}}
|
|
390
|
+
{{/if}}
|
|
391
|
+
{{else}}
|
|
392
|
+
return NullConversationManager()
|
|
393
|
+
{{/if}}
|
|
100
394
|
|
|
101
395
|
{{#if hasMemory}}
|
|
396
|
+
{{#unless hasPayment}}
|
|
102
397
|
def agent_factory():
|
|
103
398
|
cache = {}
|
|
104
|
-
def get_or_create_agent(session_id, user_id):
|
|
105
|
-
|
|
399
|
+
def get_or_create_agent(session_id, user_id{{#if hasSkillsFetcher}}, skill_plugins=None{{/if}}):
|
|
400
|
+
{{#if actorId}}
|
|
401
|
+
_actor_id = "{{actorId}}"
|
|
402
|
+
{{else}}
|
|
403
|
+
_actor_id = user_id
|
|
404
|
+
{{/if}}
|
|
405
|
+
key = f"{session_id}/{_actor_id}"
|
|
106
406
|
if key not in cache:
|
|
107
|
-
# Create an agent for the given session_id and user_id
|
|
108
407
|
cache[key] = Agent(
|
|
109
408
|
model=load_model(),
|
|
110
|
-
session_manager=get_memory_session_manager(session_id,
|
|
111
|
-
|
|
112
|
-
|
|
409
|
+
session_manager=get_memory_session_manager(session_id, _actor_id),
|
|
410
|
+
conversation_manager=_make_conversation_manager(),
|
|
411
|
+
system_prompt=DEFAULT_SYSTEM_PROMPT,
|
|
412
|
+
tools=tools,
|
|
413
|
+
{{#if hasSkillsFetcher}}
|
|
414
|
+
plugins=skill_plugins or None,
|
|
415
|
+
{{/if}}
|
|
416
|
+
{{#if hasExecutionLimits}}
|
|
417
|
+
tool_executor=SequentialToolExecutor(),
|
|
418
|
+
callback_handler=None,
|
|
419
|
+
{{/if}}
|
|
420
|
+
hooks=[
|
|
421
|
+
{{#if hasExecutionLimits}}
|
|
422
|
+
ExecutionLimitsHook(
|
|
423
|
+
{{#if maxIterations}}max_iterations={{maxIterations}},{{/if}}
|
|
424
|
+
{{#if maxTokens}}max_tokens={{maxTokens}},{{/if}}
|
|
425
|
+
{{#if timeoutSeconds}}timeout_seconds={{timeoutSeconds}},{{/if}}
|
|
426
|
+
),
|
|
427
|
+
{{/if}}
|
|
428
|
+
{{#if hasConfigBundle}}
|
|
429
|
+
ConfigBundleHook(),
|
|
430
|
+
{{/if}}
|
|
431
|
+
],
|
|
113
432
|
)
|
|
114
433
|
return cache[key]
|
|
115
434
|
return get_or_create_agent
|
|
116
435
|
get_or_create_agent = agent_factory()
|
|
436
|
+
{{/unless}}
|
|
117
437
|
{{else}}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
438
|
+
{{#unless hasPayment}}
|
|
439
|
+
# Reuses one Agent per session_id so each session keeps its own in-process
|
|
440
|
+
# conversation history (best-effort; resets on cold start). The cache is bounded
|
|
441
|
+
# to 128 sessions with LRU eviction (least-recently-used is dropped and its
|
|
442
|
+
# history reset) so a single process serving many sessions cannot leak history
|
|
443
|
+
# between them or grow without limit. For durable history, attach a session manager.
|
|
444
|
+
def agent_factory():
|
|
445
|
+
cache = OrderedDict()
|
|
446
|
+
def get_or_create_agent(session_id{{#if hasSkillsFetcher}}, skill_plugins=None{{/if}}):
|
|
447
|
+
if session_id in cache:
|
|
448
|
+
cache.move_to_end(session_id)
|
|
449
|
+
return cache[session_id]
|
|
450
|
+
if len(cache) >= 128:
|
|
451
|
+
cache.popitem(last=False)
|
|
452
|
+
cache[session_id] = Agent(
|
|
124
453
|
model=load_model(),
|
|
125
|
-
system_prompt=
|
|
126
|
-
tools=tools
|
|
454
|
+
system_prompt=DEFAULT_SYSTEM_PROMPT,
|
|
455
|
+
tools=tools,
|
|
456
|
+
conversation_manager=_make_conversation_manager(),
|
|
457
|
+
{{#if hasSkillsFetcher}}
|
|
458
|
+
plugins=skill_plugins or None,
|
|
459
|
+
{{/if}}
|
|
460
|
+
{{#if hasExecutionLimits}}
|
|
461
|
+
tool_executor=SequentialToolExecutor(),
|
|
462
|
+
callback_handler=None,
|
|
463
|
+
{{/if}}
|
|
464
|
+
hooks=[
|
|
465
|
+
{{#if hasExecutionLimits}}
|
|
466
|
+
ExecutionLimitsHook(
|
|
467
|
+
{{#if maxIterations}}max_iterations={{maxIterations}},{{/if}}
|
|
468
|
+
{{#if maxTokens}}max_tokens={{maxTokens}},{{/if}}
|
|
469
|
+
{{#if timeoutSeconds}}timeout_seconds={{timeoutSeconds}},{{/if}}
|
|
470
|
+
),
|
|
471
|
+
{{/if}}
|
|
472
|
+
{{#if hasConfigBundle}}
|
|
473
|
+
ConfigBundleHook(),
|
|
474
|
+
{{/if}}
|
|
475
|
+
],
|
|
127
476
|
)
|
|
128
|
-
|
|
477
|
+
return cache[session_id]
|
|
478
|
+
return get_or_create_agent
|
|
479
|
+
get_or_create_agent = agent_factory()
|
|
480
|
+
{{/unless}}
|
|
129
481
|
{{/if}}
|
|
130
482
|
|
|
131
483
|
|
|
484
|
+
def _extract_prompt(payload: dict):
|
|
485
|
+
"""Accept harness-style messages[], tool_results[], or plain prompt string payloads."""
|
|
486
|
+
if "messages" in payload:
|
|
487
|
+
return payload["messages"]
|
|
488
|
+
if "tool_results" in payload:
|
|
489
|
+
return [{"role": "user", "content": [{"toolResult": {
|
|
490
|
+
"toolUseId": tr["toolUseId"],
|
|
491
|
+
"status": tr.get("status", "success"),
|
|
492
|
+
"content": tr.get("content", []),
|
|
493
|
+
}} for tr in payload["tool_results"]]}]
|
|
494
|
+
return payload.get("prompt", "")
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def _has_inline_function_call(messages) -> bool:
|
|
498
|
+
"""Return True if messages contains an assistant toolUse for an inline function tool."""
|
|
499
|
+
if not _INLINE_FUNCTION_NAMES or not isinstance(messages, list):
|
|
500
|
+
return False
|
|
501
|
+
for msg in messages:
|
|
502
|
+
if msg.get("role") == "assistant":
|
|
503
|
+
for block in msg.get("content", []):
|
|
504
|
+
if isinstance(block, dict) and block.get("toolUse", {}).get("name") in _INLINE_FUNCTION_NAMES:
|
|
505
|
+
return True
|
|
506
|
+
return False
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _is_inline_function_call(event: dict) -> bool:
|
|
510
|
+
"""Check if a contentBlockStart event is for an inline function tool."""
|
|
511
|
+
if not _INLINE_FUNCTION_NAMES:
|
|
512
|
+
return False
|
|
513
|
+
cbs = event.get("contentBlockStart", {})
|
|
514
|
+
start = cbs.get("start", {})
|
|
515
|
+
tool_use = start.get("toolUse") if isinstance(start, dict) else None
|
|
516
|
+
return tool_use is not None and tool_use.get("name") in _INLINE_FUNCTION_NAMES
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
|
|
132
520
|
@app.entrypoint
|
|
133
521
|
async def invoke(payload, context):
|
|
134
522
|
log.info("Invoking Agent.....")
|
|
135
523
|
|
|
524
|
+
{{#if hasPayment}}
|
|
525
|
+
user_id = payload.get("user_id") or getattr(context, "user_id", "default-user")
|
|
526
|
+
instrument_id = payload.get("payment_instrument_id")
|
|
527
|
+
session_id = payload.get("payment_session_id")
|
|
528
|
+
payments_plugin = create_payments_plugin(user_id, instrument_id, session_id)
|
|
529
|
+
plugins = [payments_plugin] if payments_plugin else []
|
|
530
|
+
{{/if}}
|
|
531
|
+
{{#if hasSkillsFetcher}}
|
|
532
|
+
skill_paths = [{{#each pathSkills}}{{safeJson this}}{{#unless @last}}, {{/unless}}{{/each}}]
|
|
533
|
+
{{#if s3Skills}}
|
|
534
|
+
s3_skill_sources = [{{#each s3Skills}}{{safeJson this}}{{#unless @last}}, {{/unless}}{{/each}}]
|
|
535
|
+
skill_paths.extend(await asyncio.to_thread(resolve_s3_skills, s3_skill_sources, None))
|
|
536
|
+
{{/if}}
|
|
537
|
+
{{#if gitSkills}}
|
|
538
|
+
git_skill_sources = [
|
|
539
|
+
{{#each gitSkills}}
|
|
540
|
+
dict(url={{safeJson this.url}}{{#if this.path}}, path={{safeJson this.path}}{{/if}}{{#if this.credentialArn}}, credentialArn={{safeJson this.credentialArn}}{{#if this.username}}, username={{safeJson this.username}}{{/if}}{{/if}}),
|
|
541
|
+
{{/each}}
|
|
542
|
+
]
|
|
543
|
+
{{#if (some gitSkills "credentialArn")}}
|
|
544
|
+
_git_identity_client = IdentityClient(os.environ.get("AWS_REGION", os.environ.get("AWS_DEFAULT_REGION", "us-east-1")))
|
|
545
|
+
{{else}}
|
|
546
|
+
_git_identity_client = None
|
|
547
|
+
{{/if}}
|
|
548
|
+
skill_paths.extend(await asyncio.to_thread(resolve_git_skills, git_skill_sources, _git_identity_client))
|
|
549
|
+
{{/if}}
|
|
550
|
+
_skill_plugins = [AgentSkills(skills=skill_paths)] if skill_paths else []
|
|
551
|
+
{{/if}}
|
|
552
|
+
|
|
136
553
|
{{#if hasMemory}}
|
|
554
|
+
{{#if hasPayment}}
|
|
555
|
+
mem_session_id = getattr(context, 'session_id', 'default-session')
|
|
556
|
+
{{#if actorId}}
|
|
557
|
+
mem_user_id = "{{actorId}}"
|
|
558
|
+
{{else}}
|
|
559
|
+
mem_user_id = getattr(context, 'user_id', 'default-user')
|
|
560
|
+
{{/if}}
|
|
561
|
+
agent = Agent(
|
|
562
|
+
model=load_model(),
|
|
563
|
+
session_manager=get_memory_session_manager(mem_session_id, mem_user_id),
|
|
564
|
+
system_prompt=DEFAULT_SYSTEM_PROMPT + PAYMENT_SYSTEM_PROMPT,
|
|
565
|
+
tools=tools,
|
|
566
|
+
plugins=plugins{{#if hasSkillsFetcher}} + _skill_plugins{{/if}},{{#if hasConfigBundle}}
|
|
567
|
+
hooks=[ConfigBundleHook()],{{/if}}
|
|
568
|
+
)
|
|
569
|
+
{{else}}
|
|
137
570
|
session_id = getattr(context, 'session_id', 'default-session')
|
|
571
|
+
{{#if actorId}}
|
|
572
|
+
user_id = "{{actorId}}"
|
|
573
|
+
{{else}}
|
|
138
574
|
user_id = getattr(context, 'user_id', 'default-user')
|
|
139
|
-
|
|
575
|
+
{{/if}}
|
|
576
|
+
agent = get_or_create_agent(session_id, user_id{{#if hasSkillsFetcher}}, _skill_plugins{{/if}})
|
|
577
|
+
{{/if}}
|
|
578
|
+
{{else}}
|
|
579
|
+
{{#if hasPayment}}
|
|
580
|
+
agent = Agent(
|
|
581
|
+
model=load_model(),
|
|
582
|
+
system_prompt=DEFAULT_SYSTEM_PROMPT + PAYMENT_SYSTEM_PROMPT,
|
|
583
|
+
tools=tools,
|
|
584
|
+
plugins=plugins{{#if hasSkillsFetcher}} + _skill_plugins{{/if}},{{#if hasConfigBundle}}
|
|
585
|
+
hooks=[ConfigBundleHook()],{{/if}}
|
|
586
|
+
)
|
|
140
587
|
{{else}}
|
|
141
|
-
|
|
588
|
+
session_id = getattr(context, 'session_id', 'default-session')
|
|
589
|
+
agent = get_or_create_agent(session_id{{#if hasSkillsFetcher}}, _skill_plugins{{/if}})
|
|
590
|
+
{{/if}}
|
|
142
591
|
{{/if}}
|
|
143
592
|
|
|
144
|
-
|
|
145
|
-
|
|
593
|
+
prompt = _extract_prompt(payload)
|
|
594
|
+
|
|
595
|
+
{{#if inlineFunctionTools}}
|
|
596
|
+
# If Turn 2 carries the harness-style assistant(toolUse)+user(toolResult) pair,
|
|
597
|
+
# strip the placeholder turn Strands stored during Turn 1 so the real toolResult
|
|
598
|
+
# is injected cleanly — same protocol as the harness runtime.
|
|
599
|
+
if _has_inline_function_call(prompt):
|
|
600
|
+
msgs = agent.messages
|
|
601
|
+
if len(msgs) >= 2 and any("toolResult" in b for b in msgs[-1].get("content", [])):
|
|
602
|
+
del msgs[-2:]
|
|
603
|
+
{{/if}}
|
|
604
|
+
|
|
605
|
+
{{#if hasExecutionLimits}}
|
|
606
|
+
timeout_seconds = {{#if timeoutSeconds}}{{timeoutSeconds}}{{else}}None{{/if}}
|
|
607
|
+
timeout_fired = False
|
|
608
|
+
watchdog_task = None
|
|
609
|
+
if timeout_seconds is not None:
|
|
610
|
+
async def _timeout_watchdog():
|
|
611
|
+
nonlocal timeout_fired
|
|
612
|
+
await asyncio.sleep(timeout_seconds)
|
|
613
|
+
timeout_fired = True
|
|
614
|
+
agent.cancel()
|
|
615
|
+
watchdog_task = asyncio.create_task(_timeout_watchdog())
|
|
616
|
+
|
|
617
|
+
try:
|
|
618
|
+
{{#if inlineFunctionTools}}
|
|
619
|
+
hit_inline_function = False
|
|
620
|
+
{{/if}}
|
|
621
|
+
async for event in agent.stream_async(
|
|
622
|
+
prompt,
|
|
623
|
+
):
|
|
624
|
+
if not isinstance(event, dict) or "event" not in event:
|
|
625
|
+
continue
|
|
626
|
+
cbs = event["event"].get("contentBlockStart")
|
|
627
|
+
if cbs is not None and not cbs.get("start"):
|
|
628
|
+
continue
|
|
629
|
+
{{#if inlineFunctionTools}}
|
|
630
|
+
if not hit_inline_function:
|
|
631
|
+
hit_inline_function = _is_inline_function_call(event["event"])
|
|
632
|
+
{{/if}}
|
|
633
|
+
yield event
|
|
634
|
+
{{#if inlineFunctionTools}}
|
|
635
|
+
if hit_inline_function and "messageStop" in event["event"]:
|
|
636
|
+
return
|
|
637
|
+
{{/if}}
|
|
146
638
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
639
|
+
if timeout_fired:
|
|
640
|
+
yield {"event": {"messageStop": {"stopReason": "timeout_exceeded"}}}
|
|
641
|
+
except EventLoopException as e:
|
|
642
|
+
if isinstance(e.original_exception, ExecutionLimitExceeded):
|
|
643
|
+
yield {"event": {"messageStop": {"stopReason": str(e.original_exception)}}}
|
|
644
|
+
return
|
|
645
|
+
raise
|
|
646
|
+
finally:
|
|
647
|
+
if watchdog_task is not None:
|
|
648
|
+
watchdog_task.cancel()
|
|
649
|
+
try:
|
|
650
|
+
await watchdog_task
|
|
651
|
+
except asyncio.CancelledError:
|
|
652
|
+
pass
|
|
653
|
+
{{else}}
|
|
654
|
+
{{#if inlineFunctionTools}}
|
|
655
|
+
hit_inline_function = False
|
|
656
|
+
{{/if}}
|
|
657
|
+
async for event in agent.stream_async(
|
|
658
|
+
prompt,
|
|
659
|
+
):
|
|
660
|
+
if not isinstance(event, dict) or "event" not in event:
|
|
661
|
+
continue
|
|
662
|
+
cbs = event["event"].get("contentBlockStart")
|
|
663
|
+
if cbs is not None and not cbs.get("start"):
|
|
664
|
+
continue
|
|
665
|
+
{{#if inlineFunctionTools}}
|
|
666
|
+
if not hit_inline_function:
|
|
667
|
+
hit_inline_function = _is_inline_function_call(event["event"])
|
|
668
|
+
{{/if}}
|
|
669
|
+
yield event
|
|
670
|
+
{{#if inlineFunctionTools}}
|
|
671
|
+
if hit_inline_function and "messageStop" in event["event"]:
|
|
672
|
+
return
|
|
673
|
+
{{/if}}
|
|
674
|
+
{{/if}}
|
|
151
675
|
|
|
152
676
|
|
|
153
677
|
if __name__ == "__main__":
|