-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathcommand.tsx
More file actions
321 lines (290 loc) · 11.2 KB
/
Copy pathcommand.tsx
File metadata and controls
321 lines (290 loc) · 11.2 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
import { ConfigIO } from '../../../lib';
import { listABTests, updateABTest } from '../../aws/agentcore-ab-tests';
import { stopBatchEvaluation } from '../../aws/agentcore-batch-evaluation';
import { getErrorMessage } from '../../errors';
import { handlePauseResume } from '../../operations/eval';
import type { OnlineEvalActionOptions } from '../../operations/eval';
import { COMMAND_DESCRIPTIONS } from '../../tui/copy';
import { requireProject } from '../../tui/guards';
import { getRegion } from '../shared/region-utils';
import { waitForRunningThenStop } from './promote-utils';
import type { Command } from '@commander-js/extra-typings';
import { Text, render } from 'ink';
import React from 'react';
function registerOnlineEvalSubcommand(parent: Command, action: 'pause' | 'resume') {
const description =
action === 'pause'
? 'Pause a deployed online eval config. Use --arn to target configs outside the project.'
: 'Resume a paused online eval config. Use --arn to target configs outside the project.';
const pastTense = action === 'pause' ? 'Paused' : 'Resumed';
parent
.command('online-eval')
.description(description)
.argument('[name]', 'Config name from project (not needed with --arn)')
.option('--arn <arn>', 'Online eval config ARN — operate without a project directory')
.option('--region <region>', 'AWS region override (auto-detected from ARN otherwise)')
.option('--json', 'Output as JSON')
.action(async (name: string | undefined, cliOptions: { arn?: string; region?: string; json?: boolean }) => {
if (!cliOptions.arn && !name) {
const error = 'Either a config name or --arn is required';
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error }));
} else {
render(<Text color="red">{error}</Text>);
}
process.exit(1);
}
if (!cliOptions.arn) {
requireProject();
}
const options: OnlineEvalActionOptions = {
name: name ?? '',
arn: cliOptions.arn,
region: cliOptions.region,
json: cliOptions.json,
};
try {
const result = await handlePauseResume(options, action);
if (cliOptions.json) {
console.log(JSON.stringify(result));
} else if (result.success) {
const displayName = cliOptions.arn ? result.configId : name;
console.log(`${pastTense} online eval config "${displayName}" (status: ${result.executionStatus})`);
} else {
render(<Text color="red">{result.error}</Text>);
}
process.exit(result.success ? 0 : 1);
} catch (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error: getErrorMessage(error) }));
} else {
render(<Text color="red">Error: {getErrorMessage(error)}</Text>);
}
process.exit(1);
}
});
}
async function resolveABTestId(
testName: string,
region: string
): Promise<{ abTestId: string; region: string; error?: string }> {
let projectName: string | undefined;
try {
const configIO = new ConfigIO();
const deployedState = await configIO.readDeployedState();
const awsTargets = await configIO.readAWSDeploymentTargets();
try {
const projectSpec = await configIO.readProjectSpec();
projectName = projectSpec.name;
} catch {
// Project spec unavailable
}
for (const [targetName, target] of Object.entries(deployedState.targets ?? {})) {
const abTests = target.resources?.abTests;
if (abTests?.[testName]) {
const targetConfig = awsTargets.find(t => t.name === targetName);
const resolvedRegion = targetConfig?.region ?? region;
return { abTestId: abTests[testName].abTestId, region: resolvedRegion };
}
}
} catch {
// No deployed state
}
try {
const result = await listABTests({ region, maxResults: 100 });
// Match against both prefixed name ({projectName}_{testName}) and bare testName (backwards compat)
const prefixedName = projectName ? `${projectName}_${testName}` : undefined;
const match =
result.abTests.find(t => prefixedName != null && t.name === prefixedName) ??
result.abTests.find(t => t.name === testName);
if (match) return { abTestId: match.abTestId, region };
} catch {
// API call failed
}
return { abTestId: '', region, error: `AB test "${testName}" not found in deployed state or API.` };
}
function registerABTestSubcommand(parent: Command, action: 'pause' | 'resume') {
const executionStatus = action === 'pause' ? 'PAUSED' : 'RUNNING';
const pastTense = action === 'pause' ? 'Paused' : 'Resumed';
parent
.command('ab-test')
.description(`[preview] ${action === 'pause' ? 'Pause' : 'Resume'} a deployed A/B test`)
.argument('<name>', 'AB test name')
.option('--region <region>', 'AWS region')
.option('--json', 'Output as JSON')
.action(async (name: string, cliOptions: { region?: string; json?: boolean }) => {
try {
const region = await getRegion(cliOptions.region);
const { abTestId, error } = await resolveABTestId(name, region);
if (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error }));
} else {
console.error(error);
}
process.exit(1);
}
const result = await updateABTest({
region,
abTestId,
executionStatus,
});
if (cliOptions.json) {
console.log(JSON.stringify({ success: true, ...result }));
} else {
console.log(`${pastTense} AB test "${name}" (execution: ${result.executionStatus})`);
}
process.exit(0);
} catch (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error: getErrorMessage(error) }));
} else {
console.error(`Error: ${getErrorMessage(error)}`);
}
process.exit(1);
}
});
}
export const registerPause = (program: Command) => {
const pauseCmd = program.command('pause').description(COMMAND_DESCRIPTIONS.pause);
registerOnlineEvalSubcommand(pauseCmd, 'pause');
registerABTestSubcommand(pauseCmd, 'pause');
};
export const registerResume = (program: Command) => {
const resumeCmd = program.command('resume').description(COMMAND_DESCRIPTIONS.resume);
registerOnlineEvalSubcommand(resumeCmd, 'resume');
registerABTestSubcommand(resumeCmd, 'resume');
};
export const registerStop = (program: Command) => {
const stopCmd = program.command('stop').description('Stop resources');
stopCmd
.command('ab-test')
.description('[preview] Stop a deployed A/B test permanently')
.argument('<name>', 'AB test name')
.option('--region <region>', 'AWS region')
.option('--json', 'Output as JSON')
.action(async (name: string, cliOptions: { region?: string; json?: boolean }) => {
try {
const region = await getRegion(cliOptions.region);
const { abTestId, error } = await resolveABTestId(name, region);
if (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error }));
} else {
console.error(error);
}
process.exit(1);
}
const result = await updateABTest({
region,
abTestId,
executionStatus: 'STOPPED',
});
if (cliOptions.json) {
console.log(JSON.stringify({ success: true, ...result }));
} else {
console.log(`Stopped AB test "${name}" (execution: ${result.executionStatus})`);
}
process.exit(0);
} catch (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error: getErrorMessage(error) }));
} else {
console.error(`Error: ${getErrorMessage(error)}`);
}
process.exit(1);
}
});
stopCmd
.command('batch-evaluation')
.description('[preview] Stop a running batch evaluation')
.requiredOption('-i, --id <id>', 'Batch evaluation ID to stop')
.option('--region <region>', 'AWS region (auto-detected if omitted)')
.option('--json', 'Output as JSON')
.action(async (cliOptions: { id: string; region?: string; json?: boolean }) => {
try {
const region = await getRegion(cliOptions.region);
const result = await stopBatchEvaluation({
region,
batchEvaluationId: cliOptions.id,
});
if (cliOptions.json) {
console.log(JSON.stringify({ success: true, ...result }));
} else {
console.log(`\nBatch evaluation stopped successfully`);
console.log(`ID: ${result.batchEvaluationId}`);
console.log(`Status: ${result.status}\n`);
}
process.exit(0);
} catch (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error: getErrorMessage(error) }));
} else {
render(<Text color="red">Error: {getErrorMessage(error)}</Text>);
}
process.exit(1);
}
});
};
export const registerPromote = (program: Command) => {
const promoteCmd = program.command('promote').description('Promote resources');
promoteCmd
.command('ab-test')
.description('Promote the winning treatment of an A/B test')
.argument('<name>', 'AB test name')
.option('--region <region>', 'AWS region')
.option('--json', 'Output as JSON')
.action(async (name: string, cliOptions: { region?: string; json?: boolean }) => {
try {
const region = await getRegion(cliOptions.region);
const { abTestId, error } = await resolveABTestId(name, region);
if (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error }));
} else {
console.error(error);
}
process.exit(1);
}
const result = await waitForRunningThenStop(region, abTestId, name);
// Apply promotion to agentcore.json
const { promoteABTestConfig } = await import('../../operations/ab-test/promote');
let promoted = false;
let mode: string | undefined;
let promotionDetail = '';
try {
const promoResult = await promoteABTestConfig(abTestId, name);
promoted = promoResult.promoted;
mode = promoResult.mode;
promotionDetail = promoResult.promotionDetail;
} catch {
// Config read/write failed
}
if (cliOptions.json) {
console.log(
JSON.stringify({
success: true,
...result,
...(mode && { mode }),
promoted,
...(promotionDetail && { promotionDetail }),
})
);
} else {
console.log(`AB test "${name}" stopped.`);
if (promoted) {
console.log(`\n${promotionDetail}`);
console.log(`\nRun: agentcore deploy`);
}
}
process.exit(0);
} catch (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error: getErrorMessage(error) }));
} else {
console.error(`Error: ${getErrorMessage(error)}`);
}
process.exit(1);
}
});
};