forked from aws/agentcore-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseRemoveFlow.ts
More file actions
210 lines (181 loc) · 6.66 KB
/
useRemoveFlow.ts
File metadata and controls
210 lines (181 loc) · 6.66 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
import { ConfigIO, getWorkingDirectory } from '../../../../lib';
import type { AgentCoreProjectSpec } from '../../../../schema';
import { findStack } from '../../../cloudformation/stack-discovery';
import { getErrorMessage } from '../../../errors';
import { type Step, areStepsComplete, hasStepError } from '../../components';
import { withMinDuration } from '../../utils';
import { useCallback, useEffect, useMemo, useState } from 'react';
type RemovePhase = 'checking' | 'not-found' | 'confirm' | 'dry-run' | 'removing' | 'complete';
interface RemoveFlowOptions {
force: boolean;
dryRun: boolean;
}
interface RemoveFlowState {
phase: RemovePhase;
steps: Step[];
itemsToRemove: string[];
hasError: boolean;
isComplete: boolean;
hasDeployedResources: boolean;
confirmRemoval: () => void;
}
function getRemoveSteps(): Step[] {
return [{ label: 'Reset project schemas', status: 'pending' }];
}
function createDefaultProjectSpec(projectName: string): AgentCoreProjectSpec {
return {
name: projectName,
version: 1,
agents: [],
memories: [],
credentials: [],
};
}
export function useRemoveFlow({ force, dryRun }: RemoveFlowOptions): RemoveFlowState {
const [phase, setPhase] = useState<RemovePhase>('checking');
const [steps, setSteps] = useState<Step[]>([]);
const [itemsToRemove, setItemsToRemove] = useState<string[]>([]);
const [hasDeployedResources, setHasDeployedResources] = useState(false);
const [projectName, setProjectName] = useState<string>('');
const cwd = useMemo(() => getWorkingDirectory(), []);
// Check for existing project on mount
useEffect(() => {
if (phase !== 'checking') return;
const checkProject = async () => {
const configIO = new ConfigIO();
if (!configIO.configExists('project')) {
setPhase('not-found');
return;
}
// Identify what will be reset
const items: string[] = [];
let currentProjectName = '';
try {
const projectSpec = await configIO.readProjectSpec();
currentProjectName = projectSpec.name;
setProjectName(projectSpec.name);
items.push(`AgentCore project: ${projectSpec.name}`);
if (projectSpec.agents && projectSpec.agents.length > 0) {
items.push(`${projectSpec.agents.length} agent definition${projectSpec.agents.length > 1 ? 's' : ''}`);
}
if (projectSpec.memories && projectSpec.memories.length > 0) {
items.push(`${projectSpec.memories.length} memory provider${projectSpec.memories.length > 1 ? 's' : ''}`);
}
if (projectSpec.credentials && projectSpec.credentials.length > 0) {
items.push(`${projectSpec.credentials.length} credential${projectSpec.credentials.length > 1 ? 's' : ''}`);
}
} catch {
// Project exists but has issues - still allow reset
items.push('AgentCore project (corrupted or incomplete)');
}
// Check for gateways in mcp.json
if (configIO.configExists('mcp')) {
try {
const mcpSpec = await configIO.readMcpSpec();
const gatewayCount = mcpSpec.agentCoreGateways?.length ?? 0;
if (gatewayCount > 0) {
const targetCount = mcpSpec.agentCoreGateways.reduce(
(sum: number, gw: { targets?: unknown[] }) => sum + (gw.targets?.length ?? 0),
0
);
items.push(`${gatewayCount} gateway${gatewayCount > 1 ? 's' : ''}`);
if (targetCount > 0) {
items.push(`${targetCount} gateway target${targetCount > 1 ? 's' : ''}`);
}
}
} catch {
// mcp.json exists but has issues - still allow reset
}
}
items.push('All schemas will be reset to empty state');
setItemsToRemove(items);
// Check for deployed stacks per target
if (currentProjectName) {
try {
const targets = await configIO.readAWSDeploymentTargets();
for (const target of targets) {
const stack = await findStack(target.region, currentProjectName, target.name);
if (stack) {
setHasDeployedResources(true);
break;
}
}
} catch {
// Ignore errors checking for deployed resources
}
}
if (dryRun) {
setPhase('dry-run');
} else if (force) {
setSteps(getRemoveSteps());
setPhase('removing');
} else {
setPhase('confirm');
}
};
void checkProject();
}, [cwd, phase, dryRun, force]);
const confirmRemoval = useCallback(() => {
setSteps(getRemoveSteps());
setPhase('removing');
}, []);
const updateStep = (index: number, update: Partial<Step>) => {
setSteps(prev => prev.map((s, i) => (i === index ? { ...s, ...update } : s)));
};
// Main removal effect - resets all schemas to empty state
useEffect(() => {
if (phase !== 'removing') return;
let isRunning = false;
const runRemoval = async () => {
if (isRunning) return;
isRunning = true;
try {
// Reset all schemas to default empty state
updateStep(0, { status: 'running' });
try {
await withMinDuration(async () => {
const configIO = new ConfigIO();
// Reset agentcore.json (keep project name)
const defaultProjectSpec = createDefaultProjectSpec(projectName || 'Project');
await configIO.writeProjectSpec(defaultProjectSpec);
// Reset mcp.json gateways so a subsequent deploy can tear down gateway resources
if (configIO.configExists('mcp')) {
await configIO.writeMcpSpec({ agentCoreGateways: [] });
}
// Preserve aws-targets.json and deployed-state.json so that
// a subsequent `agentcore deploy` can tear down existing stacks.
});
updateStep(0, { status: 'success' });
} catch (err) {
updateStep(0, { status: 'error', error: getErrorMessage(err) });
setPhase('complete');
return;
}
setPhase('complete');
} catch (err) {
setSteps(prev => {
const runningIndex = prev.findIndex(s => s.status === 'running');
if (runningIndex >= 0) {
return prev.map((s, i) =>
i === runningIndex ? { ...s, status: 'error' as const, error: getErrorMessage(err) } : s
);
}
return prev;
});
setPhase('complete');
}
};
void runRemoval();
}, [phase, projectName]);
const hasError = hasStepError(steps);
const isComplete = areStepsComplete(steps);
return {
phase,
steps,
itemsToRemove,
hasError,
isComplete,
hasDeployedResources,
confirmRemoval,
};
}