-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsetup.ts
More file actions
627 lines (535 loc) · 22.7 KB
/
Copy pathsetup.ts
File metadata and controls
627 lines (535 loc) · 22.7 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
import { confirm, input, password, select } from "@inquirer/prompts";
import { execSync } from "child_process";
import { existsSync, readdirSync } from "fs";
import { mkdir, rm, writeFile } from "fs/promises";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import searchableCheckbox, { BACK_SENTINEL } from "./searchableCheckbox.js";
import { slugify } from "./slug-utils.ts";
// ─────────────────────────────────────────────────────────────────────────────
// Constants
// ─────────────────────────────────────────────────────────────────────────────
const __dirname = dirname(fileURLToPath(import.meta.url));
const BASE_DIR = join(__dirname, "..");
const VAPI_REGIONS: Record<string, string> = {
us: "https://api.vapi.ai",
eu: "https://api.eu.vapi.ai",
};
let vapiBaseUrl = VAPI_REGIONS.us!;
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const SLUG_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
interface ResourceTypeDef {
key: string;
label: string;
endpoint: string;
}
const RESOURCE_TYPES: ResourceTypeDef[] = [
{ key: "assistants", label: "Assistants", endpoint: "/assistant" },
{ key: "tools", label: "Tools", endpoint: "/tool" },
{ key: "squads", label: "Squads", endpoint: "/squad" },
{
key: "structuredOutputs",
label: "Structured Outputs",
endpoint: "/structured-output",
},
{
key: "personalities",
label: "Personalities",
endpoint: "/eval/simulation/personality",
},
{
key: "scenarios",
label: "Scenarios",
endpoint: "/eval/simulation/scenario",
},
{ key: "simulations", label: "Simulations", endpoint: "/eval/simulation" },
{
key: "simulationSuites",
label: "Simulation Suites",
endpoint: "/eval/simulation/suite",
},
{
key: "evals",
label: "Evals",
endpoint: "/eval",
},
];
// ─────────────────────────────────────────────────────────────────────────────
// Terminal helpers
// ─────────────────────────────────────────────────────────────────────────────
const c = {
bold: (s: string) => `\x1b[1m${s}\x1b[0m`,
dim: (s: string) => `\x1b[2m${s}\x1b[0m`,
green: (s: string) => `\x1b[32m${s}\x1b[0m`,
yellow: (s: string) => `\x1b[33m${s}\x1b[0m`,
red: (s: string) => `\x1b[31m${s}\x1b[0m`,
cyan: (s: string) => `\x1b[36m${s}\x1b[0m`,
};
// ─────────────────────────────────────────────────────────────────────────────
// API client
// ─────────────────────────────────────────────────────────────────────────────
async function apiGet(token: string, endpoint: string): Promise<unknown> {
const response = await fetch(`${vapiBaseUrl}${endpoint}`, {
method: "GET",
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) {
const text = await response.text();
throw new Error(`API GET ${endpoint} failed (${response.status}): ${text}`);
}
return response.json();
}
async function validateToken(token: string): Promise<boolean> {
try {
await apiGet(token, "/assistant?limit=1");
return true;
} catch {
return false;
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Resource fetching
// ─────────────────────────────────────────────────────────────────────────────
interface ResourceSnapshot {
key: string;
label: string;
count: number;
resources: Record<string, unknown>[];
}
function normaliseList(data: unknown): Record<string, unknown>[] {
if (Array.isArray(data)) return data as Record<string, unknown>[];
if (
data &&
typeof data === "object" &&
"results" in data &&
Array.isArray((data as Record<string, unknown>).results)
) {
return (data as Record<string, unknown>).results as Record<
string,
unknown
>[];
}
return [];
}
async function fetchAllResourceSnapshots(
token: string,
): Promise<ResourceSnapshot[]> {
const results = await Promise.all(
RESOURCE_TYPES.map(async (type): Promise<ResourceSnapshot> => {
try {
const data = await apiGet(token, type.endpoint);
const list = normaliseList(data);
return {
key: type.key,
label: type.label,
count: list.length,
resources: list,
};
} catch {
return { key: type.key, label: type.label, count: 0, resources: [] };
}
}),
);
return results;
}
// ─────────────────────────────────────────────────────────────────────────────
// Slug helpers
// ─────────────────────────────────────────────────────────────────────────────
// ─────────────────────────────────────────────────────────────────────────────
// Dependency detection — scan selected resources for UUID references
// to resources that aren't yet selected
// ─────────────────────────────────────────────────────────────────────────────
function detectMissingDependencies(
snapshots: ResourceSnapshot[],
selectedIds: Set<string>,
): Map<string, Set<string>> {
const refs = new Map<string, Set<string>>();
const addRef = (type: string, value: unknown) => {
if (typeof value !== "string" || !UUID_RE.test(value)) return;
if (selectedIds.has(`${type}::${value}`)) return;
if (!refs.has(type)) refs.set(type, new Set());
refs.get(type)!.add(value);
};
for (const snap of snapshots) {
for (const r of snap.resources) {
const id = r.id as string;
if (!selectedIds.has(`${snap.key}::${id}`)) continue;
const model = r.model as Record<string, unknown> | undefined;
if (model && Array.isArray(model.toolIds)) {
for (const tid of model.toolIds) addRef("tools", tid);
}
if (Array.isArray(r.toolIds)) {
for (const tid of r.toolIds) addRef("tools", tid);
}
const ap = r.artifactPlan as Record<string, unknown> | undefined;
if (ap && Array.isArray(ap.structuredOutputIds)) {
for (const sid of ap.structuredOutputIds)
addRef("structuredOutputs", sid);
}
if (Array.isArray(r.members)) {
for (const m of r.members as Record<string, unknown>[]) {
addRef("assistants", m.assistantId);
if (Array.isArray(m.assistantDestinations)) {
for (const d of m.assistantDestinations as Record<
string,
unknown
>[]) {
addRef("assistants", d.assistantId);
}
}
}
}
if (Array.isArray(r.destinations)) {
for (const d of r.destinations as Record<string, unknown>[]) {
addRef("assistants", d.assistantId);
}
}
if (Array.isArray(r.assistantIds)) {
for (const aid of r.assistantIds) addRef("assistants", aid);
}
addRef("personalities", r.personalityId);
addRef("scenarios", r.scenarioId);
if (Array.isArray(r.simulationIds)) {
for (const sid of r.simulationIds) addRef("simulations", sid);
}
if (Array.isArray(r.evaluations)) {
for (const ev of r.evaluations as Record<string, unknown>[]) {
addRef("structuredOutputs", ev.structuredOutputId);
}
}
}
}
// Only keep refs to resources that actually exist in our snapshots
const knownIds = new Set<string>();
for (const snap of snapshots) {
for (const r of snap.resources) {
knownIds.add(`${snap.key}::${r.id as string}`);
}
}
const missing = new Map<string, Set<string>>();
for (const [type, uuids] of refs) {
const existing = new Set<string>();
for (const uuid of uuids) {
if (knownIds.has(`${type}::${uuid}`)) existing.add(uuid);
}
if (existing.size > 0) missing.set(type, existing);
}
return missing;
}
// ─────────────────────────────────────────────────────────────────────────────
// File system helpers
// ─────────────────────────────────────────────────────────────────────────────
async function writeEnvFile(
slug: string,
token: string,
baseUrl: string,
): Promise<void> {
const envPath = join(BASE_DIR, `.env.${slug}`);
let content = `VAPI_TOKEN=${token}\n`;
if (baseUrl !== VAPI_REGIONS.us) {
content += `VAPI_BASE_URL=${baseUrl}\n`;
}
await writeFile(envPath, content);
}
async function deleteExistingOrg(slug: string): Promise<void> {
const resourceDir = join(BASE_DIR, "resources", slug);
const stateFile = join(BASE_DIR, `.vapi-state.${slug}.json`);
if (existsSync(resourceDir)) {
await rm(resourceDir, { recursive: true, force: true });
}
if (existsSync(stateFile)) {
await rm(stateFile);
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Pull integration
// ─────────────────────────────────────────────────────────────────────────────
function invokePull(slug: string, selectedIds: Set<string>): void {
// Group selected resources by type so we can pass --id per invocation
const byType = new Map<string, string[]>();
for (const id of selectedIds) {
const sep = id.indexOf("::");
const typeKey = id.substring(0, sep);
const uuid = id.substring(sep + 2);
if (!byType.has(typeKey)) byType.set(typeKey, []);
byType.get(typeKey)!.push(uuid);
}
const binDir = join(BASE_DIR, "node_modules", ".bin");
const pathSep = process.platform === "win32" ? ";" : ":";
const env = {
...process.env,
PATH: `${binDir}${pathSep}${process.env.PATH ?? ""}`,
};
for (const [typeKey, uuids] of byType) {
const idArgs = uuids.flatMap((id) => ["--id", id]);
const cmd = [
"tsx",
"src/pull.ts",
slug,
"--force",
"--type",
typeKey,
...idArgs,
].join(" ");
execSync(cmd, { cwd: BASE_DIR, stdio: "inherit", env });
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Display helpers
// ─────────────────────────────────────────────────────────────────────────────
function resourceDisplayName(r: Record<string, unknown>): string {
// Top-level name (assistants, squads, structured outputs, simulations, etc.)
if (typeof r.name === "string" && r.name) return r.name;
// Tools: meaningful name is in function.name, type gives context
const fn = r.function as Record<string, unknown> | undefined;
const fnName = typeof fn?.name === "string" ? fn.name : "";
const rType = typeof r.type === "string" ? r.type : "";
if (fnName && rType) return `${fnName} (${rType})`;
if (fnName) return fnName;
if (rType) return `${rType} (${(r.id as string).slice(0, 8)}…)`;
// Last resort
return r.id as string;
}
// ─────────────────────────────────────────────────────────────────────────────
// Main wizard
// ─────────────────────────────────────────────────────────────────────────────
async function main(): Promise<void> {
if (!existsSync(join(BASE_DIR, "node_modules"))) {
console.log(c.dim("\n Installing dependencies...\n"));
execSync("npm install", { cwd: BASE_DIR, stdio: "inherit" });
}
console.log("");
console.log(
c.bold("═══════════════════════════════════════════════════════════════"),
);
console.log(c.bold(" Vapi GitOps — Setup Wizard"));
console.log(
c.bold("═══════════════════════════════════════════════════════════════"),
);
console.log("");
// ── Step 1: API key + region ────────────────────────────────────────
let trimmedKey = "";
// eslint-disable-next-line no-constant-condition
while (true) {
const apiKey = await password({
message: "Paste your Vapi private API key",
mask: "•",
validate: (value) => {
if (!value.trim()) return "API key is required";
return true;
},
});
trimmedKey = apiKey.trim();
console.log(c.dim(` Validating against ${vapiBaseUrl}…`));
const valid = await validateToken(trimmedKey);
if (valid) {
const region = vapiBaseUrl === VAPI_REGIONS.eu ? "EU" : "US";
console.log(c.green(` ✓ Connected to Vapi (${region})\n`));
break;
}
console.log(
c.red(" ✗ Could not authenticate — invalid key or wrong region.\n"),
);
const recovery = await select({
message: "What would you like to do?",
choices: [
{ name: "Try a different API key", value: "retry" as const },
{
name: `Switch to ${vapiBaseUrl === VAPI_REGIONS.eu ? "US" : "EU"} region and retry`,
value: "switch" as const,
},
{ name: "Cancel setup", value: "cancel" as const },
],
});
if (recovery === "cancel") {
console.log(c.dim("\n Setup cancelled."));
process.exit(0);
}
if (recovery === "switch") {
vapiBaseUrl =
vapiBaseUrl === VAPI_REGIONS.eu ? VAPI_REGIONS.us! : VAPI_REGIONS.eu!;
console.log(c.dim(` Switched to ${vapiBaseUrl}\n`));
// Re-validate same key against the new region
console.log(c.dim(` Validating against ${vapiBaseUrl}…`));
const retryValid = await validateToken(trimmedKey);
if (retryValid) {
const region = vapiBaseUrl === VAPI_REGIONS.eu ? "EU" : "US";
console.log(c.green(` ✓ Connected to Vapi (${region})\n`));
break;
}
console.log(
c.red(" ✗ Still could not authenticate. Try a different key.\n"),
);
}
// "retry" or failed switch → loop back to password prompt
}
// ── Step 2: Folder slug ───────────────────────────────────────────────
const rawSlug = await input({
message: "Folder name for this org (e.g. my-org, my-org-prod)",
validate: (value) => {
const slug = slugify(value);
if (!slug || !SLUG_RE.test(slug)) {
return "Must be lowercase alphanumeric with hyphens (e.g. my-org-name)";
}
return true;
},
transformer: (value) => {
const slug = slugify(value);
if (slug && slug !== value) return `${value} → ${c.dim(slug)}`;
return value;
},
});
const slug = slugify(rawSlug);
// Check if org already exists locally
const resourceDir = join(BASE_DIR, "resources", slug);
const stateFile = join(BASE_DIR, `.vapi-state.${slug}.json`);
if (existsSync(resourceDir) || existsSync(stateFile)) {
console.log(c.yellow(`\n ⚠ Org "${slug}" already exists locally.`));
const override = await confirm({
message: "Override? (deletes existing files and re-pulls)",
default: false,
});
if (!override) {
console.log(
`\n Use ${c.cyan(`npm run pull -- ${slug}`)} to update existing resources.`,
);
process.exit(0);
}
console.log(c.dim(" Removing existing files..."));
await deleteExistingOrg(slug);
console.log(c.green(" ✓ Cleaned up\n"));
} else {
console.log(c.green(`\n ✓ Will create: resources/${slug}/\n`));
}
// ── Step 3: Resource selection ────────────────────────────────────────
console.log(c.dim(" Fetching available resources...\n"));
const snapshots = await fetchAllResourceSnapshots(trimmedKey);
const nonEmpty = snapshots.filter((s) => s.count > 0);
if (nonEmpty.length === 0) {
console.log(c.yellow(" No resources found in this org."));
console.log(" Writing environment file only.\n");
await writeEnvFile(slug, trimmedKey, vapiBaseUrl);
await mkdir(resourceDir, { recursive: true });
printSummary(slug);
return;
}
const totalCount = nonEmpty.reduce((n, s) => n + s.count, 0);
// selectedIds: "typeKey::resourceUUID"
let selectedIds: Set<string>;
// eslint-disable-next-line no-constant-condition
while (true) {
const scope = await select({
message: "Which resources to download?",
choices: [
{
name: `All (${totalCount} resources across ${nonEmpty.length} types)`,
value: "all" as const,
},
{ name: "Let me pick…", value: "pick" as const },
],
});
if (scope === "pick") {
const allChoices = nonEmpty.flatMap((snap) =>
snap.resources.map((r) => ({
value: `${snap.key}::${r.id as string}`,
name: resourceDisplayName(r),
group: snap.label,
checked: false,
})),
);
const picked = await searchableCheckbox({
message: "Select resources",
choices: allChoices,
pageSize: 20,
});
if (picked.length === 1 && picked[0] === BACK_SENTINEL) continue;
selectedIds = new Set(picked);
} else {
selectedIds = new Set(
nonEmpty.flatMap((snap) =>
snap.resources.map((r) => `${snap.key}::${r.id as string}`),
),
);
}
break;
}
// ── Step 3b: Dependency detection (iterative) ─────────────────────────
console.log(c.dim("\n Checking dependencies...\n"));
let iterations = 0;
while (iterations < 5) {
const missing = detectMissingDependencies(snapshots, selectedIds);
if (missing.size === 0) break;
console.log(c.yellow(" ⚠ Selected resources reference additional items:"));
for (const [type, uuids] of missing) {
const def = RESOURCE_TYPES.find((t) => t.key === type);
console.log(` • ${uuids.size} ${def?.label ?? type}`);
}
console.log("");
const includeDeps = await confirm({
message: "Also download referenced resources?",
default: true,
});
if (!includeDeps) break;
for (const [type, uuids] of missing) {
for (const uuid of uuids) {
selectedIds.add(`${type}::${uuid}`);
}
}
iterations++;
}
// Show final download list
console.log("\n Download list:");
for (const snap of snapshots) {
const typeSelected = [...selectedIds].filter((v) =>
v.startsWith(`${snap.key}::`),
).length;
if (typeSelected > 0) {
console.log(
` ${c.green("✓")} ${snap.label} (${typeSelected}/${snap.count})`,
);
}
}
console.log("");
// ── Step 4: Write env file & pull ─────────────────────────────────────
await writeEnvFile(slug, trimmedKey, vapiBaseUrl);
console.log(c.green(` ✓ Created .env.${slug}\n`));
console.log(c.bold(" Downloading...\n"));
invokePull(slug, selectedIds);
// ── Done ──────────────────────────────────────────────────────────────
printSummary(slug);
}
function printSummary(slug: string): void {
console.log("");
console.log(
c.bold("═══════════════════════════════════════════════════════════════"),
);
console.log(c.bold(" ✅ Setup Complete!"));
console.log(
c.bold("═══════════════════════════════════════════════════════════════"),
);
console.log("");
console.log(` 📁 Resources: resources/${slug}/`);
console.log(` 🔑 Env file: .env.${slug}`);
console.log(` 📄 State file: .vapi-state.${slug}.json`);
console.log("");
console.log(" Next steps:");
console.log(
` ${c.cyan(`npm run pull -- ${slug}`)} Pull latest from Vapi`,
);
console.log(
` ${c.cyan(`npm run push -- ${slug}`)} Push local changes to Vapi`,
);
console.log(
` ${c.cyan(`npm run pull -- ${slug} --force`)} Force overwrite local files`,
);
console.log("");
}
main().catch((error) => {
console.error(
c.red(
`\n ✗ Setup failed: ${error instanceof Error ? error.message : error}`,
),
);
process.exit(1);
});