@aws/nx-plugin 1.0.0-rc.71 → 1.0.0-rc.72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/migrations.json +6 -1
- package/package.json +1 -1
- package/src/agentcore-harness/generator.d.ts +1 -1
- package/src/infra/app/generator.d.ts +1 -1
- package/src/init/generator.d.ts +1 -1
- package/src/license/dependency-check/evaluator.js +55 -10
- package/src/license/dependency-check/evaluator.js.map +1 -1
- package/src/migrations/latest/py-agent-session-management-support/metadata.json +3 -0
- package/src/migrations/latest/py-agent-session-management-support/migration.d.ts +2 -0
- package/src/migrations/latest/py-agent-session-management-support/migration.js +308 -0
- package/src/migrations/latest/py-agent-session-management-support/migration.js.map +1 -0
- package/src/preset/generator.d.ts +1 -1
- package/src/py/agent/__snapshots__/generator.constructs.spec.ts.snap +615 -6
- package/src/py/agent/__snapshots__/generator.core.spec.ts.snap +186 -0
- package/src/py/agent/__snapshots__/generator.frameworks.spec.ts.snap +47 -3
- package/src/py/agent/__snapshots__/generator.protocols.spec.ts.snap +667 -2
- package/src/py/agent/files/langchain/common/__init__.py.template +0 -0
- package/src/py/agent/files/langchain/common/agent.py.template +3 -3
- package/src/py/agent/files/langchain/common/session.py.template +61 -0
- package/src/py/agent/files/strands/ag-ui/main.py.template +5 -1
- package/src/py/agent/files/strands/common/agent.py.template +9 -2
- package/src/py/agent/files/strands/common/session.py.template +36 -0
- package/src/py/agent/generator.d.ts +11 -1
- package/src/py/agent/generator.js +78 -28
- package/src/py/agent/generator.js.map +1 -1
- package/src/py/agent/mcp-connection/__snapshots__/generator.spec.ts.snap +2 -0
- package/src/py/agent/react-connection/generator.d.ts +1 -1
- package/src/py/agent/schema.d.js.map +1 -1
- package/src/py/agent/schema.d.ts +1 -1
- package/src/py/agent/schema.json +3 -3
- package/src/py/fast-api/react/generator.d.ts +1 -1
- package/src/smithy/project/generator.d.ts +1 -1
- package/src/smithy/react-connection/generator.d.ts +1 -1
- package/src/terraform/project/generator.d.ts +1 -1
- package/src/trpc/react/generator.d.ts +1 -1
- package/src/ts/agent/__snapshots__/generator.spec.ts.snap +27 -6
- package/src/ts/agent/a2a-connection/generator.d.ts +1 -1
- package/src/ts/agent/gateway-connection/generator.d.ts +1 -1
- package/src/ts/agent/mcp-connection/generator.d.ts +1 -1
- package/src/ts/agent/react-connection/generator.d.ts +1 -1
- package/src/ts/astro-docs/generator.d.ts +1 -1
- package/src/ts/dcr-proxy/generator.d.ts +1 -1
- package/src/ts/dynamodb/generator.d.ts +1 -1
- package/src/ts/lambda-function/generator.d.ts +1 -1
- package/src/ts/lib/generator.d.ts +1 -1
- package/src/ts/nx-generator/generator.d.ts +1 -1
- package/src/ts/nx-migration/generator.d.ts +1 -1
- package/src/ts/nx-plugin/generator.d.ts +1 -1
- package/src/ts/rdb/generator.d.ts +1 -1
- package/src/ts/react-website/agui/generator.d.ts +1 -1
- package/src/utils/agent-connection/agent-connection.d.ts +10 -0
- package/src/utils/agent-connection/agent-connection.js +15 -0
- package/src/utils/agent-connection/agent-connection.js.map +1 -1
- package/src/utils/agent-connection/files/core-runtime-config/runtime-config.ts.template +5 -3
- package/src/utils/agent-connection/files/py-core-langchain/s3/s3_checkpoint_saver_langchain.py.template +360 -0
- package/src/utils/agent-connection/files/py-core-runtime-config/runtime_config.py.template +2 -4
- package/src/utils/agent-connection/files/py-core-strands/base/tool_errors_strands.py.template +24 -0
- package/src/utils/agent-core-constructs/agent-core-constructs.d.ts +1 -1
- package/src/utils/agent-core-constructs/agent-core-constructs.js.map +1 -1
- package/src/utils/agent-core-constructs/files/cdk/app/agent-core/__nameKebabCase__/__nameKebabCase__.ts.template +113 -13
- package/src/utils/agent-core-constructs/files/terraform/app/agent-core/__nameKebabCase__/__nameKebabCase__.tf.template +76 -7
- package/src/utils/versions.d.ts +3 -0
- package/src/utils/versions.js +3 -0
- package/src/utils/versions.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/agent-connection/agent-connection.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type Tree,\n} from '@nx/devkit';\nimport pyProjectGenerator, {\n getPyProjectDetails,\n} from '../../py/project/generator';\nimport tsProjectGenerator from '../../ts/lib/generator';\nimport { addStarExport, applyGritQL, matchGritQL } from '../ast';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n type MustDeclarePy,\n} from '../declared-dependencies';\nimport { addDependenciesToPackageJson } from '../dependencies';\nimport { esmVars } from '../module-format';\nimport { addDependenciesToPyProjectToml } from '../py';\nimport {\n type IPyDepVersion,\n type ITsDepVersion,\n withVersions,\n} from '../versions';\n\n/** TypeScript dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_DEPENDENCIES = [\n { name: '@aws-lambda-powertools/parameters' },\n { name: '@aws-sdk/credential-providers' },\n { name: 'aws4fetch' },\n { name: '@modelcontextprotocol/sdk' },\n { name: '@a2a-js/sdk' },\n { name: '@strands-agents/sdk' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\n/** Python dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_PY_DEPENDENCIES = [\n { name: 'aws-lambda-powertools' },\n { name: 'strands-agents' },\n] as const satisfies readonly { name: IPyDepVersion }[];\n\ntype AgentConnectionPyDependency =\n (typeof AGENT_CONNECTION_PY_DEPENDENCIES)[number]['name'];\n\n/** Prefix a GritQL pattern with `language python` */\nconst py = (pattern: string) => `language python\\n${pattern}`;\n\nconst AGENT_CONNECTION_DIR = 'agent-connection';\nconst PACKAGES_DIR = 'packages';\nconst COMMON_DIR = 'common';\n\nexport const AGENT_CONNECTION_PROJECT_DIR = joinPathFragments(\n PACKAGES_DIR,\n COMMON_DIR,\n AGENT_CONNECTION_DIR,\n);\n\nconst PY_AGENT_CONNECTION_NAME = 'agent_connection';\n\n/**\n * Get the directory of the shared Python agent-connection project.\n */\nexport function getPythonAgentConnectionProjectDir(tree: Tree): string {\n const { dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return dir;\n}\n\n/**\n * Get the Python module name of the shared agent-connection project.\n */\nexport function getPythonAgentConnectionModuleName(tree: Tree): string {\n const { normalizedModuleName } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return normalizedModuleName;\n}\n\n/**\n * Get the shared agent-connection project as `{ name, root }`, suitable for\n * passing to {@link addWorkspaceDependencyToPyProject} (which derives the\n * dependency's PEP 503 distribution name from the project itself, so callers\n * never construct the name).\n */\nexport function getPythonAgentConnectionProject(tree: Tree): {\n name: string;\n root: string;\n} {\n const { fullyQualifiedName, dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return { name: fullyQualifiedName, root: dir };\n}\n\n/**\n * The connection protocols an agent framework can connect over. Each maps to a\n * framework-agnostic Layer-0/1 template directory plus a per-framework Layer-2\n * client directory (see `FRAMEWORKS`).\n */\nexport type ConnectionProtocol = 'mcp' | 'gateway' | 'a2a';\n\n/**\n * The agent frameworks we can generate connection clients for. Adding a new\n * framework is an additive change: append an entry to `FRAMEWORKS` with its\n * Layer-2 template directories and dependencies — the framework-agnostic\n * Layer-0/1 (`core-auth`, `core-shared`, the per-protocol transports/configs)\n * is reused unchanged.\n */\nexport type AgentFramework = 'strands' | 'langchain';\n\n/**\n * Resolve an agent component's framework, defaulting to `strands`. Connection\n * generators dispatch on the returned framework to pick the matching templates\n * and agent.py/agent.ts transforms.\n */\nexport function resolveAgentFramework(\n framework: string | undefined,\n): AgentFramework {\n return framework === 'langchain' ? 'langchain' : 'strands';\n}\n\n/**\n * Framework-agnostic Layer-1 templates, keyed by protocol. These resolve the\n * endpoint and build the signed transport/client-config; they contain no\n * framework dependency.\n */\nconst TS_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'core-mcp',\n gateway: 'core-gateway',\n a2a: 'core-a2a',\n};\nconst PY_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'py-core-mcp',\n gateway: 'py-core-gateway',\n a2a: 'py-core-a2a',\n};\n\n/**\n * A re-export the framework base emits into the agent-connection module's\n * `__init__.py` (the agent server entry point imports these by name).\n */\ninterface BaseReExport {\n fromModule: string;\n importName: string;\n}\n\n/**\n * A framework's Layer-2 templates for one language. `base` (optional) holds the\n * helpers every connection of that framework needs (error logging, per-session\n * agent cache); `baseReExports` lists what those helpers expose at the module\n * root. `protocols` maps each *supported* protocol to the thin client that wraps\n * the matching Layer-1 transport/config in the framework's client type.\n *\n * A framework whose Layer-2 needs no base helpers (e.g. LangChain, whose AG-UI\n * foundation reuses only the framework-agnostic session context) omits `base`\n * and leaves `baseReExports` empty.\n *\n * A protocol absent from `protocols` is not supported by that framework in that\n * language — callers must check before emitting. `deps` are the extra package\n * dependencies the base helpers require (per-connection client deps are added\n * by the connection generators, not here).\n */\ninterface FrameworkLanguageTemplates<Dep extends string> {\n base?: string;\n baseReExports: BaseReExport[];\n protocols: Partial<Record<ConnectionProtocol, string>>;\n deps: Dep[];\n}\n\n/**\n * Per-framework Layer-2 templates. Support is asymmetric by design: a framework\n * may target only one language (`ts`/`py` is optional) and only a subset of\n * protocols. Adding a framework — or extending an existing one to a new\n * language/protocol — is an additive change to this registry.\n */\ninterface FrameworkTemplates {\n ts?: FrameworkLanguageTemplates<string>;\n py?: FrameworkLanguageTemplates<AgentConnectionPyDependency>;\n}\n\nconst FRAMEWORKS: Record<AgentFramework, FrameworkTemplates> = {\n strands: {\n ts: {\n base: 'core-strands/base',\n baseReExports: [\n {\n fromModule: './core/with-session-id-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/model-errors-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/tool-errors-strands.js',\n importName: '*',\n },\n ],\n protocols: {\n mcp: 'core-strands/mcp',\n gateway: 'core-strands/gateway',\n a2a: 'core-strands/a2a',\n },\n deps: [],\n },\n py: {\n base: 'py-core-strands/base',\n baseReExports: [\n {\n fromModule: '.core.with_session_id_strands',\n importName: 'with_session_id',\n },\n {\n fromModule: '.core.model_errors_strands',\n importName: 'log_model_errors',\n },\n ],\n protocols: {\n mcp: 'py-core-strands/mcp',\n gateway: 'py-core-strands/gateway',\n a2a: 'py-core-strands/a2a',\n },\n deps: ['strands-agents'],\n },\n },\n langchain: {\n // LangChain is supported for Python agents only (the TypeScript LangChain\n // agent foundation has no in-process AG-UI <-> LangGraph adapter, so it is\n // not scaffolded — see ts#agent). Its Layer-2 clients stay usable after\n // agent construction, so there is no base helper layer (no model-error\n // logger / per-session agent cache) and no strands-agents dependency — its\n // AG-UI foundation reuses only the framework-agnostic session context, and\n // its A2A client drives the a2a SDK directly rather than wrapping Strands'\n // A2AAgent. The per-connection adapter dependency (langchain-mcp-adapters /\n // a2a-sdk) is added by the connection generators.\n py: {\n baseReExports: [],\n protocols: {\n mcp: 'py-core-langchain/mcp',\n gateway: 'py-core-langchain/gateway',\n a2a: 'py-core-langchain/a2a',\n },\n deps: [],\n },\n },\n};\n\n/** Resolve a framework's templates for a language + protocol, or throw. */\nfunction frameworkLanguage<L extends 'ts' | 'py'>(\n framework: AgentFramework,\n language: L,\n protocol: ConnectionProtocol,\n): NonNullable<FrameworkTemplates[L]> & { protocol: string } {\n const lang = FRAMEWORKS[framework][language];\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n const protocolDir = lang.protocols[protocol];\n if (!protocolDir) {\n throw new Error(\n `The '${framework}' framework does not support ${protocol} connections for ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n return { ...lang, protocol: protocolDir } as NonNullable<\n FrameworkTemplates[L]\n > & { protocol: string };\n}\n\n/** Protocols whose Layer-1 needs the shared MCP transport (`core-shared`). */\nconst MCP_TRANSPORT_PROTOCOLS: ConnectionProtocol[] = ['mcp', 'gateway'];\n\nconst tsCoreDir = () =>\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'core');\n\n/**\n * Runtime dependencies each TypeScript core template directory imports. Emitting\n * a template also declares its dependencies in the agent-connection project's\n * package.json so the `noUndeclaredDependencies` lint rule passes.\n */\nconst TS_TEMPLATE_DEPS: Record<\n string,\n (typeof AGENT_CONNECTION_DEPENDENCIES)[number]['name'][]\n> = {\n 'core-runtime-config': ['@aws-lambda-powertools/parameters'],\n 'core-auth': ['@aws-sdk/credential-providers', 'aws4fetch'],\n 'core-shared': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-mcp': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-gateway': [\n '@aws-sdk/credential-providers',\n '@modelcontextprotocol/sdk',\n ],\n 'core-a2a': ['@aws-sdk/credential-providers', '@a2a-js/sdk'],\n 'core-strands/base': ['@strands-agents/sdk'],\n 'core-strands/mcp': ['@strands-agents/sdk'],\n 'core-strands/gateway': ['@strands-agents/sdk'],\n 'core-strands/a2a': ['@strands-agents/sdk'],\n};\n\nconst emitTs = (\n tree: Tree,\n templateDir: string,\n declaration: DependencyDeclaration,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n tsCoreDir(),\n { ...esmVars(tree) },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n const deps = TS_TEMPLATE_DEPS[templateDir];\n if (deps?.length) {\n addDependenciesToPackageJson(\n tree,\n withVersions(\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n deps,\n ),\n {},\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'package.json'),\n );\n }\n};\n\n/**\n * Ensure the shared TypeScript agent-connection project exists and has the\n * framework-agnostic core helpers (runtime-config loader, session context).\n * Per-connection generators emit their own protocol + framework client\n * templates via `addTypeScriptCoreClient`.\n */\nexport async function ensureTypeScriptAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n): Promise<void> {\n const projectJsonPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'project.json',\n );\n if (!tree.exists(projectJsonPath)) {\n await tsProjectGenerator(tree, {\n name: AGENT_CONNECTION_DIR,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n emitTs(tree, 'core-runtime-config', declaration);\n\n // Re-export session-context helpers so agent server entry points can set the\n // current session on each inbound request without pulling in internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/session-context.js',\n );\n\n // Re-export the runtime-config loader so agent server entry points can read\n // their own connected resources (e.g. session storage) without pulling in\n // internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/runtime-config.js',\n );\n}\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the agent-connection project and re-export them. The agent\n * server entry point imports these regardless of whether any connection client\n * is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addTypeScriptCoreClient`.\n */\nexport async function addTypeScriptFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].ts;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support TypeScript agents.`,\n );\n }\n if (lang.base) {\n emitTs(tree, lang.base, declaration);\n }\n\n const indexPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'src',\n 'index.ts',\n );\n for (const reExport of lang.baseReExports) {\n await addStarExport(tree, indexPath, reExport.fromModule);\n }\n}\n\n/**\n * Emit the TypeScript client templates for a connection protocol and agent\n * framework into the agent-connection project's `src/core/` directory. Safe to\n * call multiple times — `KeepExisting` preserves customised files.\n *\n * Layers emitted:\n * - Layer 0 `core-auth` (signed fetch + endpoint resolution) — always\n * - Layer 1 `core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addTypeScriptCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'ts', protocol);\n\n emitTs(tree, 'core-auth', declaration);\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitTs(tree, 'core-shared', declaration);\n }\n emitTs(tree, TS_PROTOCOL_TEMPLATES[protocol], declaration);\n\n // Framework Layer 2: base helpers (re-exported for the agent server) + the\n // thin protocol client.\n await addTypeScriptFrameworkBase(\n tree,\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n framework,\n );\n emitTs(tree, fw.protocol, declaration);\n}\n\n/**\n * Ensure the shared Python agent-connection project exists.\n * Only creates the project shell — per-connection generators are responsible\n * for emitting their own core client templates.\n */\nexport async function ensurePythonAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n): Promise<void> {\n const projectDir = getPythonAgentConnectionProjectDir(tree);\n const moduleName = getPythonAgentConnectionModuleName(tree);\n const projectJsonPath = joinPathFragments(projectDir, 'project.json');\n\n if (!tree.exists(projectJsonPath)) {\n // Create the Python project using the standard py#project generator\n await pyProjectGenerator(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n type: 'library',\n });\n }\n\n const moduleDir = joinPathFragments(projectDir, moduleName);\n\n // Ensure core/__init__.py exists\n const coreDir = joinPathFragments(moduleDir, 'core');\n if (!tree.exists(joinPathFragments(coreDir, '__init__.py'))) {\n tree.write(joinPathFragments(coreDir, '__init__.py'), '');\n }\n\n // Ensure app/__init__.py exists\n const appInitPath = joinPathFragments(moduleDir, 'app', '__init__.py');\n if (!tree.exists(appInitPath)) {\n tree.write(appInitPath, '');\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'py-core-runtime-config'),\n coreDir,\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Re-export the session id context so agent server entry points can set the\n // current session on each inbound request without importing internals.\n const moduleInitPath = joinPathFragments(moduleDir, '__init__.py');\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'get_current_session_id',\n );\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'session_id_context',\n );\n\n // The runtime-config loader reads AppConfig via aws-lambda-powertools.\n addDependenciesToPyProjectToml(\n tree,\n projectDir,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n ['aws-lambda-powertools'],\n );\n}\n\nconst pyCoreDir = (tree: Tree) =>\n joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n 'core',\n );\n\nconst emitPy = (tree: Tree, templateDir: string) =>\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n pyCoreDir(tree),\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the Python agent-connection project and re-export them.\n * The agent server entry point imports these regardless of whether a connection\n * client is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addPythonCoreClient`.\n */\nexport async function addPythonFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].py;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support Python agents.`,\n );\n }\n if (lang.base) {\n emitPy(tree, lang.base);\n }\n\n const moduleInitPath = joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n '__init__.py',\n );\n for (const reExport of lang.baseReExports) {\n await addPythonReExport(\n tree,\n moduleInitPath,\n reExport.fromModule,\n reExport.importName,\n );\n }\n\n if (lang.deps.length > 0) {\n addDependenciesToPyProjectToml(\n tree,\n getPythonAgentConnectionProjectDir(tree),\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n lang.deps,\n );\n }\n}\n\n/**\n * Emit the Python client templates for a connection protocol and agent\n * framework into the agent-connection project's core directory.\n *\n * Layers emitted:\n * - Layer 0 `py-core-auth` (SigV4 httpx.Auth, session auth, endpoints) — always\n * - Layer 1 `py-core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addPythonCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'py', protocol);\n\n emitPy(tree, 'py-core-auth');\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitPy(tree, 'py-core-shared');\n }\n emitPy(tree, PY_PROTOCOL_TEMPLATES[protocol]);\n\n // Framework Layer 2: base helpers + the thin protocol client.\n await addPythonFrameworkBase(\n tree,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n framework,\n );\n emitPy(tree, fw.protocol);\n}\n\n/**\n * Patch a TypeScript agent.ts to create a connection client and register it\n * in the Agent's tools. Used by the MCP and gateway connection generators —\n * the client class must expose a static async `create()` returning a value\n * accepted by `Agent.tools` (e.g. an `McpClient`).\n */\nexport async function addTypeScriptClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n const clientCreationStmt = `const ${clientVarName} = await ${clientClassName}.create();`;\n\n // Transform the arrow function that contains `new Agent`:\n // - Expression body: wrap in block with client creation and return\n // - Block body: prepend client creation statement\n await applyGritQL(\n tree,\n agentFilePath,\n `or { \\`async ($p) => new Agent($args)\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n return new Agent($args);\n}\\` where { $program <: not contains \\`${clientClassName}.create\\` }, \\`async ($p) => { $body }\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n $body\n}\\` where { $body <: contains \\`new Agent($_)\\`, $program <: not contains \\`${clientClassName}.create\\` } }`,\n );\n\n // Prepend the client to the tools array\n await applyGritQL(\n tree,\n agentFilePath,\n `\\`tools: [$items]\\` => \\`tools: [${clientVarName}, $items]\\` where { $items <: within \\`new Agent($_)\\`, $items <: not contains \\`${clientVarName}\\` }`,\n );\n}\n\n/**\n * Patch a Python agent.py to create a context-managed connection client,\n * enter it in the `with` block around `yield Agent(...)`, and spread its\n * `list_tools_sync()` into the Agent's tools. Used by the MCP and gateway\n * connection generators — the client class must expose a static `create()`\n * returning a context manager with `list_tools_sync()` (e.g. an `MCPClient`).\n */\nasync function addPythonClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonClientTools(tree, agentFilePath, clientVarName);\n await addPythonClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Append `*<clientVarName>.list_tools_sync()` to the Agent's tools list.\n */\nconst addPythonClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(\n tree,\n filePath,\n py(`\\`${clientVarName}.list_tools_sync()\\``),\n )\n ) {\n return;\n }\n\n await applyGritQL(\n tree,\n filePath,\n py(`\\`tools=$old\\` where {\n $old <: not contains \\`${clientVarName}\\`,\n if ($old <: \\`[]\\`) {\n $old => \\`[*${clientVarName}.list_tools_sync()]\\`\n } else {\n $old <: \\`[$items]\\` where { $items += \\`, *${clientVarName}.list_tools_sync()\\` }\n }\n}`),\n );\n};\n\n/**\n * Create the client in get_agent and enter it in the `with` block.\n *\n * First connection: rewrites `def get_agent` to wrap the body in a with\n * block. Subsequent connections: adds to the existing with items and\n * prepends the creation line.\n */\nconst addPythonClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n // Try the \"add to existing with block\" pattern first.\n // If it succeeds, there was already a with block from a previous connection.\n const addedToWith = await applyGritQL(\n tree,\n filePath,\n py(`\\`with ($items,): $body\\` where {\n $items <: not contains \\`${clientVarName}\\`,\n $items += \\`, ${clientVarName}\\`\n}`),\n );\n\n if (addedToWith) {\n // Subsequent connection — prepend the creation line to the function body\n // (a single anchor, so the line is inserted exactly once).\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n return;\n }\n\n // First connection — wrap the existing `def get_agent` body in a single\n // `with (<var>,):` block.\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n with (\n ${clientVarName},\n ):\n $body\\``),\n );\n};\n\n/**\n * Patch a LangChain agent.py to load connection tools and spread them into the\n * `create_agent(...)` tools list. Used by the MCP and gateway connection\n * generators when the source agent uses the `langchain` framework — the client\n * class must expose a static `create()` returning a `list[BaseTool]`. The tools\n * come from langchain-mcp-adapters' `MultiServerMCPClient`, which keeps the\n * connection config on each tool and opens a fresh MCP session per call, so the\n * tools stay usable after `get_agent` returns — no `with` block is needed.\n * Mirrors {@link addPythonClientToAgent} for the Strands shape.\n */\nasync function addPythonLangchainClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonLangchainClientTools(tree, agentFilePath, clientVarName);\n await addPythonLangchainClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Spread `*<clientVarName>` into the `create_agent(...)` tools list.\n *\n * Scoped via `$old <: within \\`create_agent($_)\\`` so only the agent's own\n * tools= keyword argument is touched (not an unrelated function with a\n * `tools=` parameter).\n */\nconst addPythonLangchainClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n await applyGritQL(\n tree,\n filePath,\n py(`\\`tools=$old\\` where {\n $old <: within \\`create_agent($_)\\`,\n $old <: not contains \\`*${clientVarName}\\`,\n if ($old <: \\`[]\\`) {\n $old => \\`[*${clientVarName}]\\`\n } else {\n $old <: \\`[$items]\\` where { $items += \\`, *${clientVarName}\\` }\n }\n}`),\n );\n};\n\n/**\n * Prepend `<clientVarName> = <clientClassName>.create()` to the get_agent body\n * (which loads the connection's tools). No `with` block — the LangChain client\n * hands langchain-mcp-adapters a connection config, so each tool opens its own\n * MCP session per call and the tools are safe to use after get_agent returns.\n * Idempotent via the `not contains <clientClassName>.create` guard.\n */\nconst addPythonLangchainClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`create_agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n};\n\n/**\n * Per-framework naming + template layout for a Python per-connection client.\n * Every py#agent connection generator (mcp, gateway, a2a) names its client\n * class `<Name>Client<suffix>`, its module `<name>_client_<suffix>`, and reads\n * the per-connection app-client template from a per-framework sub-path of its\n * own `files/` dir — all of which vary only by framework, so they live here as\n * one source of truth.\n *\n * Keyed by {@link AgentFramework} rather than a boolean so a third framework is\n * an additive entry here — never another `if (isLangchain)` branch in each\n * generator.\n */\nexport interface PyClientNaming {\n /** Class-name suffix on the per-connection app client (`<Name>Client<suffix>`). */\n clientClassSuffix: string;\n /** Module/file-name suffix on the per-connection app client (`<name>_client_<suffix>`). */\n clientModuleSuffix: string;\n /**\n * Sub-path, under a connection generator's `files/` dir, of the per-connection\n * app client template for this framework. Every connection generator lays its\n * templates out the same way, so this resolves against any of them.\n */\n appTemplateSubdir: string;\n}\n\nexport const PY_CLIENT_NAMING: Record<AgentFramework, PyClientNaming> = {\n strands: {\n clientClassSuffix: 'Strands',\n clientModuleSuffix: 'strands',\n appTemplateSubdir: joinPathFragments('agent-connection', 'app'),\n },\n langchain: {\n clientClassSuffix: 'LangChain',\n clientModuleSuffix: 'langchain',\n appTemplateSubdir: joinPathFragments(\n 'langchain',\n 'agent-connection',\n 'app',\n ),\n },\n};\n\n/**\n * How an MCP-family connection (an MCP server or an AgentCore Gateway, both of\n * which expose tools over MCP) is wired into a Python agent of a given\n * framework. The mcp-connection and gateway-connection generators share this:\n * they differ only in the metadata of the thing being connected, not in how\n * the framework's client is shaped or spliced into agent.py. A2A connections\n * wire tools differently, so they reuse only {@link PY_CLIENT_NAMING}.\n */\nexport interface PyMcpFamilyConnection extends PyClientNaming {\n /** Extra Python deps this framework's MCP-family client needs (beyond the shared transport). */\n deps: IPyDepVersion[];\n /**\n * Splice the per-connection client into the agent's `get_agent` in agent.py.\n * Strands enters a context-managed `MCPClient` and spreads `list_tools_sync()`;\n * LangChain loads `BaseTool`s and spreads them into `create_agent(...)`.\n */\n wireClientIntoAgent: (\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n ) => Promise<void>;\n}\n\nexport const PY_MCP_FAMILY_CONNECTIONS: Record<\n AgentFramework,\n PyMcpFamilyConnection\n> = {\n strands: {\n ...PY_CLIENT_NAMING.strands,\n deps: [],\n wireClientIntoAgent: addPythonClientToAgent,\n },\n langchain: {\n ...PY_CLIENT_NAMING.langchain,\n // langchain-mcp-adapters backs the LangChain client; it must not pull Strands in.\n deps: ['langchain-mcp-adapters'],\n wireClientIntoAgent: addPythonLangchainClientToAgent,\n },\n};\n\n/**\n * Add a re-export to the Python agent-connection module's __init__.py.\n * Equivalent to addStarExport for TS.\n * Uses `__all__` to mark re-exports as public (satisfies ruff F401).\n * Uses GritQL for AST-aware transforms where possible.\n */\nexport async function addPythonReExport(\n tree: Tree,\n initFilePath: string,\n fromModule: string,\n importName: string,\n): Promise<void> {\n // Check if already exported\n if (await matchGritQL(tree, initFilePath, `\\`${importName}\\``)) {\n return;\n }\n\n const importLine = `from ${fromModule} import ${importName}`;\n const allEntry = `\"${importName}\"`;\n\n // If there's already an import from the same module, merge into its name list\n // (ruff I001 rejects two `from X import ...` lines for the same module).\n const mergedImport = await applyGritQL(\n tree,\n initFilePath,\n py(`\\`from ${fromModule} import $names\\` where {\n $names <: not contains \\`${importName}\\`,\n $names += \\`, ${importName}\\`\n}`),\n );\n\n if (mergedImport) {\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // Try to append import after existing import using +=\n const appendedImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`from $mod import $name\\` as $stmt where {\n $program <: not contains \\`${importName}\\`,\n $stmt += \\`\\n${importLine}\\`\n}`,\n ),\n );\n\n if (appendedImport) {\n // Also append to existing __all__\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // No existing imports — first re-export. Try to anchor after docstring.\n const anchoredImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`\"\"\"Automatically generated by Nx.\"\"\"\\` as $doc => \\`$doc\\n${importLine}\\n\\n__all__ = [${allEntry}]\\``,\n ),\n );\n\n if (!anchoredImport) {\n // Completely empty file or no docstring — write directly\n tree.write(initFilePath, `${importLine}\\n\\n__all__ = [${allEntry}]\\n`);\n }\n}\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","pyProjectGenerator","getPyProjectDetails","tsProjectGenerator","addStarExport","applyGritQL","matchGritQL","forDependencies","addDependenciesToPackageJson","esmVars","addDependenciesToPyProjectToml","withVersions","AGENT_CONNECTION_DEPENDENCIES","name","AGENT_CONNECTION_PY_DEPENDENCIES","py","pattern","AGENT_CONNECTION_DIR","PACKAGES_DIR","COMMON_DIR","AGENT_CONNECTION_PROJECT_DIR","PY_AGENT_CONNECTION_NAME","getPythonAgentConnectionProjectDir","tree","dir","directory","getPythonAgentConnectionModuleName","normalizedModuleName","getPythonAgentConnectionProject","fullyQualifiedName","root","resolveAgentFramework","framework","TS_PROTOCOL_TEMPLATES","mcp","gateway","a2a","PY_PROTOCOL_TEMPLATES","FRAMEWORKS","strands","ts","base","baseReExports","fromModule","importName","protocols","deps","langchain","frameworkLanguage","language","protocol","lang","Error","protocolDir","MCP_TRANSPORT_PROTOCOLS","tsCoreDir","TS_TEMPLATE_DEPS","emitTs","templateDir","declaration","dirname","overwriteStrategy","KeepExisting","length","ensureTypeScriptAgentConnectionProject","projectJsonPath","exists","addTypeScriptFrameworkBase","indexPath","reExport","addTypeScriptCoreClient","fw","includes","ensurePythonAgentConnectionProject","projectDir","moduleName","type","moduleDir","coreDir","write","appInitPath","moduleInitPath","addPythonReExport","pyCoreDir","emitPy","addPythonFrameworkBase","addPythonCoreClient","addTypeScriptClientToAgent","agentFilePath","clientClassName","clientVarName","clientCreationStmt","addPythonClientToAgent","addPythonClientTools","addPythonClientToGetAgent","filePath","addedToWith","addPythonLangchainClientToAgent","addPythonLangchainClientTools","addPythonLangchainClientToGetAgent","PY_CLIENT_NAMING","clientClassSuffix","clientModuleSuffix","appTemplateSubdir","PY_MCP_FAMILY_CONNECTIONS","wireClientIntoAgent","initFilePath","importLine","allEntry","mergedImport","appendedImport","anchoredImport"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QAEZ,aAAa;AACpB,OAAOC,sBACLC,mBAAmB,QACd,gCAA6B;AACpC,OAAOC,wBAAwB,4BAAyB;AACxD,SAASC,aAAa,EAAEC,WAAW,EAAEC,WAAW,QAAQ,YAAS;AACjE,SAEEC,eAAe,QAGV,8BAA2B;AAClC,SAASC,4BAA4B,QAAQ,qBAAkB;AAC/D,SAASC,OAAO,QAAQ,sBAAmB;AAC3C,SAASC,8BAA8B,QAAQ,WAAQ;AACvD,SAGEC,YAAY,QACP,iBAAc;AAErB,oFAAoF,GACpF,OAAO,MAAMC,gCAAgC;IAC3C;QAAEC,MAAM;IAAoC;IAC5C;QAAEA,MAAM;IAAgC;IACxC;QAAEA,MAAM;IAAY;IACpB;QAAEA,MAAM;IAA4B;IACpC;QAAEA,MAAM;IAAc;IACtB;QAAEA,MAAM;IAAsB;CAC/B,CAAuD;AAExD,gFAAgF,GAChF,OAAO,MAAMC,mCAAmC;IAC9C;QAAED,MAAM;IAAwB;IAChC;QAAEA,MAAM;IAAiB;CAC1B,CAAuD;AAKxD,mDAAmD,GACnD,MAAME,KAAK,CAACC,UAAoB,CAAC,iBAAiB,EAAEA,SAAS;AAE7D,MAAMC,uBAAuB;AAC7B,MAAMC,eAAe;A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+D,aAAa,CAAC,KAAK,EAAEhE,WAAW,QAAQ,EAAEC,YAAY;IAC5D,MAAMgE,WAAW,CAAC,CAAC,EAAEhE,WAAW,CAAC,CAAC;IAElC,8EAA8E;IAC9E,yEAAyE;IACzE,MAAMiE,eAAe,MAAMxG,YACzBkB,MACAmF,cACA3F,GAAG,CAAC,OAAO,EAAE4B,WAAW;2BACD,EAAEC,WAAW;gBACxB,EAAEA,WAAW;CAC5B,CAAC;IAGA,IAAIiE,cAAc;QAChB,MAAMxG,YACJkB,MACAmF,cACA3F,GAAG,CAAC,6CAA6C,EAAE6F,SAAS,IAAI,CAAC;QAEnE;IACF;IAEA,sDAAsD;IACtD,MAAME,iBAAiB,MAAMzG,YAC3BkB,MACAmF,cACA3F,GACE,CAAC;6BACsB,EAAE6B,WAAW;eAC3B,EAAE+D,WAAW;CAC3B,CAAC;IAIA,IAAIG,gBAAgB;QAClB,kCAAkC;QAClC,MAAMzG,YACJkB,MACAmF,cACA3F,GAAG,CAAC,6CAA6C,EAAE6F,SAAS,IAAI,CAAC;QAEnE;IACF;IAEA,wEAAwE;IACxE,MAAMG,iBAAiB,MAAM1G,YAC3BkB,MACAmF,cACA3F,GACE,CAAC,4DAA4D,EAAE4F,WAAW,eAAe,EAAEC,SAAS,GAAG,CAAC;IAI5G,IAAI,CAACG,gBAAgB;QACnB,yDAAyD;QACzDxF,KAAKwD,KAAK,CAAC2B,cAAc,GAAGC,WAAW,eAAe,EAAEC,SAAS,GAAG,CAAC;IACvE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/agent-connection/agent-connection.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type Tree,\n} from '@nx/devkit';\nimport pyProjectGenerator, {\n getPyProjectDetails,\n} from '../../py/project/generator';\nimport tsProjectGenerator from '../../ts/lib/generator';\nimport { addStarExport, applyGritQL, matchGritQL } from '../ast';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n type MustDeclarePy,\n} from '../declared-dependencies';\nimport { addDependenciesToPackageJson } from '../dependencies';\nimport { esmVars } from '../module-format';\nimport { addDependenciesToPyProjectToml } from '../py';\nimport {\n type IPyDepVersion,\n type ITsDepVersion,\n withVersions,\n} from '../versions';\n\n/** TypeScript dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_DEPENDENCIES = [\n { name: '@aws-lambda-powertools/parameters' },\n { name: '@aws-sdk/credential-providers' },\n { name: 'aws4fetch' },\n { name: '@modelcontextprotocol/sdk' },\n { name: '@a2a-js/sdk' },\n { name: '@strands-agents/sdk' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\n/** Python dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_PY_DEPENDENCIES = [\n { name: 'aws-lambda-powertools' },\n { name: 'strands-agents' },\n] as const satisfies readonly { name: IPyDepVersion }[];\n\ntype AgentConnectionPyDependency =\n (typeof AGENT_CONNECTION_PY_DEPENDENCIES)[number]['name'];\n\n/** Prefix a GritQL pattern with `language python` */\nconst py = (pattern: string) => `language python\\n${pattern}`;\n\nconst AGENT_CONNECTION_DIR = 'agent-connection';\nconst PACKAGES_DIR = 'packages';\nconst COMMON_DIR = 'common';\n\nexport const AGENT_CONNECTION_PROJECT_DIR = joinPathFragments(\n PACKAGES_DIR,\n COMMON_DIR,\n AGENT_CONNECTION_DIR,\n);\n\nconst PY_AGENT_CONNECTION_NAME = 'agent_connection';\n\n/**\n * Get the directory of the shared Python agent-connection project.\n */\nexport function getPythonAgentConnectionProjectDir(tree: Tree): string {\n const { dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return dir;\n}\n\n/**\n * Get the Python module name of the shared agent-connection project.\n */\nexport function getPythonAgentConnectionModuleName(tree: Tree): string {\n const { normalizedModuleName } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return normalizedModuleName;\n}\n\n/**\n * Get the shared agent-connection project as `{ name, root }`, suitable for\n * passing to {@link addWorkspaceDependencyToPyProject} (which derives the\n * dependency's PEP 503 distribution name from the project itself, so callers\n * never construct the name).\n */\nexport function getPythonAgentConnectionProject(tree: Tree): {\n name: string;\n root: string;\n} {\n const { fullyQualifiedName, dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return { name: fullyQualifiedName, root: dir };\n}\n\n/**\n * The connection protocols an agent framework can connect over. Each maps to a\n * framework-agnostic Layer-0/1 template directory plus a per-framework Layer-2\n * client directory (see `FRAMEWORKS`).\n */\nexport type ConnectionProtocol = 'mcp' | 'gateway' | 'a2a';\n\n/**\n * The agent frameworks we can generate connection clients for. Adding a new\n * framework is an additive change: append an entry to `FRAMEWORKS` with its\n * Layer-2 template directories and dependencies — the framework-agnostic\n * Layer-0/1 (`core-auth`, `core-shared`, the per-protocol transports/configs)\n * is reused unchanged.\n */\nexport type AgentFramework = 'strands' | 'langchain';\n\n/**\n * Resolve an agent component's framework, defaulting to `strands`. Connection\n * generators dispatch on the returned framework to pick the matching templates\n * and agent.py/agent.ts transforms.\n */\nexport function resolveAgentFramework(\n framework: string | undefined,\n): AgentFramework {\n return framework === 'langchain' ? 'langchain' : 'strands';\n}\n\n/**\n * Framework-agnostic Layer-1 templates, keyed by protocol. These resolve the\n * endpoint and build the signed transport/client-config; they contain no\n * framework dependency.\n */\nconst TS_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'core-mcp',\n gateway: 'core-gateway',\n a2a: 'core-a2a',\n};\nconst PY_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'py-core-mcp',\n gateway: 'py-core-gateway',\n a2a: 'py-core-a2a',\n};\n\n/**\n * A re-export the framework base emits into the agent-connection module's\n * `__init__.py` (the agent server entry point imports these by name).\n */\ninterface BaseReExport {\n fromModule: string;\n importName: string;\n}\n\n/**\n * A framework's Layer-2 templates for one language. `base` (optional) holds the\n * helpers every connection of that framework needs (error logging, per-session\n * agent cache); `baseReExports` lists what those helpers expose at the module\n * root. `protocols` maps each *supported* protocol to the thin client that wraps\n * the matching Layer-1 transport/config in the framework's client type.\n *\n * A framework whose Layer-2 needs no base helpers (e.g. LangChain, whose AG-UI\n * foundation reuses only the framework-agnostic session context) omits `base`\n * and leaves `baseReExports` empty.\n *\n * A protocol absent from `protocols` is not supported by that framework in that\n * language — callers must check before emitting. `deps` are the extra package\n * dependencies the base helpers require (per-connection client deps are added\n * by the connection generators, not here).\n */\ninterface FrameworkLanguageTemplates<Dep extends string> {\n base?: string;\n baseReExports: BaseReExport[];\n protocols: Partial<Record<ConnectionProtocol, string>>;\n deps: Dep[];\n}\n\n/**\n * Per-framework Layer-2 templates. Support is asymmetric by design: a framework\n * may target only one language (`ts`/`py` is optional) and only a subset of\n * protocols. Adding a framework — or extending an existing one to a new\n * language/protocol — is an additive change to this registry.\n */\ninterface FrameworkTemplates {\n ts?: FrameworkLanguageTemplates<string>;\n py?: FrameworkLanguageTemplates<AgentConnectionPyDependency>;\n}\n\nconst FRAMEWORKS: Record<AgentFramework, FrameworkTemplates> = {\n strands: {\n ts: {\n base: 'core-strands/base',\n baseReExports: [\n {\n fromModule: './core/with-session-id-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/model-errors-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/tool-errors-strands.js',\n importName: '*',\n },\n ],\n protocols: {\n mcp: 'core-strands/mcp',\n gateway: 'core-strands/gateway',\n a2a: 'core-strands/a2a',\n },\n deps: [],\n },\n py: {\n base: 'py-core-strands/base',\n baseReExports: [\n {\n fromModule: '.core.with_session_id_strands',\n importName: 'with_session_id',\n },\n {\n fromModule: '.core.model_errors_strands',\n importName: 'log_model_errors',\n },\n {\n fromModule: '.core.tool_errors_strands',\n importName: 'log_tool_errors',\n },\n ],\n protocols: {\n mcp: 'py-core-strands/mcp',\n gateway: 'py-core-strands/gateway',\n a2a: 'py-core-strands/a2a',\n },\n deps: ['strands-agents'],\n },\n },\n langchain: {\n // LangChain is supported for Python agents only (the TypeScript LangChain\n // agent foundation has no in-process AG-UI <-> LangGraph adapter, so it is\n // not scaffolded — see ts#agent). Its Layer-2 clients stay usable after\n // agent construction, so there is no base helper layer (no model-error\n // logger / per-session agent cache) and no strands-agents dependency — its\n // AG-UI foundation reuses only the framework-agnostic session context, and\n // its A2A client drives the a2a SDK directly rather than wrapping Strands'\n // A2AAgent. The per-connection adapter dependency (langchain-mcp-adapters /\n // a2a-sdk) is added by the connection generators.\n py: {\n baseReExports: [],\n protocols: {\n mcp: 'py-core-langchain/mcp',\n gateway: 'py-core-langchain/gateway',\n a2a: 'py-core-langchain/a2a',\n },\n deps: [],\n },\n },\n};\n\n/** Resolve a framework's templates for a language + protocol, or throw. */\nfunction frameworkLanguage<L extends 'ts' | 'py'>(\n framework: AgentFramework,\n language: L,\n protocol: ConnectionProtocol,\n): NonNullable<FrameworkTemplates[L]> & { protocol: string } {\n const lang = FRAMEWORKS[framework][language];\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n const protocolDir = lang.protocols[protocol];\n if (!protocolDir) {\n throw new Error(\n `The '${framework}' framework does not support ${protocol} connections for ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n return { ...lang, protocol: protocolDir } as NonNullable<\n FrameworkTemplates[L]\n > & { protocol: string };\n}\n\n/** Protocols whose Layer-1 needs the shared MCP transport (`core-shared`). */\nconst MCP_TRANSPORT_PROTOCOLS: ConnectionProtocol[] = ['mcp', 'gateway'];\n\nconst tsCoreDir = () =>\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'core');\n\n/**\n * Runtime dependencies each TypeScript core template directory imports. Emitting\n * a template also declares its dependencies in the agent-connection project's\n * package.json so the `noUndeclaredDependencies` lint rule passes.\n */\nconst TS_TEMPLATE_DEPS: Record<\n string,\n (typeof AGENT_CONNECTION_DEPENDENCIES)[number]['name'][]\n> = {\n 'core-runtime-config': ['@aws-lambda-powertools/parameters'],\n 'core-auth': ['@aws-sdk/credential-providers', 'aws4fetch'],\n 'core-shared': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-mcp': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-gateway': [\n '@aws-sdk/credential-providers',\n '@modelcontextprotocol/sdk',\n ],\n 'core-a2a': ['@aws-sdk/credential-providers', '@a2a-js/sdk'],\n 'core-strands/base': ['@strands-agents/sdk'],\n 'core-strands/mcp': ['@strands-agents/sdk'],\n 'core-strands/gateway': ['@strands-agents/sdk'],\n 'core-strands/a2a': ['@strands-agents/sdk'],\n};\n\nconst emitTs = (\n tree: Tree,\n templateDir: string,\n declaration: DependencyDeclaration,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n tsCoreDir(),\n { ...esmVars(tree) },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n const deps = TS_TEMPLATE_DEPS[templateDir];\n if (deps?.length) {\n addDependenciesToPackageJson(\n tree,\n withVersions(\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n deps,\n ),\n {},\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'package.json'),\n );\n }\n};\n\n/**\n * Ensure the shared TypeScript agent-connection project exists and has the\n * framework-agnostic core helpers (runtime-config loader, session context).\n * Per-connection generators emit their own protocol + framework client\n * templates via `addTypeScriptCoreClient`.\n */\nexport async function ensureTypeScriptAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n): Promise<void> {\n const projectJsonPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'project.json',\n );\n if (!tree.exists(projectJsonPath)) {\n await tsProjectGenerator(tree, {\n name: AGENT_CONNECTION_DIR,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n emitTs(tree, 'core-runtime-config', declaration);\n\n // Re-export session-context helpers so agent server entry points can set the\n // current session on each inbound request without pulling in internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/session-context.js',\n );\n\n // Re-export the runtime-config loader so agent server entry points can read\n // their own connected resources (e.g. session storage) without pulling in\n // internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/runtime-config.js',\n );\n}\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the agent-connection project and re-export them. The agent\n * server entry point imports these regardless of whether any connection client\n * is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addTypeScriptCoreClient`.\n */\nexport async function addTypeScriptFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].ts;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support TypeScript agents.`,\n );\n }\n if (lang.base) {\n emitTs(tree, lang.base, declaration);\n }\n\n const indexPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'src',\n 'index.ts',\n );\n for (const reExport of lang.baseReExports) {\n await addStarExport(tree, indexPath, reExport.fromModule);\n }\n}\n\n/**\n * Emit the TypeScript client templates for a connection protocol and agent\n * framework into the agent-connection project's `src/core/` directory. Safe to\n * call multiple times — `KeepExisting` preserves customised files.\n *\n * Layers emitted:\n * - Layer 0 `core-auth` (signed fetch + endpoint resolution) — always\n * - Layer 1 `core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addTypeScriptCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'ts', protocol);\n\n emitTs(tree, 'core-auth', declaration);\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitTs(tree, 'core-shared', declaration);\n }\n emitTs(tree, TS_PROTOCOL_TEMPLATES[protocol], declaration);\n\n // Framework Layer 2: base helpers (re-exported for the agent server) + the\n // thin protocol client.\n await addTypeScriptFrameworkBase(\n tree,\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n framework,\n );\n emitTs(tree, fw.protocol, declaration);\n}\n\n/**\n * Ensure the shared Python agent-connection project exists.\n * Only creates the project shell — per-connection generators are responsible\n * for emitting their own core client templates.\n */\nexport async function ensurePythonAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n): Promise<void> {\n const projectDir = getPythonAgentConnectionProjectDir(tree);\n const moduleName = getPythonAgentConnectionModuleName(tree);\n const projectJsonPath = joinPathFragments(projectDir, 'project.json');\n\n if (!tree.exists(projectJsonPath)) {\n // Create the Python project using the standard py#project generator\n await pyProjectGenerator(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n type: 'library',\n });\n }\n\n const moduleDir = joinPathFragments(projectDir, moduleName);\n\n // Ensure core/__init__.py exists\n const coreDir = joinPathFragments(moduleDir, 'core');\n if (!tree.exists(joinPathFragments(coreDir, '__init__.py'))) {\n tree.write(joinPathFragments(coreDir, '__init__.py'), '');\n }\n\n // Ensure app/__init__.py exists\n const appInitPath = joinPathFragments(moduleDir, 'app', '__init__.py');\n if (!tree.exists(appInitPath)) {\n tree.write(appInitPath, '');\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'py-core-runtime-config'),\n coreDir,\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Re-export the session id context so agent server entry points can set the\n // current session on each inbound request without importing internals.\n const moduleInitPath = joinPathFragments(moduleDir, '__init__.py');\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'get_current_session_id',\n );\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'session_id_context',\n );\n\n // The runtime-config loader reads AppConfig via aws-lambda-powertools.\n addDependenciesToPyProjectToml(\n tree,\n projectDir,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n ['aws-lambda-powertools'],\n );\n}\n\nconst pyCoreDir = (tree: Tree) =>\n joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n 'core',\n );\n\nconst emitPy = (tree: Tree, templateDir: string) =>\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n pyCoreDir(tree),\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n/**\n * Ensure the shared Python agent-connection project has\n * `s3_checkpoint_saver_langchain.py` — a vendored `S3CheckpointSaver`\n * (from `langgraph-checkpoint-s3`, MIT licensed) that LangChain agents with\n * `session: 's3'` import from directly (`.core.s3_checkpoint_saver_langchain`),\n * mirroring how they import `.core.runtime_config`. Vendored rather than\n * installed as a dependency, and shared rather than per-agent, since it has\n * no agent-specific templating.\n */\nexport function ensureLangchainS3CheckpointSaver(tree: Tree): void {\n emitPy(tree, 'py-core-langchain/s3');\n}\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the Python agent-connection project and re-export them.\n * The agent server entry point imports these regardless of whether a connection\n * client is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addPythonCoreClient`.\n */\nexport async function addPythonFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].py;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support Python agents.`,\n );\n }\n if (lang.base) {\n emitPy(tree, lang.base);\n }\n\n const moduleInitPath = joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n '__init__.py',\n );\n for (const reExport of lang.baseReExports) {\n await addPythonReExport(\n tree,\n moduleInitPath,\n reExport.fromModule,\n reExport.importName,\n );\n }\n\n if (lang.deps.length > 0) {\n addDependenciesToPyProjectToml(\n tree,\n getPythonAgentConnectionProjectDir(tree),\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n lang.deps,\n );\n }\n}\n\n/**\n * Emit the Python client templates for a connection protocol and agent\n * framework into the agent-connection project's core directory.\n *\n * Layers emitted:\n * - Layer 0 `py-core-auth` (SigV4 httpx.Auth, session auth, endpoints) — always\n * - Layer 1 `py-core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addPythonCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'py', protocol);\n\n emitPy(tree, 'py-core-auth');\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitPy(tree, 'py-core-shared');\n }\n emitPy(tree, PY_PROTOCOL_TEMPLATES[protocol]);\n\n // Framework Layer 2: base helpers + the thin protocol client.\n await addPythonFrameworkBase(\n tree,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n framework,\n );\n emitPy(tree, fw.protocol);\n}\n\n/**\n * Patch a TypeScript agent.ts to create a connection client and register it\n * in the Agent's tools. Used by the MCP and gateway connection generators —\n * the client class must expose a static async `create()` returning a value\n * accepted by `Agent.tools` (e.g. an `McpClient`).\n */\nexport async function addTypeScriptClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n const clientCreationStmt = `const ${clientVarName} = await ${clientClassName}.create();`;\n\n // Transform the arrow function that contains `new Agent`:\n // - Expression body: wrap in block with client creation and return\n // - Block body: prepend client creation statement\n await applyGritQL(\n tree,\n agentFilePath,\n `or { \\`async ($p) => new Agent($args)\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n return new Agent($args);\n}\\` where { $program <: not contains \\`${clientClassName}.create\\` }, \\`async ($p) => { $body }\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n $body\n}\\` where { $body <: contains \\`new Agent($_)\\`, $program <: not contains \\`${clientClassName}.create\\` } }`,\n );\n\n // Prepend the client to the tools array\n await applyGritQL(\n tree,\n agentFilePath,\n `\\`tools: [$items]\\` => \\`tools: [${clientVarName}, $items]\\` where { $items <: within \\`new Agent($_)\\`, $items <: not contains \\`${clientVarName}\\` }`,\n );\n}\n\n/**\n * Patch a Python agent.py to create a context-managed connection client,\n * enter it in the `with` block around `yield Agent(...)`, and spread its\n * `list_tools_sync()` into the Agent's tools. Used by the MCP and gateway\n * connection generators — the client class must expose a static `create()`\n * returning a context manager with `list_tools_sync()` (e.g. an `MCPClient`).\n */\nasync function addPythonClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonClientTools(tree, agentFilePath, clientVarName);\n await addPythonClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Append `*<clientVarName>.list_tools_sync()` to the Agent's tools list.\n */\nconst addPythonClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(\n tree,\n filePath,\n py(`\\`${clientVarName}.list_tools_sync()\\``),\n )\n ) {\n return;\n }\n\n await applyGritQL(\n tree,\n filePath,\n py(`\\`tools=$old\\` where {\n $old <: not contains \\`${clientVarName}\\`,\n if ($old <: \\`[]\\`) {\n $old => \\`[*${clientVarName}.list_tools_sync()]\\`\n } else {\n $old <: \\`[$items]\\` where { $items += \\`, *${clientVarName}.list_tools_sync()\\` }\n }\n}`),\n );\n};\n\n/**\n * Create the client in get_agent and enter it in the `with` block.\n *\n * First connection: rewrites `def get_agent` to wrap the body in a with\n * block. Subsequent connections: adds to the existing with items and\n * prepends the creation line.\n */\nconst addPythonClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n // Try the \"add to existing with block\" pattern first.\n // If it succeeds, there was already a with block from a previous connection.\n const addedToWith = await applyGritQL(\n tree,\n filePath,\n py(`\\`with ($items,): $body\\` where {\n $items <: not contains \\`${clientVarName}\\`,\n $items += \\`, ${clientVarName}\\`\n}`),\n );\n\n if (addedToWith) {\n // Subsequent connection — prepend the creation line to the function body\n // (a single anchor, so the line is inserted exactly once).\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n return;\n }\n\n // First connection — wrap the existing `def get_agent` body in a single\n // `with (<var>,):` block.\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n with (\n ${clientVarName},\n ):\n $body\\``),\n );\n};\n\n/**\n * Patch a LangChain agent.py to load connection tools and spread them into the\n * `create_agent(...)` tools list. Used by the MCP and gateway connection\n * generators when the source agent uses the `langchain` framework — the client\n * class must expose a static `create()` returning a `list[BaseTool]`. The tools\n * come from langchain-mcp-adapters' `MultiServerMCPClient`, which keeps the\n * connection config on each tool and opens a fresh MCP session per call, so the\n * tools stay usable after `get_agent` returns — no `with` block is needed.\n * Mirrors {@link addPythonClientToAgent} for the Strands shape.\n */\nasync function addPythonLangchainClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonLangchainClientTools(tree, agentFilePath, clientVarName);\n await addPythonLangchainClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Spread `*<clientVarName>` into the `create_agent(...)` tools list.\n *\n * Scoped via `$old <: within \\`create_agent($_)\\`` so only the agent's own\n * tools= keyword argument is touched (not an unrelated function with a\n * `tools=` parameter).\n */\nconst addPythonLangchainClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n await applyGritQL(\n tree,\n filePath,\n py(`\\`tools=$old\\` where {\n $old <: within \\`create_agent($_)\\`,\n $old <: not contains \\`*${clientVarName}\\`,\n if ($old <: \\`[]\\`) {\n $old => \\`[*${clientVarName}]\\`\n } else {\n $old <: \\`[$items]\\` where { $items += \\`, *${clientVarName}\\` }\n }\n}`),\n );\n};\n\n/**\n * Prepend `<clientVarName> = <clientClassName>.create()` to the get_agent body\n * (which loads the connection's tools). No `with` block — the LangChain client\n * hands langchain-mcp-adapters a connection config, so each tool opens its own\n * MCP session per call and the tools are safe to use after get_agent returns.\n * Idempotent via the `not contains <clientClassName>.create` guard.\n */\nconst addPythonLangchainClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`create_agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n};\n\n/**\n * Per-framework naming + template layout for a Python per-connection client.\n * Every py#agent connection generator (mcp, gateway, a2a) names its client\n * class `<Name>Client<suffix>`, its module `<name>_client_<suffix>`, and reads\n * the per-connection app-client template from a per-framework sub-path of its\n * own `files/` dir — all of which vary only by framework, so they live here as\n * one source of truth.\n *\n * Keyed by {@link AgentFramework} rather than a boolean so a third framework is\n * an additive entry here — never another `if (isLangchain)` branch in each\n * generator.\n */\nexport interface PyClientNaming {\n /** Class-name suffix on the per-connection app client (`<Name>Client<suffix>`). */\n clientClassSuffix: string;\n /** Module/file-name suffix on the per-connection app client (`<name>_client_<suffix>`). */\n clientModuleSuffix: string;\n /**\n * Sub-path, under a connection generator's `files/` dir, of the per-connection\n * app client template for this framework. Every connection generator lays its\n * templates out the same way, so this resolves against any of them.\n */\n appTemplateSubdir: string;\n}\n\nexport const PY_CLIENT_NAMING: Record<AgentFramework, PyClientNaming> = {\n strands: {\n clientClassSuffix: 'Strands',\n clientModuleSuffix: 'strands',\n appTemplateSubdir: joinPathFragments('agent-connection', 'app'),\n },\n langchain: {\n clientClassSuffix: 'LangChain',\n clientModuleSuffix: 'langchain',\n appTemplateSubdir: joinPathFragments(\n 'langchain',\n 'agent-connection',\n 'app',\n ),\n },\n};\n\n/**\n * How an MCP-family connection (an MCP server or an AgentCore Gateway, both of\n * which expose tools over MCP) is wired into a Python agent of a given\n * framework. The mcp-connection and gateway-connection generators share this:\n * they differ only in the metadata of the thing being connected, not in how\n * the framework's client is shaped or spliced into agent.py. A2A connections\n * wire tools differently, so they reuse only {@link PY_CLIENT_NAMING}.\n */\nexport interface PyMcpFamilyConnection extends PyClientNaming {\n /** Extra Python deps this framework's MCP-family client needs (beyond the shared transport). */\n deps: IPyDepVersion[];\n /**\n * Splice the per-connection client into the agent's `get_agent` in agent.py.\n * Strands enters a context-managed `MCPClient` and spreads `list_tools_sync()`;\n * LangChain loads `BaseTool`s and spreads them into `create_agent(...)`.\n */\n wireClientIntoAgent: (\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n ) => Promise<void>;\n}\n\nexport const PY_MCP_FAMILY_CONNECTIONS: Record<\n AgentFramework,\n PyMcpFamilyConnection\n> = {\n strands: {\n ...PY_CLIENT_NAMING.strands,\n deps: [],\n wireClientIntoAgent: addPythonClientToAgent,\n },\n langchain: {\n ...PY_CLIENT_NAMING.langchain,\n // langchain-mcp-adapters backs the LangChain client; it must not pull Strands in.\n deps: ['langchain-mcp-adapters'],\n wireClientIntoAgent: addPythonLangchainClientToAgent,\n },\n};\n\n/**\n * Add a re-export to the Python agent-connection module's __init__.py.\n * Equivalent to addStarExport for TS.\n * Uses `__all__` to mark re-exports as public (satisfies ruff F401).\n * Uses GritQL for AST-aware transforms where possible.\n */\nexport async function addPythonReExport(\n tree: Tree,\n initFilePath: string,\n fromModule: string,\n importName: string,\n): Promise<void> {\n // Check if already exported\n if (await matchGritQL(tree, initFilePath, `\\`${importName}\\``)) {\n return;\n }\n\n const importLine = `from ${fromModule} import ${importName}`;\n const allEntry = `\"${importName}\"`;\n\n // If there's already an import from the same module, merge into its name list\n // (ruff I001 rejects two `from X import ...` lines for the same module).\n const mergedImport = await applyGritQL(\n tree,\n initFilePath,\n py(`\\`from ${fromModule} import $names\\` where {\n $names <: not contains \\`${importName}\\`,\n $names += \\`, ${importName}\\`\n}`),\n );\n\n if (mergedImport) {\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // Try to append import after existing import using +=\n const appendedImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`from $mod import $name\\` as $stmt where {\n $program <: not contains \\`${importName}\\`,\n $stmt += \\`\\n${importLine}\\`\n}`,\n ),\n );\n\n if (appendedImport) {\n // Also append to existing __all__\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // No existing imports — first re-export. Try to anchor after docstring.\n const anchoredImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`\"\"\"Automatically generated by Nx.\"\"\"\\` as $doc => \\`$doc\\n${importLine}\\n\\n__all__ = [${allEntry}]\\``,\n ),\n );\n\n if (!anchoredImport) {\n // Completely empty file or no docstring — write directly\n tree.write(initFilePath, `${importLine}\\n\\n__all__ = [${allEntry}]\\n`);\n }\n}\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","pyProjectGenerator","getPyProjectDetails","tsProjectGenerator","addStarExport","applyGritQL","matchGritQL","forDependencies","addDependenciesToPackageJson","esmVars","addDependenciesToPyProjectToml","withVersions","AGENT_CONNECTION_DEPENDENCIES","name","AGENT_CONNECTION_PY_DEPENDENCIES","py","pattern","AGENT_CONNECTION_DIR","PACKAGES_DIR","COMMON_DIR","AGENT_CONNECTION_PROJECT_DIR","PY_AGENT_CONNECTION_NAME","getPythonAgentConnectionProjectDir","tree","dir","directory","getPythonAgentConnectionModuleName","normalizedModuleName","getPythonAgentConnectionProject","fullyQualifiedName","root","resolveAgentFramework","framework","TS_PROTOCOL_TEMPLATES","mcp","gateway","a2a","PY_PROTOCOL_TEMPLATES","FRAMEWORKS","strands","ts","base","baseReExports","fromModule","importName","protocols","deps","langchain","frameworkLanguage","language","protocol","lang","Error","protocolDir","MCP_TRANSPORT_PROTOCOLS","tsCoreDir","TS_TEMPLATE_DEPS","emitTs","templateDir","declaration","dirname","overwriteStrategy","KeepExisting","length","ensureTypeScriptAgentConnectionProject","projectJsonPath","exists","addTypeScriptFrameworkBase","indexPath","reExport","addTypeScriptCoreClient","fw","includes","ensurePythonAgentConnectionProject","projectDir","moduleName","type","moduleDir","coreDir","write","appInitPath","moduleInitPath","addPythonReExport","pyCoreDir","emitPy","ensureLangchainS3CheckpointSaver","addPythonFrameworkBase","addPythonCoreClient","addTypeScriptClientToAgent","agentFilePath","clientClassName","clientVarName","clientCreationStmt","addPythonClientToAgent","addPythonClientTools","addPythonClientToGetAgent","filePath","addedToWith","addPythonLangchainClientToAgent","addPythonLangchainClientTools","addPythonLangchainClientToGetAgent","PY_CLIENT_NAMING","clientClassSuffix","clientModuleSuffix","appTemplateSubdir","PY_MCP_FAMILY_CONNECTIONS","wireClientIntoAgent","initFilePath","importLine","allEntry","mergedImport","appendedImport","anchoredImport"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QAEZ,aAAa;AACpB,OAAOC,sBACLC,mBAAmB,QACd,gCAA6B;AACpC,OAAOC,wBAAwB,4BAAyB;AACxD,SAASC,aAAa,EAAEC,WAAW,EAAEC,WAAW,QAAQ,YAAS;AACjE,SAEEC,eAAe,QAGV,8BAA2B;AAClC,SAASC,4BAA4B,QAAQ,qBAAkB;AAC/D,SAASC,OAAO,QAAQ,sBAAmB;AAC3C,SAASC,8BAA8B,QAAQ,WAAQ;AACvD,SAGEC,YAAY,QACP,iBAAc;AAErB,oFAAoF,GACpF,OAAO,MAAMC,gCAAgC;IAC3C;QAAEC,MAAM;IAAoC;IAC5C;QAAEA,MAAM;IAAgC;IACxC;QAAEA,MAAM;IAAY;IACpB;QAAEA,MAAM;IAA4B;IACpC;QAAEA,MAAM;IAAc;IACtB;QAAEA,MAAM;IAAsB;CAC/B,CAAuD;AAExD,gFAAgF,GAChF,OAAO,MAAMC,mCAAmC;IAC9C;QAAED,MAAM;IAAwB;IAChC;QAAEA,MAAM;IAAiB;CAC1B,CA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powertools/parameters/appconfig';
|
|
|
3
3
|
/** An agent or MCP server runtime registered in AppConfig. */
|
|
4
4
|
export interface AgentRuntimeEntry {
|
|
5
5
|
arn: string;
|
|
6
|
-
/** Session storage details. Only set when the agent has
|
|
6
|
+
/** Session storage details. Only set when the agent has session storage configured. */
|
|
7
7
|
session?: {
|
|
8
|
-
/** Name of the S3 bucket storing session data. */
|
|
9
|
-
bucketName
|
|
8
|
+
/** Name of the S3 bucket storing session data (S3 session storage, or the offload bucket for DynamoDB session storage). */
|
|
9
|
+
bucketName?: string;
|
|
10
|
+
/** Name of the DynamoDB table storing session data. Only set for DynamoDB session storage. */
|
|
11
|
+
tableName?: string;
|
|
10
12
|
};
|
|
11
13
|
}
|
|
12
14
|
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"""Async S3 checkpoint storage for LangGraph, backed by a plain (sync) boto3 client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import builtins
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
from collections.abc import AsyncIterator, Iterator, Sequence
|
|
10
|
+
from typing import Any, cast
|
|
11
|
+
|
|
12
|
+
import boto3
|
|
13
|
+
from botocore.exceptions import ClientError
|
|
14
|
+
from langchain_core.runnables import RunnableConfig, run_in_executor
|
|
15
|
+
from langgraph.checkpoint.base import (
|
|
16
|
+
WRITES_IDX_MAP,
|
|
17
|
+
BaseCheckpointSaver,
|
|
18
|
+
ChannelVersions,
|
|
19
|
+
Checkpoint,
|
|
20
|
+
CheckpointMetadata,
|
|
21
|
+
CheckpointTuple,
|
|
22
|
+
get_checkpoint_id,
|
|
23
|
+
get_checkpoint_metadata,
|
|
24
|
+
)
|
|
25
|
+
from langgraph.checkpoint.serde.base import SerializerProtocol
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _normalize_checkpoint_ns(checkpoint_ns: str) -> str:
|
|
31
|
+
return checkpoint_ns if checkpoint_ns else "__default__"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _denormalize_checkpoint_ns(checkpoint_ns_safe: str) -> str:
|
|
35
|
+
return "" if checkpoint_ns_safe == "__default__" else checkpoint_ns_safe
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _get_checkpoint_key(prefix: str, thread_id: str, checkpoint_ns: str, checkpoint_id: str) -> str:
|
|
39
|
+
checkpoint_ns_safe = _normalize_checkpoint_ns(checkpoint_ns)
|
|
40
|
+
return f"{prefix}checkpoints/{thread_id}/{checkpoint_ns_safe}/{checkpoint_id}.json"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _get_writes_prefix(prefix: str, thread_id: str, checkpoint_ns: str, checkpoint_id: str) -> str:
|
|
44
|
+
checkpoint_ns_safe = _normalize_checkpoint_ns(checkpoint_ns)
|
|
45
|
+
return f"{prefix}writes/{thread_id}/{checkpoint_ns_safe}/{checkpoint_id}/"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _get_write_key(prefix: str, thread_id: str, checkpoint_ns: str, checkpoint_id: str, task_id: str, idx: int) -> str:
|
|
49
|
+
return f"{_get_writes_prefix(prefix, thread_id, checkpoint_ns, checkpoint_id)}{task_id}_{idx}.json"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _serialize_checkpoint_data(checkpoint: Checkpoint, metadata: CheckpointMetadata, serde: SerializerProtocol) -> str:
|
|
53
|
+
checkpoint_type, serialized_checkpoint = serde.dumps_typed(checkpoint)
|
|
54
|
+
checkpoint_b64 = base64.b64encode(serialized_checkpoint).decode("utf-8")
|
|
55
|
+
metadata_type, serialized_metadata = serde.dumps_typed(metadata)
|
|
56
|
+
metadata_b64 = base64.b64encode(serialized_metadata).decode("utf-8")
|
|
57
|
+
return json.dumps(
|
|
58
|
+
{
|
|
59
|
+
"checkpoint_type": checkpoint_type,
|
|
60
|
+
"checkpoint": checkpoint_b64,
|
|
61
|
+
"metadata_type": metadata_type,
|
|
62
|
+
"metadata": metadata_b64,
|
|
63
|
+
},
|
|
64
|
+
indent=2,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _deserialize_checkpoint_data(data: str, serde: SerializerProtocol) -> tuple[Checkpoint, CheckpointMetadata]:
|
|
69
|
+
parsed = json.loads(data)
|
|
70
|
+
checkpoint = serde.loads_typed((parsed["checkpoint_type"], base64.b64decode(parsed["checkpoint"])))
|
|
71
|
+
metadata = cast(
|
|
72
|
+
CheckpointMetadata,
|
|
73
|
+
serde.loads_typed((parsed["metadata_type"], base64.b64decode(parsed["metadata"]))),
|
|
74
|
+
)
|
|
75
|
+
return checkpoint, metadata
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _serialize_write_data(channel: str, value: Any, serde: SerializerProtocol) -> str:
|
|
79
|
+
type_, serialized_value = serde.dumps_typed(value)
|
|
80
|
+
value_b64 = base64.b64encode(serialized_value).decode("utf-8")
|
|
81
|
+
return json.dumps({"channel": channel, "value_type": type_, "value": value_b64}, indent=2)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _deserialize_write_data(data: str, serde: SerializerProtocol) -> tuple[str, Any]:
|
|
85
|
+
parsed = json.loads(data)
|
|
86
|
+
value = serde.loads_typed((parsed["value_type"], base64.b64decode(parsed["value"])))
|
|
87
|
+
return parsed["channel"], value
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class S3CheckpointSaver(BaseCheckpointSaver[str]):
|
|
91
|
+
"""A checkpoint saver that stores LangGraph checkpoints in Amazon S3.
|
|
92
|
+
|
|
93
|
+
The sync methods (`get_tuple`, `list`, `put`, `put_writes`,
|
|
94
|
+
`delete_thread`) call boto3 directly. The async methods offload the same
|
|
95
|
+
sync methods to a thread via `run_in_executor` (mirroring
|
|
96
|
+
`langgraph_checkpoint_aws`'s `DynamoDBSaver`), since graphs compiled with
|
|
97
|
+
this checkpointer are invoked via `.ainvoke()`/`.astream()`.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
def __init__(
|
|
101
|
+
self,
|
|
102
|
+
bucket_name: str,
|
|
103
|
+
*,
|
|
104
|
+
prefix: str = "checkpoints/",
|
|
105
|
+
s3_client: Any | None = None,
|
|
106
|
+
**kwargs: Any,
|
|
107
|
+
) -> None:
|
|
108
|
+
super().__init__(**kwargs)
|
|
109
|
+
self.bucket_name = bucket_name
|
|
110
|
+
self.prefix = prefix.rstrip("/") + "/" if prefix else ""
|
|
111
|
+
self.s3_client = s3_client or boto3.client("s3")
|
|
112
|
+
|
|
113
|
+
def _iter_objects(self, prefix: str) -> Iterator[dict[str, Any]]:
|
|
114
|
+
paginator = self.s3_client.get_paginator("list_objects_v2")
|
|
115
|
+
for page in paginator.paginate(Bucket=self.bucket_name, Prefix=prefix):
|
|
116
|
+
yield from page.get("Contents", [])
|
|
117
|
+
|
|
118
|
+
def get_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
|
|
119
|
+
thread_id = str(config["configurable"]["thread_id"])
|
|
120
|
+
checkpoint_ns = config["configurable"].get("checkpoint_ns", "")
|
|
121
|
+
|
|
122
|
+
if checkpoint_id := get_checkpoint_id(config):
|
|
123
|
+
key = _get_checkpoint_key(self.prefix, thread_id, checkpoint_ns, checkpoint_id)
|
|
124
|
+
try:
|
|
125
|
+
response = self.s3_client.get_object(Bucket=self.bucket_name, Key=key)
|
|
126
|
+
checkpoint_data = response["Body"].read().decode("utf-8")
|
|
127
|
+
checkpoint, metadata = _deserialize_checkpoint_data(checkpoint_data, self.serde)
|
|
128
|
+
|
|
129
|
+
pending_writes = self._get_writes(thread_id, checkpoint_ns, checkpoint_id)
|
|
130
|
+
|
|
131
|
+
parent_config = None
|
|
132
|
+
if "parents" in metadata and checkpoint_ns in metadata["parents"]:
|
|
133
|
+
parent_config = RunnableConfig(
|
|
134
|
+
configurable={
|
|
135
|
+
"thread_id": thread_id,
|
|
136
|
+
"checkpoint_ns": checkpoint_ns,
|
|
137
|
+
"checkpoint_id": metadata["parents"][checkpoint_ns],
|
|
138
|
+
}
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
return CheckpointTuple(
|
|
142
|
+
config=config,
|
|
143
|
+
checkpoint=checkpoint,
|
|
144
|
+
metadata=metadata,
|
|
145
|
+
parent_config=parent_config,
|
|
146
|
+
pending_writes=pending_writes,
|
|
147
|
+
)
|
|
148
|
+
except ClientError as e:
|
|
149
|
+
if e.response["Error"]["Code"] == "NoSuchKey":
|
|
150
|
+
return None
|
|
151
|
+
raise RuntimeError(f"Failed to get checkpoint: {e}") from e
|
|
152
|
+
|
|
153
|
+
# No checkpoint_id given - resolve the latest one the same way list() does.
|
|
154
|
+
return next(self.list(config, limit=1), None)
|
|
155
|
+
|
|
156
|
+
# `builtins.list` is used here (rather than the bare `list` type) because this class
|
|
157
|
+
# defines its own `list` method below, which shadows the builtin for annotations
|
|
158
|
+
# resolved within this class body.
|
|
159
|
+
def _get_writes(
|
|
160
|
+
self, thread_id: str, checkpoint_ns: str, checkpoint_id: str
|
|
161
|
+
) -> builtins.list[tuple[str, str, Any]]:
|
|
162
|
+
writes_prefix = _get_writes_prefix(self.prefix, thread_id, checkpoint_ns, checkpoint_id)
|
|
163
|
+
writes = []
|
|
164
|
+
for obj in self._iter_objects(writes_prefix):
|
|
165
|
+
key = obj["Key"]
|
|
166
|
+
filename = key.split("/")[-1].replace(".json", "")
|
|
167
|
+
if "_" not in filename:
|
|
168
|
+
continue
|
|
169
|
+
task_id, idx_str = filename.rsplit("_", 1)
|
|
170
|
+
try:
|
|
171
|
+
idx = int(idx_str)
|
|
172
|
+
except ValueError:
|
|
173
|
+
continue
|
|
174
|
+
response = self.s3_client.get_object(Bucket=self.bucket_name, Key=key)
|
|
175
|
+
channel, value = _deserialize_write_data(response["Body"].read().decode("utf-8"), self.serde)
|
|
176
|
+
writes.append((task_id, channel, value, idx))
|
|
177
|
+
|
|
178
|
+
writes.sort(key=lambda x: (x[0], x[3]))
|
|
179
|
+
return [(task_id, channel, value) for task_id, channel, value, _ in writes]
|
|
180
|
+
|
|
181
|
+
def list(
|
|
182
|
+
self,
|
|
183
|
+
config: RunnableConfig | None,
|
|
184
|
+
*,
|
|
185
|
+
filter: dict[str, Any] | None = None,
|
|
186
|
+
before: RunnableConfig | None = None,
|
|
187
|
+
limit: int | None = None,
|
|
188
|
+
) -> Iterator[CheckpointTuple]:
|
|
189
|
+
if config is None:
|
|
190
|
+
prefix = f"{self.prefix}checkpoints/"
|
|
191
|
+
else:
|
|
192
|
+
thread_id = str(config["configurable"]["thread_id"])
|
|
193
|
+
checkpoint_ns_safe = _normalize_checkpoint_ns(config["configurable"].get("checkpoint_ns", ""))
|
|
194
|
+
prefix = f"{self.prefix}checkpoints/{thread_id}/{checkpoint_ns_safe}/"
|
|
195
|
+
|
|
196
|
+
before_checkpoint_id = get_checkpoint_id(before) if before else None
|
|
197
|
+
|
|
198
|
+
try:
|
|
199
|
+
checkpoints = []
|
|
200
|
+
for obj in self._iter_objects(prefix):
|
|
201
|
+
key = obj["Key"]
|
|
202
|
+
if not key.endswith(".json"):
|
|
203
|
+
continue
|
|
204
|
+
parts = key[len(self.prefix) :].split("/")
|
|
205
|
+
if len(parts) < 4 or parts[0] != "checkpoints":
|
|
206
|
+
continue
|
|
207
|
+
key_checkpoint_id = parts[3].replace(".json", "")
|
|
208
|
+
if before_checkpoint_id and key_checkpoint_id >= before_checkpoint_id:
|
|
209
|
+
continue
|
|
210
|
+
checkpoints.append((parts[1], _denormalize_checkpoint_ns(parts[2]), key_checkpoint_id))
|
|
211
|
+
|
|
212
|
+
checkpoints.sort(key=lambda x: x[2], reverse=True)
|
|
213
|
+
if limit:
|
|
214
|
+
checkpoints = checkpoints[:limit]
|
|
215
|
+
|
|
216
|
+
for thread_id, checkpoint_ns, checkpoint_id in checkpoints:
|
|
217
|
+
checkpoint_tuple = self.get_tuple(
|
|
218
|
+
RunnableConfig(
|
|
219
|
+
configurable={
|
|
220
|
+
"thread_id": thread_id,
|
|
221
|
+
"checkpoint_ns": checkpoint_ns,
|
|
222
|
+
"checkpoint_id": checkpoint_id,
|
|
223
|
+
}
|
|
224
|
+
)
|
|
225
|
+
)
|
|
226
|
+
if checkpoint_tuple and (
|
|
227
|
+
not filter or all(checkpoint_tuple.metadata.get(k) == v for k, v in filter.items())
|
|
228
|
+
):
|
|
229
|
+
yield checkpoint_tuple
|
|
230
|
+
except ClientError as e:
|
|
231
|
+
raise RuntimeError(f"Failed to list checkpoints: {e}") from e
|
|
232
|
+
|
|
233
|
+
def put(
|
|
234
|
+
self,
|
|
235
|
+
config: RunnableConfig,
|
|
236
|
+
checkpoint: Checkpoint,
|
|
237
|
+
metadata: CheckpointMetadata,
|
|
238
|
+
new_versions: ChannelVersions,
|
|
239
|
+
) -> RunnableConfig:
|
|
240
|
+
thread_id = str(config["configurable"]["thread_id"])
|
|
241
|
+
checkpoint_ns = config["configurable"].get("checkpoint_ns", "")
|
|
242
|
+
checkpoint_id = checkpoint["id"]
|
|
243
|
+
|
|
244
|
+
full_metadata = get_checkpoint_metadata(config, metadata)
|
|
245
|
+
checkpoint_data = _serialize_checkpoint_data(checkpoint, full_metadata, self.serde)
|
|
246
|
+
key = _get_checkpoint_key(self.prefix, thread_id, checkpoint_ns, checkpoint_id)
|
|
247
|
+
|
|
248
|
+
try:
|
|
249
|
+
self.s3_client.put_object(
|
|
250
|
+
Bucket=self.bucket_name,
|
|
251
|
+
Key=key,
|
|
252
|
+
Body=checkpoint_data,
|
|
253
|
+
ContentType="application/json",
|
|
254
|
+
)
|
|
255
|
+
return {
|
|
256
|
+
"configurable": {
|
|
257
|
+
"thread_id": thread_id,
|
|
258
|
+
"checkpoint_ns": checkpoint_ns,
|
|
259
|
+
"checkpoint_id": checkpoint_id,
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
except ClientError as e:
|
|
263
|
+
raise RuntimeError(f"Failed to save checkpoint: {e}") from e
|
|
264
|
+
|
|
265
|
+
def put_writes(
|
|
266
|
+
self,
|
|
267
|
+
config: RunnableConfig,
|
|
268
|
+
writes: Sequence[tuple[str, Any]],
|
|
269
|
+
task_id: str,
|
|
270
|
+
task_path: str = "",
|
|
271
|
+
) -> None:
|
|
272
|
+
thread_id = str(config["configurable"]["thread_id"])
|
|
273
|
+
checkpoint_ns = config["configurable"].get("checkpoint_ns", "")
|
|
274
|
+
checkpoint_id = str(config["configurable"]["checkpoint_id"])
|
|
275
|
+
|
|
276
|
+
try:
|
|
277
|
+
for idx, (channel, value) in enumerate(writes):
|
|
278
|
+
write_idx = WRITES_IDX_MAP.get(channel, idx)
|
|
279
|
+
write_data = _serialize_write_data(channel, value, self.serde)
|
|
280
|
+
key = _get_write_key(self.prefix, thread_id, checkpoint_ns, checkpoint_id, task_id, write_idx)
|
|
281
|
+
self.s3_client.put_object(
|
|
282
|
+
Bucket=self.bucket_name,
|
|
283
|
+
Key=key,
|
|
284
|
+
Body=write_data,
|
|
285
|
+
ContentType="application/json",
|
|
286
|
+
)
|
|
287
|
+
except ClientError as e:
|
|
288
|
+
raise RuntimeError(f"Failed to store writes: {e}") from e
|
|
289
|
+
|
|
290
|
+
def delete_thread(self, thread_id: str) -> None:
|
|
291
|
+
thread_id = str(thread_id)
|
|
292
|
+
prefixes = [
|
|
293
|
+
f"{self.prefix}checkpoints/{thread_id}/",
|
|
294
|
+
f"{self.prefix}writes/{thread_id}/",
|
|
295
|
+
]
|
|
296
|
+
deleted_count = 0
|
|
297
|
+
try:
|
|
298
|
+
for prefix in prefixes:
|
|
299
|
+
objects_to_delete = []
|
|
300
|
+
for obj in self._iter_objects(prefix):
|
|
301
|
+
objects_to_delete.append({"Key": obj["Key"]})
|
|
302
|
+
if len(objects_to_delete) >= 1000:
|
|
303
|
+
self.s3_client.delete_objects(
|
|
304
|
+
Bucket=self.bucket_name, Delete={"Objects": objects_to_delete}
|
|
305
|
+
)
|
|
306
|
+
deleted_count += len(objects_to_delete)
|
|
307
|
+
objects_to_delete = []
|
|
308
|
+
if objects_to_delete:
|
|
309
|
+
self.s3_client.delete_objects(Bucket=self.bucket_name, Delete={"Objects": objects_to_delete})
|
|
310
|
+
deleted_count += len(objects_to_delete)
|
|
311
|
+
except ClientError as e:
|
|
312
|
+
raise RuntimeError(f"Failed to delete thread data: {e}") from e
|
|
313
|
+
|
|
314
|
+
if deleted_count == 0:
|
|
315
|
+
logger.info("No checkpoints found for thread_id=%s", thread_id)
|
|
316
|
+
else:
|
|
317
|
+
logger.info("Deleted %d objects for thread_id=%s", deleted_count, thread_id)
|
|
318
|
+
|
|
319
|
+
async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
|
|
320
|
+
return await run_in_executor(None, self.get_tuple, config)
|
|
321
|
+
|
|
322
|
+
async def alist(
|
|
323
|
+
self,
|
|
324
|
+
config: RunnableConfig | None,
|
|
325
|
+
*,
|
|
326
|
+
filter: dict[str, Any] | None = None,
|
|
327
|
+
before: RunnableConfig | None = None,
|
|
328
|
+
limit: int | None = None,
|
|
329
|
+
) -> AsyncIterator[CheckpointTuple]:
|
|
330
|
+
# ``list`` is backed by blocking boto3 calls, so it is driven from a
|
|
331
|
+
# background thread one item at a time to avoid blocking the event loop
|
|
332
|
+
# while still yielding lazily (no need to materialize all results).
|
|
333
|
+
iterator = self.list(config, filter=filter, before=before, limit=limit)
|
|
334
|
+
|
|
335
|
+
def next_item() -> CheckpointTuple | None:
|
|
336
|
+
return next(iterator, None)
|
|
337
|
+
|
|
338
|
+
while (item := await run_in_executor(None, next_item)) is not None:
|
|
339
|
+
yield item
|
|
340
|
+
|
|
341
|
+
async def aput(
|
|
342
|
+
self,
|
|
343
|
+
config: RunnableConfig,
|
|
344
|
+
checkpoint: Checkpoint,
|
|
345
|
+
metadata: CheckpointMetadata,
|
|
346
|
+
new_versions: ChannelVersions,
|
|
347
|
+
) -> RunnableConfig:
|
|
348
|
+
return await run_in_executor(None, self.put, config, checkpoint, metadata, new_versions)
|
|
349
|
+
|
|
350
|
+
async def aput_writes(
|
|
351
|
+
self,
|
|
352
|
+
config: RunnableConfig,
|
|
353
|
+
writes: Sequence[tuple[str, Any]],
|
|
354
|
+
task_id: str,
|
|
355
|
+
task_path: str = "",
|
|
356
|
+
) -> None:
|
|
357
|
+
await run_in_executor(None, self.put_writes, config, writes, task_id, task_path)
|
|
358
|
+
|
|
359
|
+
async def adelete_thread(self, thread_id: str) -> None:
|
|
360
|
+
await run_in_executor(None, self.delete_thread, thread_id)
|
|
@@ -8,10 +8,8 @@ from botocore.config import Config
|
|
|
8
8
|
def get_agentcore_runtime_config() -> dict[str, Any]:
|
|
9
9
|
"""Read the runtime-config ``agentcore`` namespace from AppConfig.
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
where keys are the class names of connected target constructs. ``session``
|
|
14
|
-
is only present when the agent has S3 session storage configured.
|
|
11
|
+
Agent runtime entries include an ARN and optional session storage details.
|
|
12
|
+
Gateway entries map their construct names to URLs.
|
|
15
13
|
|
|
16
14
|
``RUNTIME_CONFIG_APP_ID`` is set on the AgentCore runtime by the generated
|
|
17
15
|
CDK/Terraform construct for this project.
|