forked from aws/agentcore-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseRemoveFlow.ts
More file actions
196 lines (170 loc) · 6.52 KB
/
Copy pathuseRemoveFlow.ts
File metadata and controls
196 lines (170 loc) · 6.52 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
import { ConfigIO, getWorkingDirectory } from '../../../../lib';
import { findStack } from '../../../cloudformation/stack-discovery';
import { getErrorMessage } from '../../../errors';
import { createDefaultProjectSpec } from '../../../project';
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' }];
}
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.runtimes && projectSpec.runtimes.length > 0) {
items.push(`${projectSpec.runtimes.length} agent definition${projectSpec.runtimes.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' : ''}`);
}
// Check for gateways in agentcore.json
const gatewayCount = projectSpec.agentCoreGateways?.length ?? 0;
if (gatewayCount > 0) {
const targetCount = projectSpec.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' : ''}`);
}
}
if (projectSpec.policyEngines && projectSpec.policyEngines.length > 0) {
items.push(
`${projectSpec.policyEngines.length} policy engine${projectSpec.policyEngines.length > 1 ? 's' : ''}`
);
const totalPolicies = projectSpec.policyEngines.reduce((sum, e) => sum + (e.policies?.length ?? 0), 0);
if (totalPolicies > 0) {
items.push(`${totalPolicies} polic${totalPolicies > 1 ? 'ies' : 'y'}`);
}
}
} catch {
// Project exists but has issues - still allow reset
items.push('AgentCore project (corrupted or incomplete)');
}
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);
// 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,
};
}