@aws/nx-plugin 0.64.1 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/LICENSE-THIRD-PARTY +198 -132
  2. package/README.md +6 -3
  3. package/generators.json +6 -0
  4. package/package.json +13 -13
  5. package/sdk/ts.d.ts +2 -0
  6. package/sdk/ts.js +20 -17
  7. package/sdk/ts.js.map +1 -1
  8. package/src/infra/app/__snapshots__/generator.spec.ts.snap +31 -31
  9. package/src/preset/__snapshots__/generator.spec.ts.snap +5 -3
  10. package/src/py/mcp-server/__snapshots__/generator.spec.ts.snap +3 -3
  11. package/src/py/strands-agent/__snapshots__/generator.spec.ts.snap +8 -8
  12. package/src/ts/mcp-server/__snapshots__/generator.spec.ts.snap +5 -5
  13. package/src/ts/nx-plugin/__snapshots__/generator.spec.ts.snap +1 -1
  14. package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +93 -49
  15. package/src/ts/strands-agent/__snapshots__/generator.spec.ts.snap +1035 -0
  16. package/src/ts/strands-agent/files/app/agent-core-mcp-client.ts.template +132 -0
  17. package/src/ts/strands-agent/files/app/agent-core-trpc-client.ts.template +124 -0
  18. package/src/ts/strands-agent/files/app/agent.ts.template +20 -0
  19. package/src/ts/strands-agent/files/app/client.ts.template +28 -0
  20. package/src/ts/strands-agent/files/app/index.ts.template +54 -0
  21. package/src/ts/strands-agent/files/app/init.ts.template +8 -0
  22. package/src/ts/strands-agent/files/app/router.ts.template +34 -0
  23. package/src/ts/strands-agent/files/app/schema/z-async-iterable.ts.template +77 -0
  24. package/src/ts/strands-agent/files/deploy/Dockerfile.template +16 -0
  25. package/src/ts/strands-agent/generator.d.ts +10 -0
  26. package/src/ts/strands-agent/generator.js +115 -0
  27. package/src/ts/strands-agent/generator.js.map +1 -0
  28. package/src/ts/strands-agent/schema.d.ts +15 -0
  29. package/src/ts/strands-agent/schema.json +41 -0
  30. package/src/utils/versions.d.ts +58 -55
  31. package/src/utils/versions.js +57 -54
  32. package/src/utils/versions.js.map +1 -1
