@aws/agentcore 1.0.0-preview.3 → 1.0.0-preview.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (330) hide show
  1. package/README.md +193 -33
  2. package/dist/agent-inspector/index.css +1 -1
  3. package/dist/agent-inspector/index.js +99 -84
  4. package/dist/assets/README.md +6 -2
  5. package/dist/assets/__tests__/__snapshots__/assets.snapshot.test.ts.snap +3344 -366
  6. package/dist/assets/__tests__/__snapshots__/dockerfile-render.test.ts.snap +6 -2
  7. package/dist/assets/__tests__/assets.snapshot.test.ts +10 -24
  8. package/dist/assets/__tests__/googleadk-observability.test.ts +23 -0
  9. package/dist/assets/__tests__/googleadk-session-eviction.test.ts +87 -0
  10. package/dist/assets/__tests__/input-validation.test.ts +44 -0
  11. package/dist/assets/__tests__/summarization-namespace.test.ts +43 -0
  12. package/dist/assets/agents/AGENTS.md +91 -14
  13. package/dist/assets/cdk/bin/cdk.ts +109 -24
  14. package/dist/assets/cdk/lib/cdk-stack.ts +227 -19
  15. package/dist/assets/cdk/package.json +9 -9
  16. package/dist/assets/cdk/test/cdk.test.ts +4 -0
  17. package/dist/assets/container/python/Dockerfile +7 -1
  18. package/dist/assets/container/typescript/Dockerfile +25 -0
  19. package/dist/assets/container/typescript/dockerignore.template +24 -0
  20. package/dist/assets/datasets/predefined-v1.jsonl +3 -0
  21. package/dist/assets/datasets/simulated-v1.jsonl +3 -0
  22. package/dist/assets/evaluators/autoevals-lambda/execution-role-policy.json +15 -0
  23. package/dist/assets/evaluators/autoevals-lambda/lambda_function.py +37 -0
  24. package/dist/assets/evaluators/autoevals-lambda/pyproject.toml +22 -0
  25. package/dist/assets/evaluators/deepeval-lambda/execution-role-policy.json +15 -0
  26. package/dist/assets/evaluators/deepeval-lambda/lambda_function.py +29 -0
  27. package/dist/assets/evaluators/deepeval-lambda/pyproject.toml +19 -0
  28. package/dist/assets/mcp/python/pyproject.toml +1 -1
  29. package/dist/assets/python/a2a/googleadk/base/main.py +32 -18
  30. package/dist/assets/python/a2a/googleadk/base/pyproject.toml +6 -4
  31. package/dist/assets/python/a2a/langchain_langgraph/base/main.py +35 -21
  32. package/dist/assets/python/a2a/langchain_langgraph/base/pyproject.toml +4 -3
  33. package/dist/assets/python/a2a/strands/base/main.py +23 -17
  34. package/dist/assets/python/a2a/strands/base/pyproject.toml +3 -3
  35. package/dist/assets/python/a2a/strands/capabilities/memory/session.py +4 -1
  36. package/dist/assets/python/agui/googleadk/base/main.py +62 -2
  37. package/dist/assets/python/agui/googleadk/base/pyproject.toml +6 -5
  38. package/dist/assets/python/agui/langchain_langgraph/base/main.py +56 -0
  39. package/dist/assets/python/agui/langchain_langgraph/base/pyproject.toml +3 -2
  40. package/dist/assets/python/agui/strands/base/main.py +63 -1
  41. package/dist/assets/python/agui/strands/base/pyproject.toml +2 -2
  42. package/dist/assets/python/agui/strands/capabilities/memory/session.py +4 -1
  43. package/dist/assets/python/http/autogen/base/README.md +7 -1
  44. package/dist/assets/python/http/autogen/base/main.py +62 -29
  45. package/dist/assets/python/http/autogen/base/pyproject.toml +1 -1
  46. package/dist/assets/python/http/googleadk/base/README.md +7 -1
  47. package/dist/assets/python/http/googleadk/base/main.py +71 -24
  48. package/dist/assets/python/http/googleadk/base/mcp_client/client.py +7 -7
  49. package/dist/assets/python/http/googleadk/base/pyproject.toml +5 -3
  50. package/dist/assets/python/http/langchain_langgraph/base/README.md +7 -1
  51. package/dist/assets/python/http/langchain_langgraph/base/main.py +119 -24
  52. package/dist/assets/python/http/langchain_langgraph/base/mcp_client/client.py +10 -8
  53. package/dist/assets/python/http/langchain_langgraph/base/pyproject.toml +5 -4
  54. package/dist/assets/python/http/openaiagents/base/README.md +7 -1
  55. package/dist/assets/python/http/openaiagents/base/main.py +63 -32
  56. package/dist/assets/python/http/openaiagents/base/mcp_client/client.py +4 -4
  57. package/dist/assets/python/http/openaiagents/base/pyproject.toml +3 -3
  58. package/dist/assets/python/http/strands/base/README.md +8 -1
  59. package/dist/assets/python/http/strands/base/main.py +607 -47
  60. package/dist/assets/python/http/strands/base/mcp_client/client.py +49 -6
  61. package/dist/assets/python/http/strands/base/model/load.py +119 -3
  62. package/dist/assets/python/http/strands/base/model/mantle_compat.py +21 -0
  63. package/dist/assets/python/http/strands/base/pyproject.toml +11 -5
  64. package/dist/assets/python/http/strands/base/skills/fetcher.py +279 -0
  65. package/dist/assets/python/http/strands/capabilities/execution-limits/hooks/execution_limits.py +54 -0
  66. package/dist/assets/python/http/strands/capabilities/memory/session.py +4 -1
  67. package/dist/assets/python/http/strands/capabilities/payments/__init__.py +4 -0
  68. package/dist/assets/python/http/strands/capabilities/payments/payments.py +142 -0
  69. package/dist/assets/python/mcp/standalone/base/main.py +58 -0
  70. package/dist/assets/python/mcp/standalone/base/pyproject.toml +1 -1
  71. package/dist/assets/typescript/http/strands/base/README.md +42 -0
  72. package/dist/assets/typescript/http/strands/base/gitignore.template +22 -0
  73. package/dist/assets/typescript/http/strands/base/main.ts +149 -0
  74. package/dist/assets/typescript/http/strands/base/mcp_client/client.ts +11 -0
  75. package/dist/assets/typescript/http/strands/base/model/load.ts +102 -0
  76. package/dist/assets/typescript/http/strands/base/package.json +38 -0
  77. package/dist/assets/typescript/http/strands/base/tsconfig.json +19 -0
  78. package/dist/assets/typescript/http/strands/capabilities/memory/memory.ts +52 -0
  79. package/dist/assets/typescript/http/vercelai/base/README.md +42 -0
  80. package/dist/assets/typescript/http/vercelai/base/gitignore.template +22 -0
  81. package/dist/assets/typescript/http/vercelai/base/main.ts +70 -0
  82. package/dist/assets/typescript/http/vercelai/base/model/load.ts +121 -0
  83. package/dist/assets/typescript/http/vercelai/base/package.json +35 -0
  84. package/dist/assets/typescript/http/vercelai/base/tsconfig.json +19 -0
  85. package/dist/cli/index.mjs +1743 -627
  86. package/dist/lib/constants.d.ts +8 -4
  87. package/dist/lib/constants.d.ts.map +1 -1
  88. package/dist/lib/constants.js +13 -7
  89. package/dist/lib/constants.js.map +1 -1
  90. package/dist/lib/dependency-management/index.d.ts +5 -0
  91. package/dist/lib/dependency-management/index.d.ts.map +1 -0
  92. package/dist/lib/dependency-management/index.js +8 -0
  93. package/dist/lib/dependency-management/index.js.map +1 -0
  94. package/dist/lib/dependency-management/messages.d.ts +30 -0
  95. package/dist/lib/dependency-management/messages.d.ts.map +1 -0
  96. package/dist/lib/dependency-management/messages.js +86 -0
  97. package/dist/lib/dependency-management/messages.js.map +1 -0
  98. package/dist/lib/dependency-management/plan.d.ts +25 -0
  99. package/dist/lib/dependency-management/plan.d.ts.map +1 -0
  100. package/dist/lib/dependency-management/plan.js +67 -0
  101. package/dist/lib/dependency-management/plan.js.map +1 -0
  102. package/dist/lib/dependency-management/semver.d.ts +21 -0
  103. package/dist/lib/dependency-management/semver.d.ts.map +1 -0
  104. package/dist/lib/dependency-management/semver.js +51 -0
  105. package/dist/lib/dependency-management/semver.js.map +1 -0
  106. package/dist/lib/dependency-management/sync.d.ts +26 -0
  107. package/dist/lib/dependency-management/sync.d.ts.map +1 -0
  108. package/dist/lib/dependency-management/sync.js +141 -0
  109. package/dist/lib/dependency-management/sync.js.map +1 -0
  110. package/dist/lib/dependency-management/types.d.ts +85 -0
  111. package/dist/lib/dependency-management/types.d.ts.map +1 -0
  112. package/dist/lib/dependency-management/types.js +3 -0
  113. package/dist/lib/dependency-management/types.js.map +1 -0
  114. package/dist/lib/errors/index.d.ts +1 -1
  115. package/dist/lib/errors/index.d.ts.map +1 -1
  116. package/dist/lib/errors/index.js +1 -1
  117. package/dist/lib/errors/index.js.map +1 -1
  118. package/dist/lib/errors/types.d.ts +274 -0
  119. package/dist/lib/errors/types.d.ts.map +1 -0
  120. package/dist/lib/errors/types.js +423 -0
  121. package/dist/lib/errors/types.js.map +1 -0
  122. package/dist/lib/errors/zod.d.ts +8 -0
  123. package/dist/lib/errors/zod.d.ts.map +1 -0
  124. package/dist/lib/errors/{config.js → zod.js} +8 -81
  125. package/dist/lib/errors/zod.js.map +1 -0
  126. package/dist/lib/index.d.ts +3 -0
  127. package/dist/lib/index.d.ts.map +1 -1
  128. package/dist/lib/index.js +4 -1
  129. package/dist/lib/index.js.map +1 -1
  130. package/dist/lib/packaging/build-args.d.ts +6 -0
  131. package/dist/lib/packaging/build-args.d.ts.map +1 -1
  132. package/dist/lib/packaging/build-args.js +11 -2
  133. package/dist/lib/packaging/build-args.js.map +1 -1
  134. package/dist/lib/packaging/build-context-dockerignore.d.ts +23 -0
  135. package/dist/lib/packaging/build-context-dockerignore.d.ts.map +1 -0
  136. package/dist/lib/packaging/build-context-dockerignore.js +63 -0
  137. package/dist/lib/packaging/build-context-dockerignore.js.map +1 -0
  138. package/dist/lib/packaging/build-context.d.ts +21 -0
  139. package/dist/lib/packaging/build-context.d.ts.map +1 -0
  140. package/dist/lib/packaging/build-context.js +21 -0
  141. package/dist/lib/packaging/build-context.js.map +1 -0
  142. package/dist/lib/packaging/container.d.ts.map +1 -1
  143. package/dist/lib/packaging/container.js +20 -9
  144. package/dist/lib/packaging/container.js.map +1 -1
  145. package/dist/lib/packaging/helpers.d.ts +16 -0
  146. package/dist/lib/packaging/helpers.d.ts.map +1 -1
  147. package/dist/lib/packaging/helpers.js +127 -29
  148. package/dist/lib/packaging/helpers.js.map +1 -1
  149. package/dist/lib/packaging/index.d.ts +2 -1
  150. package/dist/lib/packaging/index.d.ts.map +1 -1
  151. package/dist/lib/packaging/index.js +9 -20
  152. package/dist/lib/packaging/index.js.map +1 -1
  153. package/dist/lib/packaging/node.d.ts +2 -2
  154. package/dist/lib/packaging/node.d.ts.map +1 -1
  155. package/dist/lib/packaging/node.js +83 -38
  156. package/dist/lib/packaging/node.js.map +1 -1
  157. package/dist/lib/packaging/python.js +12 -12
  158. package/dist/lib/packaging/python.js.map +1 -1
  159. package/dist/lib/result.d.ts +57 -0
  160. package/dist/lib/result.d.ts.map +1 -0
  161. package/dist/lib/result.js +62 -0
  162. package/dist/lib/result.js.map +1 -0
  163. package/dist/lib/schemas/io/config-io.d.ts +14 -0
  164. package/dist/lib/schemas/io/config-io.d.ts.map +1 -1
  165. package/dist/lib/schemas/io/config-io.js +89 -5
  166. package/dist/lib/schemas/io/config-io.js.map +1 -1
  167. package/dist/lib/schemas/io/global-config.d.ts +41 -0
  168. package/dist/lib/schemas/io/global-config.d.ts.map +1 -0
  169. package/dist/lib/schemas/io/global-config.js +119 -0
  170. package/dist/lib/schemas/io/global-config.js.map +1 -0
  171. package/dist/lib/schemas/io/index.d.ts +1 -2
  172. package/dist/lib/schemas/io/index.d.ts.map +1 -1
  173. package/dist/lib/schemas/io/index.js +1 -4
  174. package/dist/lib/schemas/io/index.js.map +1 -1
  175. package/dist/lib/schemas/io/path-resolver.d.ts +0 -6
  176. package/dist/lib/schemas/io/path-resolver.d.ts.map +1 -1
  177. package/dist/lib/schemas/io/path-resolver.js +3 -13
  178. package/dist/lib/schemas/io/path-resolver.js.map +1 -1
  179. package/dist/lib/secrets/cipher.d.ts +12 -0
  180. package/dist/lib/secrets/cipher.d.ts.map +1 -0
  181. package/dist/lib/secrets/cipher.js +54 -0
  182. package/dist/lib/secrets/cipher.js.map +1 -0
  183. package/dist/lib/secrets/index.d.ts +4 -0
  184. package/dist/lib/secrets/index.d.ts.map +1 -0
  185. package/dist/lib/secrets/index.js +15 -0
  186. package/dist/lib/secrets/index.js.map +1 -0
  187. package/dist/lib/secrets/key-provider.d.ts +16 -0
  188. package/dist/lib/secrets/key-provider.d.ts.map +1 -0
  189. package/dist/lib/secrets/key-provider.js +191 -0
  190. package/dist/lib/secrets/key-provider.js.map +1 -0
  191. package/dist/lib/secrets/sensitive-keys.d.ts +21 -0
  192. package/dist/lib/secrets/sensitive-keys.d.ts.map +1 -0
  193. package/dist/lib/secrets/sensitive-keys.js +67 -0
  194. package/dist/lib/secrets/sensitive-keys.js.map +1 -0
  195. package/dist/lib/time-constants.d.ts +5 -0
  196. package/dist/lib/time-constants.d.ts.map +1 -0
  197. package/dist/lib/time-constants.js +8 -0
  198. package/dist/lib/time-constants.js.map +1 -0
  199. package/dist/lib/utils/env.d.ts +8 -2
  200. package/dist/lib/utils/env.d.ts.map +1 -1
  201. package/dist/lib/utils/env.js +65 -17
  202. package/dist/lib/utils/env.js.map +1 -1
  203. package/dist/lib/utils/index.d.ts +3 -2
  204. package/dist/lib/utils/index.d.ts.map +1 -1
  205. package/dist/lib/utils/index.js +6 -1
  206. package/dist/lib/utils/index.js.map +1 -1
  207. package/dist/lib/utils/polling.d.ts +31 -0
  208. package/dist/lib/utils/polling.d.ts.map +1 -0
  209. package/dist/lib/utils/polling.js +61 -0
  210. package/dist/lib/utils/polling.js.map +1 -0
  211. package/dist/lib/utils/subprocess.d.ts +4 -1
  212. package/dist/lib/utils/subprocess.d.ts.map +1 -1
  213. package/dist/lib/utils/subprocess.js +11 -57
  214. package/dist/lib/utils/subprocess.js.map +1 -1
  215. package/dist/lib/utils/zod.d.ts +16 -0
  216. package/dist/lib/utils/zod.d.ts.map +1 -1
  217. package/dist/lib/utils/zod.js +45 -0
  218. package/dist/lib/utils/zod.js.map +1 -1
  219. package/dist/schema/constants.d.ts +56 -2
  220. package/dist/schema/constants.d.ts.map +1 -1
  221. package/dist/schema/constants.js +82 -7
  222. package/dist/schema/constants.js.map +1 -1
  223. package/dist/schema/schemas/agent-env.d.ts +187 -7
  224. package/dist/schema/schemas/agent-env.d.ts.map +1 -1
  225. package/dist/schema/schemas/agent-env.js +323 -27
  226. package/dist/schema/schemas/agent-env.js.map +1 -1
  227. package/dist/schema/schemas/agentcore-project.d.ts +519 -12
  228. package/dist/schema/schemas/agentcore-project.d.ts.map +1 -1
  229. package/dist/schema/schemas/agentcore-project.js +342 -13
  230. package/dist/schema/schemas/agentcore-project.js.map +1 -1
  231. package/dist/schema/schemas/auth.d.ts +174 -0
  232. package/dist/schema/schemas/auth.d.ts.map +1 -1
  233. package/dist/schema/schemas/auth.js +127 -3
  234. package/dist/schema/schemas/auth.js.map +1 -1
  235. package/dist/schema/schemas/aws-targets.d.ts +18 -0
  236. package/dist/schema/schemas/aws-targets.d.ts.map +1 -1
  237. package/dist/schema/schemas/aws-targets.js +6 -0
  238. package/dist/schema/schemas/aws-targets.js.map +1 -1
  239. package/dist/schema/schemas/connections.d.ts +185 -0
  240. package/dist/schema/schemas/connections.d.ts.map +1 -0
  241. package/dist/schema/schemas/connections.js +176 -0
  242. package/dist/schema/schemas/connections.js.map +1 -0
  243. package/dist/schema/schemas/deployed-state.d.ts +392 -5
  244. package/dist/schema/schemas/deployed-state.d.ts.map +1 -1
  245. package/dist/schema/schemas/deployed-state.js +112 -2
  246. package/dist/schema/schemas/deployed-state.js.map +1 -1
  247. package/dist/schema/schemas/index.d.ts +3 -0
  248. package/dist/schema/schemas/index.d.ts.map +1 -1
  249. package/dist/schema/schemas/index.js +5 -0
  250. package/dist/schema/schemas/index.js.map +1 -1
  251. package/dist/schema/schemas/mcp-defs.d.ts +2 -1
  252. package/dist/schema/schemas/mcp-defs.d.ts.map +1 -1
  253. package/dist/schema/schemas/mcp-defs.js +3 -2
  254. package/dist/schema/schemas/mcp-defs.js.map +1 -1
  255. package/dist/schema/schemas/mcp.d.ts +197 -0
  256. package/dist/schema/schemas/mcp.d.ts.map +1 -1
  257. package/dist/schema/schemas/mcp.js +334 -5
  258. package/dist/schema/schemas/mcp.js.map +1 -1
  259. package/dist/schema/schemas/primitives/ab-test.d.ts +135 -0
  260. package/dist/schema/schemas/primitives/ab-test.d.ts.map +1 -0
  261. package/dist/schema/schemas/primitives/ab-test.js +95 -0
  262. package/dist/schema/schemas/primitives/ab-test.js.map +1 -0
  263. package/dist/schema/schemas/primitives/capacity-provider.d.ts +237 -0
  264. package/dist/schema/schemas/primitives/capacity-provider.d.ts.map +1 -0
  265. package/dist/schema/schemas/primitives/capacity-provider.js +220 -0
  266. package/dist/schema/schemas/primitives/capacity-provider.js.map +1 -0
  267. package/dist/schema/schemas/primitives/config-bundle.d.ts +32 -0
  268. package/dist/schema/schemas/primitives/config-bundle.d.ts.map +1 -0
  269. package/dist/schema/schemas/primitives/config-bundle.js +41 -0
  270. package/dist/schema/schemas/primitives/config-bundle.js.map +1 -0
  271. package/dist/schema/schemas/primitives/dataset.d.ts +48 -0
  272. package/dist/schema/schemas/primitives/dataset.d.ts.map +1 -0
  273. package/dist/schema/schemas/primitives/dataset.js +58 -0
  274. package/dist/schema/schemas/primitives/dataset.js.map +1 -0
  275. package/dist/schema/schemas/primitives/evaluator.d.ts +22 -0
  276. package/dist/schema/schemas/primitives/evaluator.d.ts.map +1 -1
  277. package/dist/schema/schemas/primitives/evaluator.js +28 -3
  278. package/dist/schema/schemas/primitives/evaluator.js.map +1 -1
  279. package/dist/schema/schemas/primitives/harness.d.ts +377 -19
  280. package/dist/schema/schemas/primitives/harness.d.ts.map +1 -1
  281. package/dist/schema/schemas/primitives/harness.js +379 -24
  282. package/dist/schema/schemas/primitives/harness.js.map +1 -1
  283. package/dist/schema/schemas/primitives/index.d.ts +17 -9
  284. package/dist/schema/schemas/primitives/index.d.ts.map +1 -1
  285. package/dist/schema/schemas/primitives/index.js +62 -1
  286. package/dist/schema/schemas/primitives/index.js.map +1 -1
  287. package/dist/schema/schemas/primitives/knowledge-base.d.ts +104 -0
  288. package/dist/schema/schemas/primitives/knowledge-base.d.ts.map +1 -0
  289. package/dist/schema/schemas/primitives/knowledge-base.js +99 -0
  290. package/dist/schema/schemas/primitives/knowledge-base.js.map +1 -0
  291. package/dist/schema/schemas/primitives/memory.d.ts +22 -4
  292. package/dist/schema/schemas/primitives/memory.d.ts.map +1 -1
  293. package/dist/schema/schemas/primitives/memory.js +57 -16
  294. package/dist/schema/schemas/primitives/memory.js.map +1 -1
  295. package/dist/schema/schemas/primitives/online-eval-config.d.ts +21 -2
  296. package/dist/schema/schemas/primitives/online-eval-config.d.ts.map +1 -1
  297. package/dist/schema/schemas/primitives/online-eval-config.js +45 -5
  298. package/dist/schema/schemas/primitives/online-eval-config.js.map +1 -1
  299. package/dist/schema/schemas/primitives/payment.d.ts +86 -0
  300. package/dist/schema/schemas/primitives/payment.d.ts.map +1 -0
  301. package/dist/schema/schemas/primitives/payment.js +88 -0
  302. package/dist/schema/schemas/primitives/payment.js.map +1 -0
  303. package/dist/schema/schemas/primitives/policy.d.ts +26 -0
  304. package/dist/schema/schemas/primitives/policy.d.ts.map +1 -1
  305. package/dist/schema/schemas/primitives/policy.js +5 -1
  306. package/dist/schema/schemas/primitives/policy.js.map +1 -1
  307. package/npm-shrinkwrap.json +16874 -0
  308. package/package.json +49 -21
  309. package/scripts/bump-version.ts +4 -4
  310. package/scripts/bundle.mjs +70 -41
  311. package/scripts/extract-cli-model.mjs +269 -0
  312. package/scripts/extract-cli-model.test.mjs +43 -0
  313. package/scripts/render_adoc.py +350 -0
  314. package/scripts/run-e2e-dev.sh +56 -0
  315. package/scripts/run-e2e-local.sh +145 -0
  316. package/scripts/safe-junit-reporter.ts +7 -0
  317. package/scripts/sanitize-test-artifacts.ts +65 -0
  318. package/scripts/sync-vended-cdk.ts +49 -0
  319. package/scripts/test_render_adoc.py +38 -0
  320. package/dist/lib/errors/config.d.ts +0 -49
  321. package/dist/lib/errors/config.d.ts.map +0 -1
  322. package/dist/lib/errors/config.js.map +0 -1
  323. package/dist/lib/packaging/errors.d.ts +0 -16
  324. package/dist/lib/packaging/errors.d.ts.map +0 -1
  325. package/dist/lib/packaging/errors.js +0 -36
  326. package/dist/lib/packaging/errors.js.map +0 -1
  327. package/dist/lib/schemas/io/cli-config.d.ts +0 -12
  328. package/dist/lib/schemas/io/cli-config.d.ts.map +0 -1
  329. package/dist/lib/schemas/io/cli-config.js +0 -35
  330. 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
