-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcleanup.ts
More file actions
291 lines (257 loc) · 10.1 KB
/
Copy pathcleanup.ts
File metadata and controls
291 lines (257 loc) · 10.1 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
import { resolve } from "path";
import { fileURLToPath } from "url";
import { VAPI_BASE_URL, VAPI_ENV, VAPI_TOKEN } from "./config.ts";
import { loadState } from "./state.ts";
// ─────────────────────────────────────────────────────────────────────────────
// Dangerous Sync - Delete everything NOT in state file
// ─────────────────────────────────────────────────────────────────────────────
const REQUEST_DELAY_MS = 700;
async function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
async function vapiGet<T>(endpoint: string, debug = false): Promise<T> {
await sleep(REQUEST_DELAY_MS);
const response = await fetch(`${VAPI_BASE_URL}${endpoint}`, {
headers: { Authorization: `Bearer ${VAPI_TOKEN}` },
});
if (!response.ok) {
throw new Error(`GET ${endpoint} failed: ${response.status}`);
}
const data: unknown = await response.json();
if (debug && isRecord(data)) {
console.log(` DEBUG: Response keys: ${Object.keys(data)}`);
}
// Handle paginated responses - check various wrapper formats
if (isRecord(data)) {
// Try common pagination patterns: { data }, { results }, { items }, { structuredOutputs }
const possibleArrayKeys = [
"data",
"results",
"items",
"structuredOutputs",
"assistants",
"tools",
"squads",
];
for (const key of possibleArrayKeys) {
const wrappedValue = data[key];
if (Array.isArray(wrappedValue)) {
return wrappedValue as T;
}
}
}
return data as T;
}
async function vapiDelete(endpoint: string): Promise<void> {
await sleep(REQUEST_DELAY_MS);
const response = await fetch(`${VAPI_BASE_URL}${endpoint}`, {
method: "DELETE",
headers: { Authorization: `Bearer ${VAPI_TOKEN}` },
});
if (!response.ok && response.status !== 404) {
throw new Error(`DELETE ${endpoint} failed: ${response.status}`);
}
}
interface VapiResource {
id: string;
name?: string;
}
function readConfirmToken(argv: string[]): string | undefined {
// Accept either `--confirm <slug>` or `--confirm=<slug>`.
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "--confirm") return argv[i + 1];
if (arg?.startsWith("--confirm=")) return arg.slice("--confirm=".length);
}
return undefined;
}
async function main(): Promise<void> {
const dryRun = !process.argv.includes("--force");
const confirmToken = readConfirmToken(process.argv);
console.log(
"═══════════════════════════════════════════════════════════════",
);
console.log(`🧹 Vapi Cleanup - Environment: ${VAPI_ENV}`);
console.log(` API: ${VAPI_BASE_URL}`);
console.log(
` Mode: ${dryRun ? "🔒 DRY-RUN (use --force to delete)" : "⚠️ DELETING"}`,
);
console.log(
"═══════════════════════════════════════════════════════════════\n",
);
// Destructive cleanup must be double-gated. `--force` alone is not enough
// because it is easy to set habitually or copy from another command where
// it has a different meaning. Require `--confirm <slug>` so the caller has
// to name the org they intend to wipe.
if (!dryRun && confirmToken !== VAPI_ENV) {
console.error(
`❌ Refusing to run destructive cleanup without explicit confirmation.`,
);
console.error(
` Re-run with: npm run cleanup -- ${VAPI_ENV} --force --confirm ${VAPI_ENV}`,
);
process.exit(1);
}
const state = loadState();
// State values are ResourceState objects, not bare UUIDs. Extract each
// .uuid for the orphan-detection set.
const stateIds = new Set([
...Object.values(state.assistants).map((e) => e.uuid),
...Object.values(state.tools).map((e) => e.uuid),
...Object.values(state.structuredOutputs).map((e) => e.uuid),
...Object.values(state.squads).map((e) => e.uuid),
...Object.values(state.personalities).map((e) => e.uuid),
...Object.values(state.scenarios).map((e) => e.uuid),
...Object.values(state.simulations).map((e) => e.uuid),
...Object.values(state.simulationSuites).map((e) => e.uuid),
...Object.values(state.evals).map((e) => e.uuid),
]);
// A state file with zero tracked resources is almost always a fresh clone,
// a corrupted state, or a bootstrap that has not written yet. Deleting from
// that baseline would wipe the entire org. Block it explicitly.
if (!dryRun && stateIds.size === 0) {
console.error(
`❌ Refusing to run destructive cleanup: state file has 0 tracked resources.`,
);
console.error(
` This usually means the state was never bootstrapped. Run ` +
`\`npm run pull -- ${VAPI_ENV} --bootstrap\` first, then retry.`,
);
process.exit(1);
}
console.log(`📄 State file has ${stateIds.size} resource IDs to keep\n`);
const toDelete: {
type: string;
id: string;
name: string;
endpoint: string;
}[] = [];
// Fetch and compare each resource type
const resourceTypes = [
{
name: "assistants",
endpoint: "/assistant",
deleteEndpoint: "/assistant",
},
{ name: "tools", endpoint: "/tool", deleteEndpoint: "/tool" },
{
name: "structured outputs",
endpoint: "/structured-output",
deleteEndpoint: "/structured-output",
},
{ name: "squads", endpoint: "/squad", deleteEndpoint: "/squad" },
{
name: "personalities",
endpoint: "/eval/simulation/personality",
deleteEndpoint: "/eval/simulation/personality",
},
{
name: "scenarios",
endpoint: "/eval/simulation/scenario",
deleteEndpoint: "/eval/simulation/scenario",
},
{
name: "simulations",
endpoint: "/eval/simulation",
deleteEndpoint: "/eval/simulation",
},
{
name: "simulation suites",
endpoint: "/eval/simulation/suite",
deleteEndpoint: "/eval/simulation/suite",
},
{ name: "evals", endpoint: "/eval", deleteEndpoint: "/eval" },
];
for (const { name, endpoint, deleteEndpoint } of resourceTypes) {
console.log(`📥 Fetching ${name}...`);
try {
// Enable debug for structured outputs to see response format
const debug = name === "structured outputs";
const resources = await vapiGet<VapiResource[]>(endpoint, debug);
if (!Array.isArray(resources)) {
const resourceKeys = isRecord(resources)
? Object.keys(resources).join(", ")
: "(none)";
console.log(
` ⚠️ Unexpected response format for ${name}: ${typeof resources}, keys: ${resourceKeys}`,
);
continue;
}
const orphans = resources.filter((r) => !stateIds.has(r.id));
if (orphans.length > 0) {
console.log(
` Found ${orphans.length} orphaned ${name} (${resources.length} total)`,
);
for (const r of orphans) {
toDelete.push({
type: name,
id: r.id,
name: r.name || "(unnamed)",
endpoint: `${deleteEndpoint}/${r.id}`,
});
}
} else {
console.log(` ✅ All ${resources.length} ${name} are in state`);
}
} catch (error) {
console.log(` ⚠️ Could not fetch ${name}: ${error}`);
}
}
console.log(
"\n═══════════════════════════════════════════════════════════════",
);
if (toDelete.length === 0) {
console.log("✅ Nothing to delete - all resources match state file\n");
return;
}
console.log(`\n⚠️ Found ${toDelete.length} resources to delete:\n`);
for (const { type, id, name } of toDelete) {
console.log(` 🗑️ ${type}: ${name} (${id})`);
}
if (dryRun) {
console.log(
"\n═══════════════════════════════════════════════════════════════",
);
console.log("🔒 DRY-RUN MODE - No resources were deleted");
console.log(" To actually delete, run:");
console.log(
` npm run cleanup -- ${VAPI_ENV} --force --confirm ${VAPI_ENV}`,
);
console.log(
"═══════════════════════════════════════════════════════════════\n",
);
return;
}
console.log("\n🗑️ Deleting...\n");
let deleted = 0;
let failed = 0;
for (const { type, id, name, endpoint } of toDelete) {
try {
await vapiDelete(endpoint);
console.log(` ✅ Deleted ${type}: ${name}`);
deleted++;
} catch (error) {
console.log(` ❌ Failed to delete ${type}: ${name} - ${error}`);
failed++;
}
}
console.log(
"\n═══════════════════════════════════════════════════════════════",
);
console.log(`✅ Cleanup complete: ${deleted} deleted, ${failed} failed`);
console.log(
"═══════════════════════════════════════════════════════════════\n",
);
}
export { main as runCleanup };
const isMainModule =
resolve(process.argv[1] ?? "") === resolve(fileURLToPath(import.meta.url));
if (isMainModule) {
main().catch((error) => {
console.error("\n❌ Cleanup failed:", error);
process.exit(1);
});
}