-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathcommand.tsx
More file actions
298 lines (280 loc) · 11.9 KB
/
command.tsx
File metadata and controls
298 lines (280 loc) · 11.9 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
import { ValidationError, getWorkingDirectory, serializeResult } from '../../../lib';
import type {
BuildType,
ModelProvider,
NetworkMode,
ProtocolMode,
SDKFramework,
TargetLanguage,
} from '../../../schema';
import { LIFECYCLE_TIMEOUT_MAX, LIFECYCLE_TIMEOUT_MIN } from '../../../schema';
import { getErrorMessage } from '../../errors';
import { runCliCommand } from '../../telemetry/cli-command-run.js';
import {
AgentFramework,
AgentLanguage,
AgentProtocol,
AgentType,
MemoryType,
ModelProvider as ModelProviderEnum,
NetworkMode as NetworkModeEnum,
BuildType as TelemetryBuildType,
standardize,
} from '../../telemetry/schemas/common-shapes.js';
import { renderTUI } from '../../tui';
import { COMMAND_DESCRIPTIONS } from '../../tui/copy';
import { requireTTY } from '../../tui/guards';
import { parseCommaSeparatedList } from '../shared/vpc-utils';
import { type ProgressCallback, createProject, createProjectWithAgent, getDryRunInfo } from './action';
import type { CreateOptions } from './types';
import { validateCreateOptions } from './validate';
import type { Command } from '@commander-js/extra-typings';
import { Text, render } from 'ink';
/** Render CreateScreen for interactive TUI mode */
function handleCreateTUI(): Promise<void> {
return renderTUI({
initialRoute: { name: 'create' },
enterAltScreen: false,
actionOnBack: 'exit',
isInteractive: false,
});
}
/** Print completion summary after successful create */
function printCreateSummary(
projectName: string,
agentName: string | undefined,
language: string | undefined,
framework: string | undefined
): void {
const green = '\x1b[32m';
const cyan = '\x1b[36m';
const dim = '\x1b[2m';
const reset = '\x1b[0m';
console.log('');
// Created summary
console.log(`${dim}Created:${reset}`);
console.log(` ${projectName}/`);
if (agentName) {
const frameworkLabel = framework ?? 'agent';
const agentPath = `app/${agentName}/`;
const agentcorePath = 'agentcore/';
const maxPathLen = Math.max(agentPath.length, agentcorePath.length);
console.log(` ${agentPath.padEnd(maxPathLen)} ${dim}${language} agent (${frameworkLabel})${reset}`);
console.log(` ${agentcorePath.padEnd(maxPathLen)} ${dim}Config and CDK project${reset}`);
} else {
console.log(` agentcore/ ${dim}Config and CDK project${reset}`);
}
console.log('');
// Success and next steps
console.log(`${green}Project created successfully!${reset}`);
console.log('');
console.log('To continue, navigate to your new project:');
console.log('');
console.log(` ${cyan}cd ${projectName}${reset}`);
console.log(` ${cyan}agentcore${reset}`);
console.log('');
}
/** Handle CLI mode with progress output */
async function handleCreateCLI(options: CreateOptions): Promise<void> {
const cwd = options.outputDir ?? getWorkingDirectory();
const name = options.name ?? options.projectName;
const projectName = options.projectName ?? name;
// Handle dry-run mode (no telemetry for dry-run)
if (options.dryRun) {
const validation = validateCreateOptions(options, cwd);
if (!validation.valid) {
if (options.json) {
console.log(JSON.stringify({ success: false, error: validation.error }));
} else {
console.error(validation.error);
}
process.exit(1);
}
const result = getDryRunInfo({ name: name!, projectName, cwd, language: options.language });
if (options.json) {
console.log(JSON.stringify(serializeResult(result)));
} else if (result.success) {
console.log('Dry run - would create:');
for (const path of result.wouldCreate ?? []) {
console.log(` ${path}`);
}
}
process.exit(0);
}
const knownAttrs = {
agent_language: standardize(AgentLanguage, options.language),
agent_framework: standardize(AgentFramework, options.framework),
model_provider: standardize(ModelProviderEnum, options.modelProvider),
memory_type: standardize(MemoryType, options.memory ?? 'none'),
agent_protocol: standardize(AgentProtocol, options.protocol ?? 'http'),
build_type: standardize(TelemetryBuildType, options.build ?? 'codezip'),
agent_type: standardize(AgentType, options.type ?? 'create'),
network_mode: standardize(NetworkModeEnum, options.networkMode ?? 'public'),
has_agent: options.agent !== false,
};
await runCliCommand(
'create',
!!options.json,
async () => {
const validation = validateCreateOptions(options, cwd);
if (!validation.valid) {
throw new ValidationError(validation.error!);
}
const green = '\x1b[32m';
const reset = '\x1b[0m';
// Progress callback for real-time output
const onProgress: ProgressCallback | undefined = options.json
? undefined
: (step, status) => {
if (status === 'done') {
console.log(`${green}[done]${reset} ${step}`);
} else if (status === 'error') {
console.log(`\x1b[31m[error]${reset} ${step}`);
}
// 'start' is silent - we only show when done
};
// Commander.js --no-agent sets agent=false, not noAgent=true
const skipAgent = options.agent === false;
const result = skipAgent
? await createProject({
name: projectName!,
cwd,
skipGit: options.skipGit,
skipInstall: options.skipInstall,
onProgress,
})
: await createProjectWithAgent({
name: name!,
projectName,
cwd,
type: options.type as 'create' | 'import' | undefined,
buildType: (options.build as BuildType) ?? 'CodeZip',
language: (options.language as TargetLanguage) ?? (options.type === 'import' ? 'Python' : undefined),
framework: options.framework as SDKFramework | undefined,
modelProvider: options.modelProvider as ModelProvider | undefined,
apiKey: options.apiKey,
memory: (options.memory as 'none' | 'shortTerm' | 'longAndShortTerm') ?? 'none',
protocol: options.protocol as ProtocolMode | undefined,
agentId: options.agentId,
agentAliasId: options.agentAliasId,
region: options.region,
networkMode: options.networkMode as NetworkMode | undefined,
subnets: parseCommaSeparatedList(options.subnets),
securityGroups: parseCommaSeparatedList(options.securityGroups),
idleTimeout: options.idleTimeout ? Number(options.idleTimeout) : undefined,
maxLifetime: options.maxLifetime ? Number(options.maxLifetime) : undefined,
sessionStorageMountPath: options.sessionStorageMountPath,
withConfigBundle: options.withConfigBundle,
skipGit: options.skipGit,
skipInstall: options.skipInstall,
skipPythonSetup: options.skipPythonSetup,
onProgress,
});
if (!result.success) {
throw result.error;
}
if (options.json) {
console.log(JSON.stringify(result));
} else {
printCreateSummary(projectName!, result.agentName, options.language, options.framework);
if (options.skipInstall) {
console.log(
"\nDependency installation was skipped. Run 'npm install' in agentcore/cdk/ and 'uv sync' in your agent directory manually."
);
}
}
return knownAttrs;
},
knownAttrs
);
}
export const registerCreate = (program: Command) => {
program
.command('create')
.description(COMMAND_DESCRIPTIONS.create)
.option('--name <name>', 'Resource name (agent or harness) [non-interactive]')
.option(
'--project-name <name>',
'Project name (start with letter, alphanumeric only, max 23 chars) [non-interactive]'
)
.option('--no-agent', 'Skip agent creation [non-interactive]')
.option('--defaults', 'Use defaults (Python, Strands, Bedrock, no memory) [non-interactive]')
.option('--build <type>', 'Build type: CodeZip or Container (default: CodeZip) [non-interactive]')
.option('--language <language>', 'Target language: Python or TypeScript (default: Python) [non-interactive]')
.option(
'--framework <framework>',
'Agent framework (Strands, LangChain_LangGraph, GoogleADK, OpenAIAgents, VercelAI) [non-interactive]'
)
.option('--model-provider <provider>', 'Model provider (Bedrock, Anthropic, OpenAI, Gemini) [non-interactive]')
.option('--api-key <key>', 'API key for non-Bedrock providers [non-interactive]')
.option('--memory <option>', 'Memory option (none, shortTerm, longAndShortTerm) [non-interactive]')
.option('--protocol <protocol>', 'Protocol: HTTP, MCP, A2A, AGUI (default: HTTP) [non-interactive]')
.option('--type <type>', 'Agent type: create or import (default: create) [non-interactive]')
.option('--agent-id <id>', 'Bedrock Agent ID (required for --type import) [non-interactive]')
.option('--agent-alias-id <id>', 'Bedrock Agent Alias ID (required for --type import) [non-interactive]')
.option('--region <region>', 'AWS region for Bedrock Agent (required for --type import) [non-interactive]')
.option('--network-mode <mode>', 'Network mode (PUBLIC, VPC) [non-interactive]')
.option('--subnets <ids>', 'Comma-separated subnet IDs (required for VPC mode) [non-interactive]')
.option('--security-groups <ids>', 'Comma-separated security group IDs (required for VPC mode) [non-interactive]')
.option(
'--idle-timeout <seconds>',
`Idle session timeout in seconds (${LIFECYCLE_TIMEOUT_MIN}-${LIFECYCLE_TIMEOUT_MAX}) [non-interactive]`
)
.option(
'--max-lifetime <seconds>',
`Max instance lifetime in seconds (${LIFECYCLE_TIMEOUT_MIN}-${LIFECYCLE_TIMEOUT_MAX}) [non-interactive]`
)
.option(
'--session-storage-mount-path <path>',
'Absolute mount path for session filesystem storage under /mnt (e.g. /mnt/data) [non-interactive]'
)
.option('--with-config-bundle', 'Create a config bundle wired into the agent template [preview] [non-interactive]')
.option('--output-dir <dir>', 'Output directory (default: current directory) [non-interactive]')
.option('--skip-git', 'Skip git repository initialization [non-interactive]')
.option('--skip-python-setup', 'Skip Python virtual environment setup [non-interactive]')
.option('--skip-install', 'Skip all dependency installation (npm install, uv sync) [non-interactive]')
.option('--dry-run', 'Preview what would be created without making changes [non-interactive]')
.option('--json', 'Output as JSON [non-interactive]')
.action(async options => {
try {
// Apply defaults if --defaults flag is set
if (options.defaults) {
options.language = options.language ?? 'Python';
options.build = options.build ?? 'CodeZip';
options.framework = options.framework ?? 'Strands';
options.modelProvider = options.modelProvider ?? 'Bedrock';
options.memory = options.memory ?? 'none';
}
// Any flag triggers non-interactive CLI mode
const hasAnyFlag = Boolean(
options.name ??
options.projectName ??
(options.agent === false ? true : null) ??
options.defaults ??
options.build ??
options.language ??
options.framework ??
options.modelProvider ??
options.apiKey ??
options.memory ??
options.outputDir ??
options.skipGit ??
options.skipPythonSetup ??
options.skipInstall ??
options.dryRun ??
options.json
);
if (hasAnyFlag) {
// Default language to Python (only supported option) for CLI mode
options.language = options.language ?? 'Python';
await handleCreateCLI(options as CreateOptions);
} else {
requireTTY();
await handleCreateTUI();
}
} catch (error) {
render(<Text color="red">Error: {getErrorMessage(error)}</Text>);
process.exit(1);
}
});
};