- {{#if sessionStorageMountPath}}
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
- # Define a Streamable HTTP MCP Client
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 = get_all_gateway_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
- {{#if sessionStorageMountPath}}
37
- SESSION_STORAGE_PATH = "{{sessionStorageMountPath}}"
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
- """Resolve path safely within the storage boundary."""
41
- resolved = os.path.realpath(os.path.join(SESSION_STORAGE_PATH, path.lstrip("/")))
42
- if not resolved.startswith(os.path.realpath(SESSION_STORAGE_PATH)):
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 persistent storage. The path is relative to the storage root."""
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 content to a file in persistent storage. The path is relative to the storage root."""
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,403 @@ 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(directory: str = "") -> str:
76
- """List files in persistent storage. The directory is relative to the storage root."""
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
- target = _safe_resolve(directory)
79
- entries = os.listdir(target)
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 '{directory}': {e.strerror}"
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
- key = f"{session_id}/{user_id}"
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, user_id),
111
- system_prompt=SYSTEM_PROMPT,
112
- tools=tools
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
- _agent = None
119
-
120
- def get_or_create_agent():
121
- global _agent
122
- if _agent is None:
123
- _agent = Agent(
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=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
- return _agent
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 strip_trailing_tool_use(messages: Any) -> list[dict]:
485
+ """Strip toolUse blocks from the tail until the last message has none."""
486
+ if not isinstance(messages, list):
487
+ raise ValueError("messages must be a list")
488
+
489
+ messages = list(messages)
490
+ while messages:
491
+ last = messages[-1]
492
+ if not isinstance(last, dict):
493
+ raise ValueError("each message must be an object")
494
+ original_content = last.get("content", [])
495
+ if not isinstance(original_content, list) or not all(isinstance(block, dict) for block in original_content):
496
+ raise ValueError("each message content value must be a list of content blocks")
497
+
498
+ content = [block for block in original_content if "toolUse" not in block]
499
+ if len(content) == len(original_content):
500
+ break
501
+ if content:
502
+ messages[-1] = {**last, "content": content}
503
+ break
504
+ messages.pop()
505
+
506
+ return messages
507
+
508
+
509
+ def _extract_prompt(payload: dict):
510
+ """Accept validated harness messages, tool results, or a plain prompt string."""
511
+ if not isinstance(payload, dict):
512
+ raise ValueError("payload must be a JSON object")
513
+ if "messages" in payload:
514
+ return strip_trailing_tool_use(payload["messages"])
515
+ if "tool_results" in payload:
516
+ tool_results = payload["tool_results"]
517
+ if not isinstance(tool_results, list) or not all(
518
+ isinstance(tool_result, dict) and isinstance(tool_result.get("toolUseId"), str)
519
+ for tool_result in tool_results
520
+ ):
521
+ raise ValueError("tool_results must contain objects with a toolUseId string")
522
+ return [{"role": "user", "content": [{"toolResult": {
523
+ "toolUseId": tr["toolUseId"],
524
+ "status": tr.get("status", "success"),
525
+ "content": tr.get("content", []),
526
+ }} for tr in tool_results]}]
527
+ prompt = payload.get("prompt", "")
528
+ if not isinstance(prompt, str):
529
+ raise ValueError("prompt must be a string")
530
+ return prompt
531
+
532
+
533
+ def _has_inline_function_call(messages) -> bool:
534
+ """Return True if messages contains an assistant toolUse for an inline function tool."""
535
+ if not _INLINE_FUNCTION_NAMES or not isinstance(messages, list):
536
+ return False
537
+ for msg in messages:
538
+ if msg.get("role") == "assistant":
539
+ for block in msg.get("content", []):
540
+ if isinstance(block, dict) and block.get("toolUse", {}).get("name") in _INLINE_FUNCTION_NAMES:
541
+ return True
542
+ return False
543
+
544
+
545
+ def _is_inline_function_call(event: dict) -> bool:
546
+ """Check if a contentBlockStart event is for an inline function tool."""
547
+ if not _INLINE_FUNCTION_NAMES:
548
+ return False
549
+ cbs = event.get("contentBlockStart", {})
550
+ start = cbs.get("start", {})
551
+ tool_use = start.get("toolUse") if isinstance(start, dict) else None
552
+ return tool_use is not None and tool_use.get("name") in _INLINE_FUNCTION_NAMES
553
+
554
+
555
+
132
556
  @app.entrypoint
133
557
  async def invoke(payload, context):
134
558
  log.info("Invoking Agent.....")
135
559
 
560
+ {{#if hasPayment}}
561
+ user_id = payload.get("user_id") or getattr(context, "user_id", "default-user")
562
+ instrument_id = payload.get("payment_instrument_id")
563
+ session_id = payload.get("payment_session_id")
564
+ payments_plugin = create_payments_plugin(user_id, instrument_id, session_id)
565
+ plugins = [payments_plugin] if payments_plugin else []
566
+ {{/if}}
567
+ {{#if hasSkillsFetcher}}
568
+ skill_paths = [{{#each pathSkills}}{{safeJson this}}{{#unless @last}}, {{/unless}}{{/each}}]
569
+ {{#if s3Skills}}
570
+ s3_skill_sources = [{{#each s3Skills}}{{safeJson this}}{{#unless @last}}, {{/unless}}{{/each}}]
571
+ skill_paths.extend(await asyncio.to_thread(resolve_s3_skills, s3_skill_sources, None))
572
+ {{/if}}
573
+ {{#if gitSkills}}
574
+ git_skill_sources = [
575
+ {{#each gitSkills}}
576
+ 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}}),
577
+ {{/each}}
578
+ ]
579
+ {{#if (some gitSkills "credentialArn")}}
580
+ _git_identity_client = IdentityClient(os.environ.get("AWS_REGION", os.environ.get("AWS_DEFAULT_REGION", "us-east-1")))
581
+ {{else}}
582
+ _git_identity_client = None
583
+ {{/if}}
584
+ skill_paths.extend(await asyncio.to_thread(resolve_git_skills, git_skill_sources, _git_identity_client))
585
+ {{/if}}
586
+ _skill_plugins = [AgentSkills(skills=skill_paths)] if skill_paths else []
587
+ {{/if}}
588
+
136
589
  {{#if hasMemory}}
590
+ {{#if hasPayment}}
591
+ mem_session_id = getattr(context, 'session_id', 'default-session')
592
+ {{#if actorId}}
593
+ mem_user_id = "{{actorId}}"
594
+ {{else}}
595
+ mem_user_id = getattr(context, 'user_id', 'default-user')
596
+ {{/if}}
597
+ agent = Agent(
598
+ model=load_model(),
599
+ session_manager=get_memory_session_manager(mem_session_id, mem_user_id),
600
+ system_prompt=DEFAULT_SYSTEM_PROMPT + PAYMENT_SYSTEM_PROMPT,
601
+ tools=tools,
602
+ plugins=plugins{{#if hasSkillsFetcher}} + _skill_plugins{{/if}},{{#if hasConfigBundle}}
603
+ hooks=[ConfigBundleHook()],{{/if}}
604
+ )
605
+ {{else}}
137
606
  session_id = getattr(context, 'session_id', 'default-session')
607
+ {{#if actorId}}
608
+ user_id = "{{actorId}}"
609
+ {{else}}
138
610
  user_id = getattr(context, 'user_id', 'default-user')
139
- agent = get_or_create_agent(session_id, user_id)
611
+ {{/if}}
612
+ agent = get_or_create_agent(session_id, user_id{{#if hasSkillsFetcher}}, _skill_plugins{{/if}})
613
+ {{/if}}
140
614
  {{else}}
141
- agent = get_or_create_agent()
615
+ {{#if hasPayment}}
616
+ agent = Agent(
617
+ model=load_model(),
618
+ system_prompt=DEFAULT_SYSTEM_PROMPT + PAYMENT_SYSTEM_PROMPT,
619
+ tools=tools,
620
+ plugins=plugins{{#if hasSkillsFetcher}} + _skill_plugins{{/if}},{{#if hasConfigBundle}}
621
+ hooks=[ConfigBundleHook()],{{/if}}
622
+ )
623
+ {{else}}
624
+ session_id = getattr(context, 'session_id', 'default-session')
625
+ agent = get_or_create_agent(session_id{{#if hasSkillsFetcher}}, _skill_plugins{{/if}})
142
626
  {{/if}}
627
+ {{/if}}
628
+
629
+ prompt = _extract_prompt(payload)
143
630
 
144
- # Execute and format response
145
- stream = agent.stream_async(payload.get("prompt"))
631
+ {{#if inlineFunctionTools}}
632
+ # If Turn 2 carries the harness-style assistant(toolUse)+user(toolResult) pair,
633
+ # strip the placeholder turn Strands stored during Turn 1 so the real toolResult
634
+ # is injected cleanly — same protocol as the harness runtime.
635
+ if _has_inline_function_call(prompt):
636
+ msgs = agent.messages
637
+ if len(msgs) >= 2 and any("toolResult" in b for b in msgs[-1].get("content", [])):
638
+ del msgs[-2:]
639
+ {{/if}}
640
+
641
+ {{#if hasExecutionLimits}}
642
+ timeout_seconds = {{#if timeoutSeconds}}{{timeoutSeconds}}{{else}}None{{/if}}
643
+ timeout_fired = False
644
+ watchdog_task = None
645
+ if timeout_seconds is not None:
646
+ async def _timeout_watchdog():
647
+ nonlocal timeout_fired
648
+ await asyncio.sleep(timeout_seconds)
649
+ timeout_fired = True
650
+ agent.cancel()
651
+ watchdog_task = asyncio.create_task(_timeout_watchdog())
652
+
653
+ try:
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}}
146
674
 
147
- async for event in stream:
148
- # Handle Text parts of the response
149
- if "data" in event and isinstance(event["data"], str):
150
- yield event["data"]
675
+ if timeout_fired:
676
+ yield {"event": {"messageStop": {"stopReason": "timeout_exceeded"}}}
677
+ except EventLoopException as e:
678
+ if isinstance(e.original_exception, ExecutionLimitExceeded):
679
+ yield {"event": {"messageStop": {"stopReason": str(e.original_exception)}}}
680
+ return
681
+ raise
682
+ finally:
683
+ if watchdog_task is not None:
684
+ watchdog_task.cancel()
685
+ try:
686
+ await watchdog_task
687
+ except asyncio.CancelledError:
688
+ pass
689
+ {{else}}
690
+ {{#if inlineFunctionTools}}
691
+ hit_inline_function = False
692
+ {{/if}}
693
+ async for event in agent.stream_async(
694
+ prompt,
695
+ ):
696
+ if not isinstance(event, dict) or "event" not in event:
697
+ continue
698
+ cbs = event["event"].get("contentBlockStart")
699
+ if cbs is not None and not cbs.get("start"):
700
+ continue
701
+ {{#if inlineFunctionTools}}
702
+ if not hit_inline_function:
703
+ hit_inline_function = _is_inline_function_call(event["event"])
704
+ {{/if}}
705
+ yield event
706
+ {{#if inlineFunctionTools}}
707
+ if hit_inline_function and "messageStop" in event["event"]:
708
+ return
709
+ {{/if}}
710
+ {{/if}}
151
711
 
152
712
 
153
713
  if __name__ == "__main__":