forked from aws/agentcore-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactions.ts
More file actions
489 lines (438 loc) · 16.8 KB
/
Copy pathactions.ts
File metadata and controls
489 lines (438 loc) · 16.8 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import { ConfigIO, SecureCredentials } from '../../../lib';
import type { AgentCoreMcpSpec, DeployedState } from '../../../schema';
import { validateAwsCredentials } from '../../aws/account';
import { createSwitchableIoHost } from '../../cdk/toolkit-lib';
import {
buildDeployedState,
getStackOutputs,
parseAgentOutputs,
parseEvaluatorOutputs,
parseGatewayOutputs,
parseMemoryOutputs,
parseOnlineEvalOutputs,
parsePolicyEngineOutputs,
parsePolicyOutputs,
} from '../../cloudformation';
import { getErrorMessage } from '../../errors';
import { ExecLogger } from '../../logging';
import {
bootstrapEnvironment,
buildCdkProject,
checkBootstrapNeeded,
checkStackDeployability,
getAllCredentials,
hasIdentityApiProviders,
hasIdentityOAuthProviders,
performStackTeardown,
setupApiKeyProviders,
setupOAuth2Providers,
setupTransactionSearch,
synthesizeCdk,
validateProject,
} from '../../operations/deploy';
import { formatTargetStatus, getGatewayTargetStatuses } from '../../operations/deploy/gateway-status';
import type { DeployResult } from './types';
export interface ValidatedDeployOptions {
target: string;
autoConfirm?: boolean;
verbose?: boolean;
plan?: boolean;
diff?: boolean;
onProgress?: (step: string, status: 'start' | 'success' | 'error') => void;
onResourceEvent?: (message: string) => void;
}
const AGENT_NEXT_STEPS = ['agentcore invoke', 'agentcore status'];
const MEMORY_ONLY_NEXT_STEPS = ['agentcore add agent', 'agentcore status'];
export async function handleDeploy(options: ValidatedDeployOptions): Promise<DeployResult> {
let toolkitWrapper = null;
const logger = new ExecLogger({ command: 'deploy' });
const { onProgress } = options;
let currentStepName = '';
const startStep = (name: string) => {
currentStepName = name;
logger.startStep(name);
onProgress?.(name, 'start');
};
const endStep = (status: 'success' | 'error', message?: string) => {
logger.endStep(status, message);
onProgress?.(currentStepName, status);
};
try {
const configIO = new ConfigIO();
// Load targets and find the specified one
startStep('Load deployment target');
const targets = await configIO.readAWSDeploymentTargets();
const target = targets.find(t => t.name === options.target);
if (!target) {
endStep('error', `Target "${options.target}" not found`);
logger.finalize(false);
return {
success: false,
error: `Target "${options.target}" not found in aws-targets.json`,
logPath: logger.getRelativeLogPath(),
};
}
endStep('success');
// Read project spec for gateway information (used later for deploy step name and outputs)
let mcpSpec: Pick<AgentCoreMcpSpec, 'agentCoreGateways'> | null = null;
try {
const projectSpec = await configIO.readProjectSpec();
mcpSpec = { agentCoreGateways: projectSpec.agentCoreGateways };
} catch {
// Project read failed — no gateways
}
// Preflight: validate project
startStep('Validate project');
const context = await validateProject();
endStep('success');
// Teardown confirmation: if this is a teardown deploy, require --yes
if (context.isTeardownDeploy && !options.autoConfirm) {
logger.finalize(false);
return {
success: false,
error:
'This will delete all deployed resources and the CloudFormation stack. Run with --yes to confirm teardown.',
logPath: logger.getRelativeLogPath(),
};
}
// Validate AWS credentials (deferred for teardown deploys until after confirmation)
if (context.isTeardownDeploy) {
startStep('Validate AWS credentials');
await validateAwsCredentials();
endStep('success');
}
// Build CDK project
startStep('Build CDK project');
await buildCdkProject(context.cdkProject);
endStep('success');
// Set up identity providers before CDK synth (CDK needs credential ARNs)
let identityKmsKeyArn: string | undefined;
// Read runtime credentials from process.env (enables non-interactive deploy with -y)
const neededCredentials = getAllCredentials(context.projectSpec);
const envCredentials: Record<string, string> = {};
for (const cred of neededCredentials) {
const value = process.env[cred.envVarName];
if (value) {
envCredentials[cred.envVarName] = value;
}
}
const runtimeCredentials =
Object.keys(envCredentials).length > 0 ? new SecureCredentials(envCredentials) : undefined;
// Unified credentials map for deployed state (both API Key and OAuth)
const deployedCredentials: Record<
string,
{ credentialProviderArn: string; clientSecretArn?: string; callbackUrl?: string }
> = {};
if (hasIdentityApiProviders(context.projectSpec)) {
startStep('Creating credentials...');
const identityResult = await setupApiKeyProviders({
projectSpec: context.projectSpec,
configBaseDir: configIO.getConfigRoot(),
region: target.region,
runtimeCredentials,
enableKmsEncryption: true,
});
if (identityResult.hasErrors) {
const errorResult = identityResult.results.find(r => r.status === 'error');
const errorMsg =
errorResult?.error && typeof errorResult.error === 'string' ? errorResult.error : 'Identity setup failed';
endStep('error', errorMsg);
logger.finalize(false);
return { success: false, error: errorMsg, logPath: logger.getRelativeLogPath() };
}
identityKmsKeyArn = identityResult.kmsKeyArn;
// Collect API Key credential ARNs for deployed state
for (const result of identityResult.results) {
if (result.credentialProviderArn) {
deployedCredentials[result.providerName] = {
credentialProviderArn: result.credentialProviderArn,
};
}
}
endStep('success');
}
// Set up OAuth credential providers if needed
if (hasIdentityOAuthProviders(context.projectSpec)) {
startStep('Creating OAuth credentials...');
const oauthResult = await setupOAuth2Providers({
projectSpec: context.projectSpec,
configBaseDir: configIO.getConfigRoot(),
region: target.region,
runtimeCredentials,
});
if (oauthResult.hasErrors) {
// Log detailed error internally, return sanitized message to avoid leaking OAuth details
const errorResult = oauthResult.results.find(r => r.status === 'error');
logger.log(`OAuth setup error: ${errorResult?.error ?? 'unknown'}`, 'error');
const errorMsg = 'OAuth credential setup failed. Check the log for details.';
endStep('error', errorMsg);
logger.finalize(false);
return { success: false, error: errorMsg, logPath: logger.getRelativeLogPath() };
}
// Collect OAuth credential ARNs for deployed state
for (const result of oauthResult.results) {
if (result.credentialProviderArn) {
deployedCredentials[result.providerName] = {
credentialProviderArn: result.credentialProviderArn,
clientSecretArn: result.clientSecretArn,
callbackUrl: result.callbackUrl,
};
}
}
endStep('success');
}
// Write credential ARNs to deployed state before CDK synth so the template can read them
if (Object.keys(deployedCredentials).length > 0) {
const existingPreSynthState = await configIO.readDeployedState().catch(() => ({ targets: {} }) as DeployedState);
const targetState = existingPreSynthState.targets?.[target.name] ?? { resources: {} };
targetState.resources ??= {};
targetState.resources.credentials = deployedCredentials;
if (identityKmsKeyArn) targetState.resources.identityKmsKeyArn = identityKmsKeyArn;
await configIO.writeDeployedState({
...existingPreSynthState,
targets: { ...existingPreSynthState.targets, [target.name]: targetState },
});
}
// Synthesize CloudFormation templates
startStep('Synthesize CloudFormation');
const switchableIoHost = options.verbose ? createSwitchableIoHost() : undefined;
const synthResult = await synthesizeCdk(
context.cdkProject,
switchableIoHost ? { ioHost: switchableIoHost.ioHost } : undefined
);
toolkitWrapper = synthResult.toolkitWrapper;
const stackNames = synthResult.stackNames;
if (stackNames.length === 0) {
endStep('error', 'No stacks found');
logger.finalize(false);
return { success: false, error: 'No stacks found to deploy', logPath: logger.getRelativeLogPath() };
}
const stackName = stackNames[0]!;
endStep('success');
// Check if bootstrap needed
startStep('Check bootstrap status');
const bootstrapCheck = await checkBootstrapNeeded(context.awsTargets);
if (bootstrapCheck.needsBootstrap) {
if (options.autoConfirm) {
logger.log('Bootstrap needed, auto-confirming...');
await bootstrapEnvironment(toolkitWrapper, target);
} else {
endStep('error', 'Bootstrap required');
logger.finalize(false);
return {
success: false,
error: 'AWS environment needs bootstrapping. Run with --yes to auto-bootstrap.',
logPath: logger.getRelativeLogPath(),
};
}
}
endStep('success');
// Check stack deployability
startStep('Check stack status');
const deployabilityCheck = await checkStackDeployability(target.region, stackNames);
if (!deployabilityCheck.canDeploy) {
endStep('error', deployabilityCheck.message);
logger.finalize(false);
return {
success: false,
error: deployabilityCheck.message ?? 'Stack is not in a deployable state',
logPath: logger.getRelativeLogPath(),
};
}
endStep('success');
// Plan mode: stop after synth and checks, don't deploy
if (options.plan) {
logger.finalize(true);
await toolkitWrapper.dispose();
toolkitWrapper = null;
return {
success: true,
targetName: target.name,
stackName,
logPath: logger.getRelativeLogPath(),
};
}
// Diff mode: run cdk diff and exit without deploying
if (options.diff) {
startStep('Run CDK diff');
const diffIoHost = switchableIoHost ?? createSwitchableIoHost();
let hasDiffContent = false;
diffIoHost.setOnRawMessage((code, _level, message) => {
if (!message) return;
// I4002: formatted diff per stack, I4001: overall diff summary
if (code === 'CDK_TOOLKIT_I4002' || code === 'CDK_TOOLKIT_I4001') {
hasDiffContent = true;
console.log(message);
}
});
diffIoHost.setVerbose(true);
await toolkitWrapper.diff();
if (!hasDiffContent) {
console.log('No stack differences detected.');
}
diffIoHost.setVerbose(false);
diffIoHost.setOnRawMessage(null);
endStep('success');
logger.finalize(true);
await toolkitWrapper.dispose();
toolkitWrapper = null;
return {
success: true,
targetName: target.name,
stackName,
logPath: logger.getRelativeLogPath(),
};
}
// Deploy
const hasGateways = (mcpSpec?.agentCoreGateways?.length ?? 0) > 0;
const deployStepName = hasGateways ? 'Deploying gateways...' : 'Deploy to AWS';
startStep(deployStepName);
// Enable verbose output for resource-level events
if (switchableIoHost && options.onResourceEvent) {
switchableIoHost.setOnMessage(msg => {
options.onResourceEvent!(msg.message);
});
switchableIoHost.setVerbose(true);
}
await toolkitWrapper.deploy();
// Disable verbose output
if (switchableIoHost) {
switchableIoHost.setVerbose(false);
switchableIoHost.setOnMessage(null);
}
endStep('success');
if (context.isTeardownDeploy) {
// After deploying the empty spec, destroy the stack entirely
startStep('Tear down stack');
const teardown = await performStackTeardown(target.name);
if (!teardown.success) {
const teardownError = typeof teardown.error === 'string' ? teardown.error : 'Unknown teardown error';
endStep('error', teardownError);
logger.finalize(false);
return {
success: false,
error: `Stack teardown failed: ${teardownError}`,
logPath: logger.getRelativeLogPath(),
};
}
endStep('success');
logger.finalize(true);
return {
success: true,
targetName: target.name,
stackName,
logPath: logger.getRelativeLogPath(),
};
}
// Get stack outputs and persist state
startStep('Persist deployment state');
const outputs = await getStackOutputs(target.region, stackName);
const agentNames = context.projectSpec.agents?.map(a => a.name) || [];
const agents = parseAgentOutputs(outputs, agentNames, stackName);
// Parse memory outputs
const memoryNames = (context.projectSpec.memories ?? []).map(m => m.name);
const memories = parseMemoryOutputs(outputs, memoryNames);
if (memoryNames.length > 0 && Object.keys(memories).length !== memoryNames.length) {
logger.log(
`Deployed-state missing outputs for ${memoryNames.length - Object.keys(memories).length} memory(ies).`,
'warn'
);
}
// Parse evaluator outputs
const evaluatorNames = (context.projectSpec.evaluators ?? []).map(e => e.name);
const evaluators = parseEvaluatorOutputs(outputs, evaluatorNames);
// Parse online eval config outputs
const onlineEvalNames = (context.projectSpec.onlineEvalConfigs ?? []).map(c => c.name);
const onlineEvalConfigs = parseOnlineEvalOutputs(outputs, onlineEvalNames);
// Parse policy engine outputs
const policyEngineSpecs = context.projectSpec.policyEngines ?? [];
const policyEngineNames = policyEngineSpecs.map(pe => pe.name);
const policyEngines = parsePolicyEngineOutputs(outputs, policyEngineNames);
// Parse policy outputs
const policySpecs = policyEngineSpecs.flatMap(pe =>
pe.policies.map(p => ({ engineName: pe.name, policyName: p.name }))
);
const policies = parsePolicyOutputs(outputs, policySpecs);
// Parse gateway outputs
const gatewaySpecs =
mcpSpec?.agentCoreGateways?.reduce(
(acc, gateway) => {
acc[gateway.name] = gateway;
return acc;
},
{} as Record<string, unknown>
) ?? {};
const gateways = parseGatewayOutputs(outputs, gatewaySpecs);
const existingState = await configIO.readDeployedState().catch(() => undefined);
const deployedState = buildDeployedState({
targetName: target.name,
stackName,
agents,
gateways,
existingState,
identityKmsKeyArn,
credentials: deployedCredentials,
memories,
evaluators,
onlineEvalConfigs,
policyEngines,
policies,
});
await configIO.writeDeployedState(deployedState);
// Show gateway URLs and target sync status
if (Object.keys(gateways).length > 0) {
const gatewayUrls = Object.entries(gateways)
.map(([name, gateway]) => `${name}: ${gateway.gatewayArn}`)
.join(', ');
logger.log(`Gateway URLs: ${gatewayUrls}`);
// Query target sync statuses (non-blocking)
for (const [, gateway] of Object.entries(gateways)) {
const statuses = await getGatewayTargetStatuses(gateway.gatewayId, target.region);
for (const targetStatus of statuses) {
logger.log(` ${targetStatus.name}: ${formatTargetStatus(targetStatus.status)}`);
}
}
}
endStep('success');
// Post-deploy: Enable CloudWatch Transaction Search (non-blocking, silent)
const nextSteps = agentNames.length > 0 ? [...AGENT_NEXT_STEPS] : [...MEMORY_ONLY_NEXT_STEPS];
const notes: string[] = [];
if (agentNames.length > 0 || hasGateways) {
try {
const tsResult = await setupTransactionSearch({
region: target.region,
accountId: target.account,
agentNames,
hasGateways,
});
if (tsResult.error) {
logger.log(`Transaction search setup warning: ${tsResult.error}`, 'warn');
} else {
notes.push(
'Transaction search enabled. It takes ~10 minutes for transaction search to be fully active and for traces from invocations to be indexed.'
);
}
} catch (err: unknown) {
logger.log(`Transaction search setup failed: ${getErrorMessage(err)}`, 'warn');
}
}
logger.finalize(true);
return {
success: true,
targetName: target.name,
stackName,
outputs,
logPath: logger.getRelativeLogPath(),
nextSteps,
notes,
};
} catch (err: unknown) {
logger.log(getErrorMessage(err), 'error');
logger.finalize(false);
return { success: false, error: getErrorMessage(err), logPath: logger.getRelativeLogPath() };
} finally {
if (toolkitWrapper) {
await toolkitWrapper.dispose();
}
}
}