@@ -0,0 +1,132 @@
1
+ import { McpClient } from '@strands-agents/sdk';
2
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
3
+ import { AwsClient } from 'aws4fetch';
4
+ import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
5
+
6
+ /**
7
+ * Options for creating an AgentCore MCP client with IAM authentication
8
+ */
9
+ export interface AgentCoreMcpClientIamOptions {
10
+ agentRuntimeArn: string;
11
+ region: string;
12
+ sessionId: string;
13
+ }
14
+
15
+ /**
16
+ * Options for creating an AgentCore MCP client with JWT authentication
17
+ */
18
+ export interface AgentCoreMcpClientJwtOptions {
19
+ agentRuntimeArn: string;
20
+ accessToken: string;
21
+ region: string;
22
+ sessionId: string;
23
+ }
24
+
25
+ /**
26
+ * Internal options for creating an AgentCore MCP client
27
+ */
28
+ interface CreateOptions {
29
+ agentRuntimeArn: string;
30
+ region: string;
31
+ sessionId: string;
32
+ additionalHeaders?: Record<string, string>;
33
+ fetch?: typeof fetch;
34
+ }
35
+
36
+ /**
37
+ * Factory for clients to call MCP servers hosted on Bedrock AgentCore Runtime
38
+ */
39
+ export class AgentCoreMcpClient {
40
+ /**
41
+ * Internal method to create an MCP client
42
+ */
43
+ private static create(options: CreateOptions): McpClient {
44
+ const {
45
+ agentRuntimeArn,
46
+ region,
47
+ sessionId,
48
+ additionalHeaders = {},
49
+ fetch: customFetch,
50
+ } = options;
51
+
52
+ // Encode the ARN for URL
53
+ const encodedArn = agentRuntimeArn
54
+ .replace(/:/g, '%3A')
55
+ .replace(/\//g, '%2F');
56
+ const url = `https://bedrock-agentcore.${region}.amazonaws.com/runtimes/${encodedArn}/invocations?qualifier=DEFAULT`;
57
+
58
+ // Create a custom fetch that adds required headers
59
+ const fetchWithHeaders: typeof fetch = async (input, init) => {
60
+ const headers = {
61
+ 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id': sessionId,
62
+ ...additionalHeaders,
63
+ };
64
+ const existingHeaders = init?.headers;
65
+
66
+ const mergedInit = {
67
+ ...init,
68
+ headers: !existingHeaders
69
+ ? headers
70
+ : existingHeaders instanceof Headers
71
+ ? (() => {
72
+ const h = new Headers(existingHeaders);
73
+ Object.entries(headers).forEach(([k, v]) => h.append(k, v));
74
+ return h;
75
+ })()
76
+ : Array.isArray(existingHeaders)
77
+ ? [...existingHeaders, ...Object.entries(headers)]
78
+ : { ...existingHeaders, ...headers },
79
+ };
80
+ return (customFetch || fetch)(input, mergedInit);
81
+ };
82
+
83
+ // Create the transport
84
+ const transport = new StreamableHTTPClientTransport(new URL(url), {
85
+ fetch: fetchWithHeaders,
86
+ });
87
+
88
+ // Create and return the MCP client
89
+ return new McpClient({ transport });
90
+ }
91
+
92
+ /**
93
+ * Create an MCP client with IAM (SigV4) authentication
94
+ */
95
+ static withIamAuth(options: AgentCoreMcpClientIamOptions): McpClient {
96
+ const { region, ...rest } = options;
97
+
98
+ // Create credential provider
99
+ const credentialProvider = fromNodeProviderChain();
100
+
101
+ // Create a SigV4 signing fetch function
102
+ const sigv4Fetch: typeof fetch = async (...args) => {
103
+ const credentials = await credentialProvider();
104
+ const client = new AwsClient({
105
+ ...credentials,
106
+ service: 'bedrock-agentcore',
107
+ region,
108
+ });
109
+ return client.fetch(...args);
110
+ };
111
+
112
+ return AgentCoreMcpClient.create({
113
+ ...rest,
114
+ region,
115
+ fetch: sigv4Fetch,
116
+ });
117
+ }
118
+
119
+ /**
120
+ * Create an MCP client with JWT authentication
121
+ */
122
+ static withJwtAuth(options: AgentCoreMcpClientJwtOptions): McpClient {
123
+ const { accessToken, ...rest } = options;
124
+
125
+ return AgentCoreMcpClient.create({
126
+ ...rest,
127
+ additionalHeaders: {
128
+ Authorization: `Bearer ${accessToken}`,
129
+ },
130
+ });
131
+ }
132
+ }
@@ -0,0 +1,124 @@
1
+ import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
2
+ import { createTRPCClient, createWSClient, WebSocketLinkOptions, wsLink } from '@trpc/client';
3
+ import { AwsClient } from 'aws4fetch';
4
+ import { AnyTRPCRouter } from '@trpc/server';
5
+ import { WebSocket } from 'node:http';
6
+
7
+ export interface WebSocketTrpcClientOptions {
8
+ /**
9
+ * URL of the websocket server, eg http://localhost:8080/ws
10
+ */
11
+ url: string;
12
+ /**
13
+ * Factory for creating headers to include in the WebSocket handshake
14
+ */
15
+ buildHeaders?: () => Promise<{ [key: string]: string }>;
16
+ }
17
+
18
+ /**
19
+ * Client for connecting to tRPC APIs via WebSocket
20
+ */
21
+ export class WebSocketTrpcClient {
22
+ /**
23
+ * Utility for creating a tRPC client with a WebSocket link and custom headers
24
+ */
25
+ public static create = <TRouter extends AnyTRPCRouter>({
26
+ url,
27
+ buildHeaders = async () => ({}),
28
+ }: WebSocketTrpcClientOptions) => {
29
+ let headers = {};
30
+ const client = createWSClient({
31
+ url: async () => {
32
+ headers = await buildHeaders();
33
+ return url;
34
+ },
35
+ WebSocket: class extends WebSocket {
36
+ constructor(wsUrl: string | URL) {
37
+ super(wsUrl, { headers });
38
+ }
39
+ } as any,
40
+ });
41
+
42
+ return createTRPCClient<TRouter>({
43
+ links: [wsLink({ client } as WebSocketLinkOptions<TRouter>)],
44
+ });
45
+ };
46
+ }
47
+
48
+ export interface AgentCoreTrpcClientOptions {
49
+ /**
50
+ * The ARN of the Bedrock AgentCore Runtime to connect to
51
+ */
52
+ agentRuntimeArn: string;
53
+ }
54
+
55
+ export interface AgentCoreTrpcClientIamOptions extends AgentCoreTrpcClientOptions {
56
+ /**
57
+ * Optional AWS credential provider. If not provided, uses the default
58
+ * credential provider chain from the AWS SDK.
59
+ */
60
+ credentialProvider?: ReturnType<typeof fromNodeProviderChain>;
61
+ }
62
+
63
+ export interface AgentCoreTrpcClientJwtOptions extends AgentCoreTrpcClientOptions {
64
+ /**
65
+ * A function which returns the JWT access token used to authenticate
66
+ */
67
+ accessTokenProvider: () => Promise<string>;
68
+ }
69
+
70
+ /**
71
+ * Client for connecting to a tRPC API on Bedrock AgentCore Runtime via WebSocket.
72
+ */
73
+ export class AgentCoreTrpcClient {
74
+ /**
75
+ * Construct the websocket url for connecting to Bedrock AgentCore Runtime
76
+ */
77
+ private static buildUrl = (agentRuntimeArn: string) => {
78
+ const region = agentRuntimeArn.split(':')[3];
79
+ const url = `wss://bedrock-agentcore.${region}.amazonaws.com/runtimes/${agentRuntimeArn.replace(/:/g, '%3A').replace(/\//g, '%2F')}/ws`;
80
+ return { region, url };
81
+ };
82
+
83
+ /**
84
+ * Creates a tRPC client with IAM authentication using AWS credentials.
85
+ *
86
+ * The WebSocket connection is authenticated using AWS Signature Version 4 (SigV4) signed headers.
87
+ * This method signs the WebSocket upgrade request headers directly, rather than using a presigned URL.
88
+ */
89
+ public static withIamAuth = <TRouter extends AnyTRPCRouter>(options: AgentCoreTrpcClientIamOptions) => {
90
+ const credentialProvider =
91
+ options.credentialProvider ?? fromNodeProviderChain();
92
+ const { region, url } = AgentCoreTrpcClient.buildUrl(options.agentRuntimeArn);
93
+
94
+ return WebSocketTrpcClient.create<TRouter>({
95
+ url,
96
+ buildHeaders: async () =>
97
+ Object.fromEntries(
98
+ (
99
+ await new AwsClient({
100
+ ...(await credentialProvider()),
101
+ region,
102
+ service: 'bedrock-agentcore',
103
+ }).sign(url)
104
+ ).headers,
105
+ ),
106
+ });
107
+ };
108
+
109
+ /**
110
+ * Creates a tRPC client with JWT (JSON Web Token) authentication.
111
+ *
112
+ * The WebSocket connection includes the JWT as a Bearer token in the Authorization header.
113
+ */
114
+ public static withJwtAuth = <TRouter extends AnyTRPCRouter>(options: AgentCoreTrpcClientJwtOptions) => {
115
+ const { url } = AgentCoreTrpcClient.buildUrl(options.agentRuntimeArn);
116
+
117
+ return WebSocketTrpcClient.create<TRouter>({
118
+ url,
119
+ buildHeaders: async () => ({
120
+ Authorization: `Bearer ${await options.accessTokenProvider()}`,
121
+ }),
122
+ });
123
+ };
124
+ }
@@ -0,0 +1,20 @@
1
+ import { Agent, tool } from '@strands-agents/sdk';
2
+ import { z } from 'zod';
3
+
4
+ const add = tool({
5
+ name: 'Add',
6
+ description: 'Add two numbers',
7
+ inputSchema: z.object({
8
+ a: z.number(),
9
+ b: z.number(),
10
+ }),
11
+ callback: ({ a, b }) => a + b,
12
+ });
13
+
14
+ export const getAgent = () =>
15
+ new Agent({
16
+ systemPrompt: `You are an addition wizard.
17
+ Use the add tool for addition tasks.
18
+ Refer to tools as your 'spellbook'.`,
19
+ tools: [add],
20
+ });
@@ -0,0 +1,28 @@
1
+ import { AppRouter } from './router.js';
2
+ import { AgentCoreTrpcClient, WebSocketTrpcClient } from './agent-core-trpc-client.js';
3
+
4
+ /**
5
+ * Client for connecting to <%- agentNameClassName %> on Bedrock AgentCore Runtime via WebSocket from a NodeJS environment
6
+ *
7
+ * Refer to the Nx Plugin for AWS documentation for instructions to connect to this agent in a browser.
8
+ */
9
+ export class <%- agentNameClassName %>Client {
10
+ /**
11
+ * Creates a tRPC client with IAM authentication using AWS credentials.
12
+ *
13
+ * The WebSocket connection is authenticated using AWS Signature Version 4 (SigV4)
14
+ */
15
+ public static withIamAuth = AgentCoreTrpcClient.withIamAuth<AppRouter>;
16
+
17
+ /**
18
+ * Creates a tRPC client with JWT (JSON Web Token) authentication.
19
+ *
20
+ * The WebSocket connection includes the JWT as a Bearer token in the Authorization header.
21
+ */
22
+ public static withJwtAuth = AgentCoreTrpcClient.withJwtAuth<AppRouter>;
23
+
24
+ /**
25
+ * Creates a tRPC client for use with a locally running <%- agentNameClassName %>.
26
+ */
27
+ public static local = WebSocketTrpcClient.create<AppRouter>;
28
+ }
@@ -0,0 +1,54 @@
1
+ import { createServer } from 'http';
2
+ import {
3
+ CreateHTTPContextOptions,
4
+ createHTTPHandler,
5
+ } from '@trpc/server/adapters/standalone';
6
+ import { appRouter, AppRouter } from './router.js';
7
+ import { WebSocketServer } from 'ws';
8
+ import cors from 'cors';
9
+ import {
10
+ CreateWSSContextFnOptions,
11
+ applyWSSHandler,
12
+ } from '@trpc/server/adapters/ws';
13
+ import { Context } from './init.js';
14
+
15
+ const PORT = parseInt(process.env.PORT || '8080');
16
+
17
+ const createContext = (
18
+ opts: CreateHTTPContextOptions | CreateWSSContextFnOptions,
19
+ ): Context => ({});
20
+
21
+ const handler = createHTTPHandler({
22
+ router: appRouter,
23
+ middleware: cors(),
24
+ createContext,
25
+ });
26
+
27
+ const server = createServer((req, res) => {
28
+ const url = new URL(req.url || '', `https://${req.headers.host}`);
29
+
30
+ // Handle bedrock agentcore health check
31
+ if (url.pathname === '/ping') {
32
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
33
+ res.end('Healthy');
34
+ return;
35
+ }
36
+
37
+ // Handle other requests with tRPC
38
+ handler(req, res);
39
+ });
40
+
41
+ const wss = new WebSocketServer({
42
+ server,
43
+ path: '/ws',
44
+ });
45
+
46
+ applyWSSHandler<AppRouter>({
47
+ wss,
48
+ router: appRouter,
49
+ createContext,
50
+ });
51
+
52
+ server.listen(PORT);
53
+
54
+ console.log(`TRPC server listening on port ${PORT}`);
@@ -0,0 +1,8 @@
1
+ import { initTRPC } from '@trpc/server';
2
+
3
+ // eslint-disable-next-line
4
+ export interface Context {}
5
+
6
+ export const t = initTRPC.context<Context>().create();
7
+
8
+ export const publicProcedure = t.procedure;
@@ -0,0 +1,34 @@
1
+ import { publicProcedure, t } from './init.js';
2
+ import { z } from 'zod';
3
+ import { zAsyncIterable } from './schema/z-async-iterable.js';
4
+ import { getAgent } from './agent.js';
5
+
6
+ export const router = t.router;
7
+
8
+ export const appRouter = router({
9
+ invoke: publicProcedure
10
+ .input(z.object({ message: z.string() }))
11
+ .output(
12
+ zAsyncIterable({
13
+ yield: z.string(),
14
+ tracked: false,
15
+ }),
16
+ )
17
+ .subscription(async function* (opts) {
18
+ const agent = getAgent();
19
+
20
+ for await (const event of agent.stream(opts.input.message)) {
21
+ if (
22
+ event.type === 'modelContentBlockDeltaEvent' &&
23
+ event.delta.type === 'textDelta'
24
+ ) {
25
+ yield event.delta.text;
26
+ } else if (event.type === 'modelMessageStopEvent') {
27
+ yield '\n';
28
+ }
29
+ }
30
+ return;
31
+ }),
32
+ });
33
+
34
+ export type AppRouter = typeof appRouter;
@@ -0,0 +1,77 @@
1
+ import { isTrackedEnvelope, tracked, TrackedEnvelope } from '@trpc/server';
2
+ import { z } from 'zod';
3
+
4
+ function isAsyncIterable<TValue, TReturn = unknown>(
5
+ value: unknown,
6
+ ): value is AsyncIterable<TValue, TReturn> {
7
+ return !!value && typeof value === 'object' && Symbol.asyncIterator in value;
8
+ }
9
+
10
+ const trackedEnvelopeSchema =
11
+ z.custom<TrackedEnvelope<unknown>>(isTrackedEnvelope);
12
+
13
+ /**
14
+ * A Zod schema helper designed specifically for validating async iterables. This schema ensures that:
15
+ * 1. The value being validated is an async iterable.
16
+ * 2. Each item yielded by the async iterable conforms to a specified type.
17
+ * 3. The return value of the async iterable, if any, also conforms to a specified type.
18
+ */
19
+ export function zAsyncIterable<
20
+ TYieldIn,
21
+ TYieldOut,
22
+ TReturnIn = void,
23
+ TReturnOut = void,
24
+ Tracked extends boolean = false,
25
+ >(opts: {
26
+ /**
27
+ * Validate the value yielded by the async generator
28
+ */
29
+ yield: z.ZodType<TYieldOut, TYieldIn>;
30
+ /**
31
+ * Validate the return value of the async generator
32
+ * @remark not applicable for subscriptions
33
+ */
34
+ return?: z.ZodType<TReturnOut, TReturnIn>;
35
+ /**
36
+ * Whether if the yielded values are tracked
37
+ * @remark only applicable for subscriptions
38
+ */
39
+ tracked?: Tracked;
40
+ }) {
41
+ return z
42
+ .custom<
43
+ AsyncIterable<
44
+ Tracked extends true ? TrackedEnvelope<TYieldIn> : TYieldIn,
45
+ TReturnIn
46
+ >
47
+ >((val) => isAsyncIterable(val))
48
+ .transform(async function* (iter) {
49
+ const iterator = iter[Symbol.asyncIterator]();
50
+ try {
51
+ let next;
52
+ while ((next = await iterator.next()) && !next.done) {
53
+ if (opts.tracked) {
54
+ const [id, data] = trackedEnvelopeSchema.parse(next.value);
55
+ yield tracked(id, await opts.yield.parseAsync(data));
56
+ continue;
57
+ }
58
+ yield opts.yield.parseAsync(next.value);
59
+ }
60
+ if (opts.return) {
61
+ return await opts.return.parseAsync(next.value);
62
+ }
63
+ return;
64
+ } finally {
65
+ await iterator.return?.();
66
+ }
67
+ }) as z.ZodType<
68
+ AsyncIterable<
69
+ Tracked extends true ? TrackedEnvelope<TYieldIn> : TYieldIn,
70
+ TReturnIn
71
+ >,
72
+ AsyncIterable<
73
+ Tracked extends true ? TrackedEnvelope<TYieldOut> : TYieldOut,
74
+ TReturnOut
75
+ >
76
+ >;
77
+ }
@@ -0,0 +1,16 @@
1
+ FROM public.ecr.aws/docker/library/node:lts-jod
2
+
3
+ WORKDIR /app
4
+
5
+ # Add AWS Distro for OpenTelemetry for observability
6
+ # https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/observability-configure.html
7
+ RUN npm install @aws/aws-distro-opentelemetry-node-autoinstrumentation@^0.7.0
8
+
9
+ # Copy bundled agent
10
+ COPY --from=workspace <%- distDir %>/bundle/agent/<%- name %>/index.js /app
11
+
12
+ EXPOSE 8080
13
+
14
+ # Auto-instrument with AWS Distro for OpenTelemetry
15
+ # https://aws-otel.github.io/docs/getting-started/js-sdk/trace-metric-auto-instr
16
+ CMD [ "node", "--require", "@aws/aws-distro-opentelemetry-node-autoinstrumentation/register", "index.js" ]
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+ import { GeneratorCallback, Tree } from '@nx/devkit';
6
+ import { TsStrandsAgentGeneratorSchema } from './schema';
7
+ import { NxGeneratorInfo } from '../../utils/nx';
8
+ export declare const TS_STRANDS_AGENT_GENERATOR_INFO: NxGeneratorInfo;
9
+ export declare const tsStrandsAgentGenerator: (tree: Tree, options: TsStrandsAgentGeneratorSchema) => Promise<GeneratorCallback>;
10
+ export default tsStrandsAgentGenerator;
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tsStrandsAgentGenerator = exports.TS_STRANDS_AGENT_GENERATOR_INFO = void 0;
4
+ const tslib_1 = require("tslib");
5
+ /**
6
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
7
+ * SPDX-License-Identifier: Apache-2.0
8
+ */
9
+ const devkit_1 = require("@nx/devkit");
10
+ const nx_1 = require("../../utils/nx");
11
+ const metrics_1 = require("../../utils/metrics");
12
+ const format_1 = require("../../utils/format");
13
+ const names_1 = require("../../utils/names");
14
+ const versions_1 = require("../../utils/versions");
15
+ const npm_scope_1 = require("../../utils/npm-scope");
16
+ const bundle_1 = require("../../utils/bundle/bundle");
17
+ const iac_1 = require("../../utils/iac");
18
+ const shared_constructs_1 = require("../../utils/shared-constructs");
19
+ const agent_core_constructs_1 = require("../../utils/agent-core-constructs/agent-core-constructs");
20
+ const port_1 = require("../../utils/port");
21
+ exports.TS_STRANDS_AGENT_GENERATOR_INFO = (0, nx_1.getGeneratorInfo)(__filename);
22
+ const tsStrandsAgentGenerator = (tree, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
23
+ var _a, _b;
24
+ const project = (0, nx_1.readProjectConfigurationUnqualified)(tree, options.project);
25
+ if (!tree.exists((0, devkit_1.joinPathFragments)(project.root, 'tsconfig.json'))) {
26
+ throw new Error(`Unsupported project ${options.project}. Expected a TypeScript project (with a tsconfig.json)`);
27
+ }
28
+ const defaultName = `${(0, names_1.kebabCase)(project.name.split('/').pop())}-agent`;
29
+ const name = (0, names_1.kebabCase)((_a = options.name) !== null && _a !== void 0 ? _a : defaultName);
30
+ const agentNameClassName = (0, names_1.toClassName)(name);
31
+ const agentTargetPrefix = options.name ? name : 'agent';
32
+ const targetSourceDirRelativeToProjectRoot = (0, devkit_1.joinPathFragments)('src', agentTargetPrefix);
33
+ const targetSourceDir = (0, devkit_1.joinPathFragments)(project.root, targetSourceDirRelativeToProjectRoot);
34
+ const relativeSourceDir = targetSourceDir.replace(project.root + '/', './');
35
+ const distDir = (0, devkit_1.joinPathFragments)('dist', project.root);
36
+ const computeType = (_b = options.computeType) !== null && _b !== void 0 ? _b : 'BedrockAgentCoreRuntime';
37
+ // Generate example agent
38
+ (0, devkit_1.generateFiles)(tree, (0, devkit_1.joinPathFragments)(__dirname, 'files', 'app'), targetSourceDir, {
39
+ name,
40
+ agentNameClassName,
41
+ distDir,
42
+ }, { overwriteStrategy: devkit_1.OverwriteStrategy.KeepExisting });
43
+ if (computeType === 'BedrockAgentCoreRuntime') {
44
+ const dockerImageTag = `${(0, npm_scope_1.getNpmScope)(tree)}-${name}:latest`;
45
+ // Add bundle target
46
+ (0, bundle_1.addTypeScriptBundleTarget)(tree, project, {
47
+ targetFilePath: `${targetSourceDirRelativeToProjectRoot}/index.ts`,
48
+ bundleOutputDir: (0, devkit_1.joinPathFragments)('agent', name),
49
+ });
50
+ // Add the Dockerfile
51
+ (0, devkit_1.generateFiles)(tree, (0, devkit_1.joinPathFragments)(__dirname, 'files', 'deploy'), targetSourceDir, {
52
+ distDir,
53
+ name,
54
+ }, { overwriteStrategy: devkit_1.OverwriteStrategy.KeepExisting });
55
+ const dockerTargetName = `${agentTargetPrefix}-docker`;
56
+ project.targets[dockerTargetName] = {
57
+ cache: true,
58
+ executor: 'nx:run-commands',
59
+ options: {
60
+ command: `docker build --platform linux/arm64 -t ${dockerImageTag} ${targetSourceDir} --build-context workspace=.`,
61
+ },
62
+ dependsOn: ['bundle'],
63
+ };
64
+ (0, nx_1.addDependencyToTargetIfNotPresent)(project, 'docker', dockerTargetName);
65
+ (0, nx_1.addDependencyToTargetIfNotPresent)(project, 'build', 'docker');
66
+ // Add shared constructs
67
+ const iacProvider = yield (0, iac_1.resolveIacProvider)(tree, options.iacProvider);
68
+ yield (0, shared_constructs_1.sharedConstructsGenerator)(tree, { iacProvider });
69
+ (0, agent_core_constructs_1.addAgentInfra)(tree, {
70
+ agentNameKebabCase: name,
71
+ agentNameClassName,
72
+ projectName: project.name,
73
+ dockerImageTag,
74
+ iacProvider,
75
+ });
76
+ }
77
+ // Add dependencies
78
+ (0, devkit_1.addDependenciesToPackageJson)(tree, (0, versions_1.withVersions)([
79
+ '@trpc/server',
80
+ '@trpc/client',
81
+ 'zod',
82
+ '@strands-agents/sdk',
83
+ 'ws',
84
+ 'cors',
85
+ '@aws-sdk/credential-providers',
86
+ 'aws4fetch',
87
+ '@modelcontextprotocol/sdk',
88
+ ]), (0, versions_1.withVersions)(['tsx', '@types/ws', '@types/cors']));
89
+ // NB: we assign the local dev port from 8081 as 8080 is used by vscode server, and so conflicts
90
+ // for those working on remote dev envirionments. The deployed agent in agentcore still runs on
91
+ // 8080 as per the agentcore contract.
92
+ const localDevPort = (0, port_1.assignPort)(tree, project, 8081);
93
+ (0, devkit_1.updateProjectConfiguration)(tree, project.name, Object.assign(Object.assign({}, project), { targets: Object.assign(Object.assign({}, project.targets), { [`${agentTargetPrefix}-serve`]: {
94
+ executor: 'nx:run-commands',
95
+ options: {
96
+ commands: [`tsx --watch ${relativeSourceDir}/index.ts`],
97
+ cwd: '{projectRoot}',
98
+ env: {
99
+ PORT: `${localDevPort}`,
100
+ },
101
+ },
102
+ continuous: true,
103
+ } }) }));
104
+ (0, nx_1.addComponentGeneratorMetadata)(tree, project.name, exports.TS_STRANDS_AGENT_GENERATOR_INFO, agentTargetPrefix, { port: localDevPort });
105
+ yield (0, metrics_1.addGeneratorMetricsIfApplicable)(tree, [
106
+ exports.TS_STRANDS_AGENT_GENERATOR_INFO,
107
+ ]);
108
+ yield (0, format_1.formatFilesInSubtree)(tree);
109
+ return () => {
110
+ (0, devkit_1.installPackagesTask)(tree);
111
+ };
112
+ });
113
+ exports.tsStrandsAgentGenerator = tsStrandsAgentGenerator;
114
+ exports.default = exports.tsStrandsAgentGenerator;
115
+ //# sourceMappingURL=generator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.js","sourceRoot":"","sources":["../../../../../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,EAAE,eAAe;oBACpB,GAAG,EAAE;wBACH,IAAI,EAAE,GAAG,YAAY,EAAE;qBACxB;iBACF;gBACD,UAAU,EAAE,IAAI;aACjB,OAEH,CAAC;IAEH,IAAA,kCAA6B,EAC3B,IAAI,EACJ,OAAO,CAAC,IAAI,EACZ,uCAA+B,EAC/B,iBAAiB,EACjB,EAAE,IAAI,EAAE,YAAY,EAAE,CACvB,CAAC;IAEF,MAAM,IAAA,yCAA+B,EAAC,IAAI,EAAE;QAC1C,uCAA+B;KAChC,CAAC,CAAC;IAEH,MAAM,IAAA,6BAAoB,EAAC,IAAI,CAAC,CAAC;IACjC,OAAO,GAAG,EAAE;QACV,IAAA,4BAAmB,EAAC,IAAI,CAAC,CAAC;IAC5B,CAAC,CAAC;AACJ,CAAC,CAAA,CAAC;AAlJW,QAAA,uBAAuB,2BAkJlC;AAEF,kBAAe,+BAAuB,CAAC"}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ import { IacProviderOption } from '../../utils/iac';
7
+
8
+ export type TsStrandsAgentComputeType = 'BedrockAgentCoreRuntime' | 'None';
9
+
10
+ export interface TsStrandsAgentGeneratorSchema {
11
+ project: string;
12
+ name?: string;
13
+ computeType?: TsStrandsAgentComputeType;
14
+ iacProvider: IacProviderOption;
15
+ }