-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathruntime-stack.ts
More file actions
301 lines (253 loc) · 9.74 KB
/
Copy pathruntime-stack.ts
File metadata and controls
301 lines (253 loc) · 9.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import * as cdk from 'aws-cdk-lib';
import * as bedrockagentcore from 'aws-cdk-lib/aws-bedrockagentcore';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as ecr from 'aws-cdk-lib/aws-ecr';
import * as cognito from 'aws-cdk-lib/aws-cognito';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as s3deploy from 'aws-cdk-lib/aws-s3-deployment';
import * as cr from 'aws-cdk-lib/custom-resources';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';
export interface AgentCoreStackProps extends cdk.StackProps {
userPool: cognito.IUserPool;
userPoolClient: cognito.IUserPoolClient;
}
export class AgentCoreStack extends cdk.Stack {
public readonly agentRuntimeArn: string;
public readonly memoryId: string;
constructor(scope: Construct, id: string, props: AgentCoreStackProps) {
super(scope, id, props);
// Import resources from infra stack
const sourceBucketName = cdk.Fn.importValue('AgentCoreSourceBucketName');
const buildProjectName = cdk.Fn.importValue('AgentCoreBuildProjectName');
const buildProjectArn = cdk.Fn.importValue('AgentCoreBuildProjectArn');
const sourceBucket = s3.Bucket.fromBucketName(
this,
'SourceBucket',
sourceBucketName
);
// Use existing ECR repository
const agentRepository = ecr.Repository.fromRepositoryName(
this,
'AgentRepository',
'strands_agent_repository'
);
// Import existing IAM role
const agentRole = iam.Role.fromRoleArn(
this,
'AgentRuntimeRole',
cdk.Fn.importValue('AgentCoreRuntimeRoleArn')
);
// Get Cognito discovery URL for inbound auth
const region = cdk.Stack.of(this).region;
const discoveryUrl = `https://cognito-idp.${region}.amazonaws.com/${props.userPool.userPoolId}/.well-known/openid-configuration`;
// Create AgentCore Memory for short-term conversation history
const agentMemory = new bedrockagentcore.CfnMemory(this, 'AgentMemory', {
name: 'strands_agent_memory',
eventExpiryDuration: 365,
description: 'Short-term memory store for conversation history',
});
// Store Memory ID for exports
this.memoryId = agentMemory.attrMemoryId;
// Step 1: Upload only the essential agent files (exclude heavy directories)
const agentSourceUpload = new s3deploy.BucketDeployment(this, 'AgentSourceUpload', {
sources: [s3deploy.Source.asset('../agent', {
exclude: [
'venv/**', // Python virtual environment (can be 100+ MB)
'__pycache__/**', // Python cache files
'*.pyc', // Compiled Python files
'.git/**', // Git files
'node_modules/**', // Node modules if any
'.DS_Store', // macOS files
'*.log', // Log files
'build/**', // Build artifacts
'dist/**', // Distribution files
]
})],
destinationBucket: sourceBucket,
destinationKeyPrefix: 'agent-source/',
prune: false,
retainOnDelete: false,
});
// Step 2: Trigger CodeBuild to build the Docker image
const buildTrigger = new cr.AwsCustomResource(this, 'TriggerCodeBuild', {
onCreate: {
service: 'CodeBuild',
action: 'startBuild',
parameters: {
projectName: buildProjectName,
},
physicalResourceId: cr.PhysicalResourceId.of(`build-${Date.now()}`),
},
onUpdate: {
service: 'CodeBuild',
action: 'startBuild',
parameters: {
projectName: buildProjectName,
},
physicalResourceId: cr.PhysicalResourceId.of(`build-${Date.now()}`),
},
policy: cr.AwsCustomResourcePolicy.fromStatements([
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['codebuild:StartBuild', 'codebuild:BatchGetBuilds'],
resources: [buildProjectArn],
}),
]),
// Add timeout to prevent hanging
timeout: cdk.Duration.minutes(5),
});
// Ensure build happens after source upload
buildTrigger.node.addDependency(agentSourceUpload);
// Step 3: Wait for build to complete using a custom Lambda
const buildWaiterFunction = new lambda.Function(this, 'BuildWaiterFunction', {
runtime: lambda.Runtime.NODEJS_22_X,
handler: 'index.handler',
code: lambda.Code.fromInline(`
const { CodeBuildClient, BatchGetBuildsCommand } = require('@aws-sdk/client-codebuild');
exports.handler = async (event) => {
console.log('Event:', JSON.stringify(event));
if (event.RequestType === 'Delete') {
return sendResponse(event, 'SUCCESS', { Status: 'DELETED' });
}
const buildId = event.ResourceProperties.BuildId;
const maxWaitMinutes = 14; // Lambda timeout is 15 min, leave 1 min buffer
const pollIntervalSeconds = 30;
console.log('Waiting for build:', buildId);
const client = new CodeBuildClient({});
const startTime = Date.now();
const maxWaitMs = maxWaitMinutes * 60 * 1000;
while (Date.now() - startTime < maxWaitMs) {
try {
const response = await client.send(new BatchGetBuildsCommand({ ids: [buildId] }));
const build = response.builds[0];
const status = build.buildStatus;
console.log(\`Build status: \${status}\`);
if (status === 'SUCCEEDED') {
return await sendResponse(event, 'SUCCESS', { Status: 'SUCCEEDED' });
} else if (['FAILED', 'FAULT', 'TIMED_OUT', 'STOPPED'].includes(status)) {
return await sendResponse(event, 'FAILED', {}, \`Build failed with status: \${status}\`);
}
await new Promise(resolve => setTimeout(resolve, pollIntervalSeconds * 1000));
} catch (error) {
console.error('Error:', error);
return await sendResponse(event, 'FAILED', {}, error.message);
}
}
return await sendResponse(event, 'FAILED', {}, \`Build timeout after \${maxWaitMinutes} minutes\`);
};
async function sendResponse(event, status, data, reason) {
const responseBody = JSON.stringify({
Status: status,
Reason: reason || \`See CloudWatch Log Stream: \${event.LogStreamName}\`,
PhysicalResourceId: event.PhysicalResourceId || event.RequestId,
StackId: event.StackId,
RequestId: event.RequestId,
LogicalResourceId: event.LogicalResourceId,
Data: data
});
console.log('Response:', responseBody);
const https = require('https');
const url = require('url');
const parsedUrl = url.parse(event.ResponseURL);
return new Promise((resolve, reject) => {
const options = {
hostname: parsedUrl.hostname,
port: 443,
path: parsedUrl.path,
method: 'PUT',
headers: {
'Content-Type': '',
'Content-Length': responseBody.length
}
};
const request = https.request(options, (response) => {
console.log(\`Status: \${response.statusCode}\`);
resolve(data);
});
request.on('error', (error) => {
console.error('Error:', error);
reject(error);
});
request.write(responseBody);
request.end();
});
}
`),
timeout: cdk.Duration.minutes(15), // Lambda max timeout is 15 minutes
memorySize: 256,
});
buildWaiterFunction.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['codebuild:BatchGetBuilds'],
resources: [buildProjectArn],
}));
// Custom resource that invokes the waiter Lambda
const buildWaiter = new cdk.CustomResource(this, 'BuildWaiter', {
serviceToken: buildWaiterFunction.functionArn,
properties: {
BuildId: buildTrigger.getResponseField('build.id'),
},
});
buildWaiter.node.addDependency(buildTrigger);
// Create the AgentCore Runtime with inbound auth
const agentRuntime = new bedrockagentcore.CfnRuntime(this, 'AgentRuntime', {
agentRuntimeName: 'strands_agent',
description: 'AgentCore runtime using Strands Agents framework with Cognito authentication',
roleArn: agentRole.roleArn,
// Container configuration
agentRuntimeArtifact: {
containerConfiguration: {
containerUri: `${agentRepository.repositoryUri}:latest`,
},
},
// Network configuration - PUBLIC for internet access
networkConfiguration: {
networkMode: 'PUBLIC',
},
// Protocol configuration
protocolConfiguration: 'HTTP',
// Inbound authentication configuration
authorizerConfiguration: {
customJwtAuthorizer: {
discoveryUrl: discoveryUrl,
allowedClients: [props.userPoolClient.userPoolClientId],
},
},
// Environment variables
environmentVariables: {
AGENTCORE_MEMORY_ID: agentMemory.attrMemoryId,
LOG_LEVEL: 'INFO',
IMAGE_VERSION: new Date().toISOString(),
},
tags: {
Environment: 'dev',
Application: 'strands-agent',
},
});
// Ensure AgentCore runtime is created after build completes
agentRuntime.node.addDependency(buildWaiter);
// Store runtime info for frontend
this.agentRuntimeArn = agentRuntime.attrAgentRuntimeArn;
new cdk.CfnOutput(this, 'AgentRuntimeArn', {
value: agentRuntime.attrAgentRuntimeArn,
description: 'AgentCore Runtime ARN',
exportName: 'AgentCoreRuntimeArn',
});
new cdk.CfnOutput(this, 'EndpointName', {
value: 'DEFAULT',
description: 'Runtime Endpoint Name (DEFAULT auto-created)',
exportName: 'AgentCoreEndpointName',
});
new cdk.CfnOutput(this, 'Region', {
value: region,
description: 'AWS Region for AgentCore Runtime',
exportName: 'AgentCoreRegion',
});
new cdk.CfnOutput(this, 'AgentMemoryId', {
value: agentMemory.attrMemoryId,
description: 'AgentCore Memory ID for session management',
exportName: 'AgentCoreMemoryId',
});
}
}