-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathpull.ts
More file actions
1103 lines (971 loc) · 39.2 KB
/
Copy pathpull.ts
File metadata and controls
1103 lines (971 loc) · 39.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
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { execSync } from "child_process";
import { existsSync, readdirSync, statSync } from "fs";
import { mkdir, writeFile } from "fs/promises";
import { dirname, join, relative, resolve } from "path";
import { fileURLToPath } from "url";
import { stringify } from "yaml";
import {
APPLY_FILTER,
BASE_DIR,
BOOTSTRAP_SYNC,
loadIgnorePatterns,
matchesIgnore,
RESOURCES_DIR,
VAPI_BASE_URL,
VAPI_ENV,
VAPI_TOKEN,
} from "./config.ts";
import { credentialReverseMap, replaceCredentialRefs } from "./credentials.ts";
import { hashPayload, loadState, saveState, upsertState } from "./state.ts";
import type { ResourceState, ResourceType, StateFile } from "./types.ts";
// ─────────────────────────────────────────────────────────────────────────────
// Types
// ─────────────────────────────────────────────────────────────────────────────
export interface VapiResource {
id: string;
name?: string;
[key: string]: unknown;
}
// Fields to remove from resources before saving (server-managed or computed fields)
const EXCLUDED_FIELDS = [
"id",
"orgId",
"createdAt",
"updatedAt",
"analyticsMetadata",
"isDeleted",
// Computed/derived fields that shouldn't be synced back
"isServerUrlSecretSet", // Computed: indicates if server URL secret is set
"workflowIds", // Server-managed: workflows are a separate resource type
];
// Map resource types to their API endpoints
const ENDPOINT_MAP: Record<ResourceType, string> = {
tools: "/tool",
structuredOutputs: "/structured-output",
assistants: "/assistant",
squads: "/squad",
personalities: "/eval/simulation/personality",
scenarios: "/eval/simulation/scenario",
simulations: "/eval/simulation",
simulationSuites: "/eval/simulation/suite",
evals: "/eval",
};
// Map resource types to their folder paths (relative to resources/)
const FOLDER_MAP: Record<ResourceType, string> = {
tools: "tools",
structuredOutputs: "structuredOutputs",
assistants: "assistants",
squads: "squads",
personalities: "simulations/personalities",
scenarios: "simulations/scenarios",
simulations: "simulations/tests",
simulationSuites: "simulations/suites",
evals: "evals",
};
// ─────────────────────────────────────────────────────────────────────────────
// Git Helpers (detect locally changed files to skip during pull)
// ─────────────────────────────────────────────────────────────────────────────
function gitCmd(args: string): string {
return execSync(`git ${args}`, {
cwd: BASE_DIR,
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
}).trim();
}
function isGitRepo(): boolean {
try {
gitCmd("rev-parse --is-inside-work-tree");
return true;
} catch {
return false;
}
}
function gitHasCommits(): boolean {
try {
gitCmd("rev-parse HEAD");
return true;
} catch {
return false;
}
}
// Returns relative paths of all locally modified, deleted, or untracked files.
//
// Two flags matter here:
//
// - `--untracked-files=all`: by default, `git status --porcelain` collapses
// untracked directories to a single entry like `?? resources/<org>/`. In a
// fresh-clone workflow where the resource tree is not yet tracked, that
// collapsed entry would not match the per-file lookup downstream and locally
// edited files would silently get overwritten on pull. `=all` forces git to
// list each individual file.
//
// - `-z` (null-terminated): so filenames containing spaces, newlines, or
// quotes parse correctly without the ad-hoc quote/arrow stripping that the
// plain porcelain format requires. With `-z`, renames emit two separate
// null-terminated records: `XY new\0old\0` — we want `new`, so we consume
// the record after any `R`/`C` status.
function getLocallyChangedFiles(): Set<string> {
const status = gitCmd("status --porcelain --untracked-files=all -z");
const files = new Set<string>();
const records = status.split("\0");
for (let i = 0; i < records.length; i++) {
const record = records[i];
if (!record) continue;
// Each record is `XY <path>`. For R/C statuses, the NEXT record is the
// original path, which we skip.
const x = record[0];
const filePath = record.slice(3);
if (filePath) files.add(filePath);
if (x === "R" || x === "C") {
// Skip the following "from" path record
i++;
}
}
return files;
}
// ─────────────────────────────────────────────────────────────────────────────
// API Functions
// ─────────────────────────────────────────────────────────────────────────────
export async function fetchAllResources(
resourceType: ResourceType,
): Promise<VapiResource[]> {
const endpoint = ENDPOINT_MAP[resourceType];
const url = `${VAPI_BASE_URL}${endpoint}`;
const response = await fetch(url, {
method: "GET",
headers: {
Authorization: `Bearer ${VAPI_TOKEN}`,
},
});
if (!response.ok) {
const errorText = await response.text();
let apiMessage = errorText;
try {
const parsed = JSON.parse(errorText);
if (typeof parsed.message === "string") apiMessage = parsed.message;
} catch {}
throw new Error(
`API GET ${endpoint} failed (${response.status}): ${apiMessage}`,
);
}
const data = await response.json();
// Handle paginated response format (e.g., structured-output returns { results: [], metadata: {} })
if (
data &&
typeof data === "object" &&
"results" in data &&
Array.isArray(data.results)
) {
return data.results as VapiResource[];
}
return data as VapiResource[];
}
// ─────────────────────────────────────────────────────────────────────────────
// Credential Fetching
// ─────────────────────────────────────────────────────────────────────────────
interface VapiCredential {
id: string;
name?: string;
provider: string;
[key: string]: unknown;
}
async function fetchCredentials(): Promise<VapiCredential[]> {
const url = `${VAPI_BASE_URL}/credential`;
const response = await fetch(url, {
method: "GET",
headers: { Authorization: `Bearer ${VAPI_TOKEN}` },
});
if (!response.ok) {
const errorText = await response.text();
let apiMessage = errorText;
try {
const parsed = JSON.parse(errorText);
if (typeof parsed.message === "string") apiMessage = parsed.message;
} catch {}
throw new Error(
`API GET /credential failed (${response.status}): ${apiMessage}`,
);
}
return (await response.json()) as VapiCredential[];
}
function credentialSlug(cred: VapiCredential): string {
const base = cred.name || cred.provider || "credential";
return slugify(base);
}
async function pullCredentials(state: StateFile): Promise<void> {
console.log("\n🔑 Pulling credentials...");
const credentials = await fetchCredentials();
console.log(` Found ${credentials.length} credentials in Vapi`);
const newSection: Record<string, ResourceState> = {};
// Build reverse map from existing state to preserve slug stability
const existingReverse = new Map<string, string>();
for (const [slug, entry] of Object.entries(state.credentials)) {
existingReverse.set(entry.uuid, slug);
}
for (const cred of credentials) {
// Reuse existing slug if available, otherwise generate a new one
let slug = existingReverse.get(cred.id);
if (!slug) {
slug = credentialSlug(cred);
}
// Preserve existing hash metadata if the slug+uuid pair survives.
const prior = state.credentials[slug];
newSection[slug] =
prior && prior.uuid === cred.id
? prior
: { uuid: cred.id, lastPulledAt: new Date().toISOString() };
console.log(` 🔑 ${slug} -> ${cred.id}`);
}
state.credentials = newSection;
}
// ─────────────────────────────────────────────────────────────────────────────
// Naming & Slug Generation
// ─────────────────────────────────────────────────────────────────────────────
function slugify(name: string): string {
return name
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.replace(/-+/g, "-");
}
function extractName(resource: VapiResource): string | undefined {
if (resource.name) return resource.name;
// Tools store their name under function.name
const fn = resource.function as Record<string, unknown> | undefined;
if (fn?.name && typeof fn.name === "string") return fn.name;
return undefined;
}
function generateResourceId(resource: VapiResource): string {
const name = extractName(resource);
const shortId = resource.id.slice(0, 8);
return name ? `${slugify(name)}-${shortId}` : `resource-${shortId}`;
}
export function extractBaseSlug(resourceId: string): string {
const match = resourceId.match(/^(.*)-([a-f0-9]{8})$/i);
return match?.[1] ?? resourceId;
}
export function resourceIdMatchesName(
resourceId: string,
resource: VapiResource,
): boolean {
const name = extractName(resource);
if (!name) return true;
return extractBaseSlug(resourceId) === slugify(name);
}
export function listExistingResourceIds(resourceType: ResourceType): string[] {
const dir = join(RESOURCES_DIR, FOLDER_MAP[resourceType]);
if (!existsSync(dir)) return [];
const walk = (currentDir: string, ids: string[]): string[] => {
const entries = readdirSync(currentDir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(currentDir, entry.name);
if (entry.isDirectory()) {
walk(fullPath, ids);
continue;
}
if (!/\.(yml|yaml|md)$/.test(entry.name)) {
continue;
}
const relativePath = relative(dir, fullPath);
ids.push(relativePath.replace(/\.(yml|yaml|md)$/, ""));
}
return ids;
};
return walk(dir, []);
}
// When pulling a new environment, a resource may already exist on disk under a
// different UUID suffix (e.g., `end-call-tool-8102e715` from dev). Match by
// name-slug so we reuse the existing file instead of creating a duplicate.
//
// State-awareness guard: if a name-matching file is already claimed in state
// by a *different* UUID, refuse adoption. Without this guard, two dashboard
// resources sharing a name (e.g. a Duplicate-Assistant click, or any
// platform auto-seed of a same-named twin) collapse onto the same file —
// the second pull silently overwrites the first's content and reassigns
// the slug's state mapping to the new UUID, orphaning the original.
// Falling through to `generateResourceId` (caller) produces a deterministic
// `<name>-<uuid8>` slug per UUID, so the second resource gets its own file.
export function findExistingResourceId(
existingResourceIds: string[],
resource: VapiResource,
stateSection: Record<string, ResourceState>,
): string | undefined {
const name = extractName(resource);
if (!name) return undefined;
const nameSlug = slugify(name);
const matches = existingResourceIds.filter(
(id) => extractBaseSlug(id) === nameSlug,
);
if (matches.length === 0) return undefined;
// A file is adoptable when it is either unclaimed in state (cross-env
// pull: file shipped from dev, this env has no prior state for it) or
// already claimed by THIS resource's UUID. The same-UUID branch is
// defensive — in the production code path the caller's
// `reverseMap.get(resource.id)` short-circuits this case, so we only
// reach this function when the UUID is unknown to state. Keep the
// branch anyway so the helper is correct in isolation.
// A file claimed by a *different* UUID is not adoptable — adopting it
// would clobber the existing resource's content and state mapping.
const adoptable = matches.filter((id) => {
const claim = stateSection[id]?.uuid;
return claim === undefined || claim === resource.id;
});
return adoptable.length === 1 ? adoptable[0] : undefined;
}
function removeUuidMappings(
stateSection: Record<string, ResourceState>,
uuid: string,
keepResourceId?: string,
): void {
for (const [resourceId, entry] of Object.entries(stateSection)) {
if (entry.uuid === uuid && resourceId !== keepResourceId) {
delete stateSection[resourceId];
}
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Resource Processing
// ─────────────────────────────────────────────────────────────────────────────
export function cleanResource(resource: VapiResource): Record<string, unknown> {
const cleaned: Record<string, unknown> = {};
// Preserve `null` values: the API uses `null` to represent an intentionally
// cleared field (e.g. `voicemailMessage: null`), which is semantically
// different from an absent field. Stripping it on pull would cause the next
// push to drop the clear and re-apply any prior value still on the server.
for (const [key, value] of Object.entries(resource)) {
if (!EXCLUDED_FIELDS.includes(key) && value !== undefined) {
cleaned[key] = value;
}
}
return cleaned;
}
function buildReverseMap(
state: StateFile,
resourceType: ResourceType,
): Map<string, string> {
// uuid -> resourceId
const map = new Map<string, string>();
const stateSection = state[resourceType];
for (const [resourceId, entry] of Object.entries(stateSection)) {
map.set(entry.uuid, resourceId);
}
return map;
}
// ─────────────────────────────────────────────────────────────────────────────
// Reference Resolution (UUID -> resourceId)
// ─────────────────────────────────────────────────────────────────────────────
function resolveReferencesToResourceIds(
resource: Record<string, unknown>,
state: StateFile,
): Record<string, unknown> {
const toolsMap = buildReverseMap(state, "tools");
const assistantsMap = buildReverseMap(state, "assistants");
const structuredOutputsMap = buildReverseMap(state, "structuredOutputs");
const personalitiesMap = buildReverseMap(state, "personalities");
const scenariosMap = buildReverseMap(state, "scenarios");
const simulationsMap = buildReverseMap(state, "simulations");
const resolved = { ...resource };
// Resolve toolIds in model
if (resolved.model && typeof resolved.model === "object") {
const model = { ...(resolved.model as Record<string, unknown>) };
if (Array.isArray(model.toolIds)) {
model.toolIds = model.toolIds.map(
(uuid: string) => toolsMap.get(uuid) ?? uuid,
);
}
resolved.model = model;
}
// Resolve structuredOutputIds in artifactPlan
if (resolved.artifactPlan && typeof resolved.artifactPlan === "object") {
const artifactPlan = {
...(resolved.artifactPlan as Record<string, unknown>),
};
if (Array.isArray(artifactPlan.structuredOutputIds)) {
artifactPlan.structuredOutputIds = artifactPlan.structuredOutputIds.map(
(uuid: string) => structuredOutputsMap.get(uuid) ?? uuid,
);
}
resolved.artifactPlan = artifactPlan;
}
// Resolve assistantIds in structured outputs (API returns camelCase)
if (Array.isArray(resolved.assistantIds)) {
resolved.assistant_ids = (resolved.assistantIds as string[]).map(
(uuid: string) => assistantsMap.get(uuid) ?? uuid,
);
delete resolved.assistantIds;
}
// Resolve assistantId in tool destinations (handoff tools)
if (Array.isArray(resolved.destinations)) {
resolved.destinations = (
resolved.destinations as Record<string, unknown>[]
).map((dest) => {
if (typeof dest.assistantId === "string") {
return {
...dest,
assistantId: assistantsMap.get(dest.assistantId) ?? dest.assistantId,
};
}
return dest;
});
}
// Resolve members[].assistantId in squads
if (Array.isArray(resolved.members)) {
resolved.members = (resolved.members as Record<string, unknown>[]).map(
(member) => {
const resolvedMember = { ...member };
if (typeof member.assistantId === "string") {
resolvedMember.assistantId =
assistantsMap.get(member.assistantId) ?? member.assistantId;
}
// Resolve assistantDestinations[].assistantId
if (Array.isArray(member.assistantDestinations)) {
resolvedMember.assistantDestinations = (
member.assistantDestinations as Record<string, unknown>[]
).map((dest) => {
if (typeof dest.assistantId === "string") {
return {
...dest,
assistantId:
assistantsMap.get(dest.assistantId) ?? dest.assistantId,
};
}
return dest;
});
}
return resolvedMember;
},
);
}
// Resolve personalityId in simulations
if (typeof resolved.personalityId === "string") {
resolved.personalityId =
personalitiesMap.get(resolved.personalityId) ?? resolved.personalityId;
}
// Resolve scenarioId in simulations
if (typeof resolved.scenarioId === "string") {
resolved.scenarioId =
scenariosMap.get(resolved.scenarioId) ?? resolved.scenarioId;
}
// Resolve simulationIds in simulation suites
if (Array.isArray(resolved.simulationIds)) {
resolved.simulationIds = (resolved.simulationIds as string[]).map(
(uuid: string) => simulationsMap.get(uuid) ?? uuid,
);
}
return resolved;
}
// ─────────────────────────────────────────────────────────────────────────────
// File Writing
// ─────────────────────────────────────────────────────────────────────────────
/**
* Extract system prompt from model.messages if present
* Returns the system prompt content and the cleaned data (without system message)
*/
function extractSystemPrompt(data: Record<string, unknown>): {
systemPrompt: string | null;
cleanedData: Record<string, unknown>;
} {
const model = data.model as Record<string, unknown> | undefined;
if (!model || !Array.isArray(model.messages)) {
return { systemPrompt: null, cleanedData: data };
}
const messages = model.messages as Array<{ role?: string; content?: string }>;
const systemMessage = messages.find((m) => m.role === "system");
if (!systemMessage?.content) {
return { systemPrompt: null, cleanedData: data };
}
// Remove system message from messages array
const remainingMessages = messages.filter((m) => m.role !== "system");
// Create cleaned data without system message
const cleanedData = { ...data };
const cleanedModel = { ...model };
if (remainingMessages.length > 0) {
cleanedModel.messages = remainingMessages;
} else {
delete cleanedModel.messages;
}
cleanedData.model = cleanedModel;
return { systemPrompt: systemMessage.content, cleanedData };
}
// Deterministic key ordering: 'name' first, then alphabetical
// Applied to all levels (top-level and nested objects) for stable diffs
const sortMapEntries = (a: { key: unknown }, b: { key: unknown }): number => {
const aKey = String(a.key);
const bKey = String(b.key);
if (aKey === "name") return -1;
if (bKey === "name") return 1;
return aKey.localeCompare(bKey);
};
const YAML_OPTIONS = {
lineWidth: 0,
defaultStringType: "PLAIN" as const,
defaultKeyType: "PLAIN" as const,
sortMapEntries,
};
async function writeResourceFile(
resourceType: ResourceType,
resourceId: string,
data: Record<string, unknown>,
): Promise<string> {
const folderPath = FOLDER_MAP[resourceType];
const dir = join(RESOURCES_DIR, folderPath);
// For assistants, check if there's a system prompt to extract
if (resourceType === "assistants") {
const { systemPrompt, cleanedData } = extractSystemPrompt(data);
if (systemPrompt) {
// Write as .md with frontmatter
const filePath = join(dir, `${resourceId}.md`);
await mkdir(dirname(filePath), { recursive: true });
const yamlContent = stringify(cleanedData, YAML_OPTIONS);
const mdContent = `---\n${yamlContent}---\n\n${systemPrompt}\n`;
await writeFile(filePath, mdContent);
return filePath;
}
}
// Default: write as .yml
const filePath = join(dir, `${resourceId}.yml`);
await mkdir(dirname(filePath), { recursive: true });
const yamlContent = stringify(data, YAML_OPTIONS);
await writeFile(filePath, yamlContent);
return filePath;
}
// ─────────────────────────────────────────────────────────────────────────────
// Pull Functions
// ─────────────────────────────────────────────────────────────────────────────
export interface PullStats {
created: number;
updated: number;
skipped: number;
}
export interface PullOptions {
force?: boolean;
bootstrap?: boolean;
typeFilter?: ResourceType[];
resourceIds?: string[];
}
export interface PullResult {
state: StateFile;
stats: Record<ResourceType, PullStats>;
force: boolean;
bootstrap: boolean;
}
export async function pullResourceType(
resourceType: ResourceType,
state: StateFile,
options: {
changedFiles?: Set<string>;
force?: boolean;
bootstrap?: boolean;
resourceIds?: string[];
} = {},
): Promise<PullStats> {
const { changedFiles, force, bootstrap, resourceIds } = options;
console.log(`\n📥 Pulling ${resourceType}...`);
const allResources = (await fetchAllResources(resourceType)) ?? [];
if (!Array.isArray(allResources)) {
console.log(` ⚠️ No ${resourceType} found (API returned non-array)`);
return { created: 0, updated: 0, skipped: 0 };
}
let resources = allResources;
if (resourceIds?.length) {
const requestedIds = new Set(resourceIds);
resources = allResources.filter((resource) =>
requestedIds.has(resource.id),
);
const foundIds = new Set(resources.map((resource) => resource.id));
const missingIds = resourceIds.filter((id) => !foundIds.has(id));
console.log(
` Found ${resources.length} matching ${resourceType} in Vapi (requested ${resourceIds.length})`,
);
if (missingIds.length > 0) {
console.log(
` ⚠️ Requested IDs not found for ${resourceType}: ${missingIds.join(", ")}`,
);
}
} else {
console.log(` Found ${resources.length} ${resourceType} in Vapi`);
}
const reverseMap = buildReverseMap(state, resourceType);
const credReverse = credentialReverseMap(state);
const newStateSection: Record<string, ResourceState> = resourceIds?.length
? { ...state[resourceType] }
: {};
const existingResourceIds = bootstrap
? []
: listExistingResourceIds(resourceType);
let created = 0;
let updated = 0;
let skipped = 0;
for (const resource of resources) {
// Check if we already have this resource in state (by UUID)
let resourceId = reverseMap.get(resource.id);
if (resourceId && !resourceIdMatchesName(resourceId, resource)) {
delete newStateSection[resourceId];
resourceId = undefined;
}
if (!resourceId) {
// Reuse an existing file's resourceId if the name matches (cross-env
// pull). The adoption guard needs both prior-pull claims AND
// intra-pull claims so the fix is iteration-order-independent:
// - `state[resourceType]` carries prior-pull claims loaded from
// disk. Without this, if the dashboard returns the new same-name
// twin BEFORE the tracked one, the new twin sees `newStateSection`
// empty and clobbers the tracked file. The customer's mudflap-prod
// 5-Rileys investigation surfaced this ordering dependency.
// - `newStateSection` carries intra-pull claims from earlier
// iterations. Handles the converse (tracked-then-twin order).
// Spread `newStateSection` last so it wins when both have the same
// slug — the in-flight value is the more authoritative claim during
// this pull (e.g. an earlier iteration rekeyed the slug to a new UUID).
const claimView = { ...state[resourceType], ...newStateSection };
resourceId = bootstrap
? generateResourceId(resource)
: (findExistingResourceId(existingResourceIds, resource, claimView) ??
generateResourceId(resource));
}
const isNew =
!reverseMap.get(resource.id) ||
!resourceIdMatchesName(resourceId, resource);
removeUuidMappings(newStateSection, resource.id, resourceId);
const folderPath = FOLDER_MAP[resourceType];
// Skip resources matched by .vapi-ignore.
// These are explicit opt-outs — the resource exists on the dashboard but
// this repo does not manage it. Do NOT track in state (so a future
// un-ignore pulls cleanly and so state doesn't accumulate stale entries).
if (!bootstrap && !force) {
const matched = matchesIgnore(folderPath, resourceId);
if (matched) {
console.log(` 🚫 ${resourceId} (matched .vapi-ignore: ${matched})`);
skipped++;
continue;
}
}
// Skip files that have been locally modified (git detection)
if (!bootstrap && changedFiles) {
const mdPath = join(
"resources",
VAPI_ENV,
folderPath,
`${resourceId}.md`,
);
const ymlPath = join(
"resources",
VAPI_ENV,
folderPath,
`${resourceId}.yml`,
);
const yamlPath = join(
"resources",
VAPI_ENV,
folderPath,
`${resourceId}.yaml`,
);
if (
changedFiles.has(mdPath) ||
changedFiles.has(ymlPath) ||
changedFiles.has(yamlPath)
) {
console.log(` ✏️ ${resourceId} (locally modified, preserving)`);
upsertState(newStateSection, resourceId, { uuid: resource.id });
skipped++;
continue;
}
}
// Skip locally edited files even without git (mtime-based detection).
// If the resource file is newer than the state file, it was locally
// modified after the last successful pull. This is the safety net for the
// fresh-clone case: if git either isn't enabled at all OR has nothing
// useful to say about the resource tree (untracked, no changes, etc.),
// fall through here. The bug we are guarding against was treating an
// empty `changedFiles` Set as "git already gave us the answer" — it has
// not, and the mtime check must run.
if (
!bootstrap &&
!force &&
!isNew &&
(!changedFiles || changedFiles.size === 0)
) {
const dir = join(RESOURCES_DIR, folderPath);
const localFile = [
join(dir, `${resourceId}.md`),
join(dir, `${resourceId}.yml`),
join(dir, `${resourceId}.yaml`),
].find((p) => existsSync(p));
if (localFile) {
const stateFilePath = join(BASE_DIR, `.vapi-state.${VAPI_ENV}.json`);
if (existsSync(stateFilePath)) {
const localMtime = statSync(localFile).mtimeMs;
const stateMtime = statSync(stateFilePath).mtimeMs;
if (localMtime > stateMtime) {
console.log(` ✏️ ${resourceId} (locally modified, preserving)`);
upsertState(newStateSection, resourceId, { uuid: resource.id });
skipped++;
continue;
}
}
}
}
// Skip resources whose local file was deleted (works without git).
// A resource that was previously tracked in state but now has no local
// file is treated as an intentional deletion. To stop tracking it
// entirely (so it never re-appears on pull), add it to .vapi-ignore.
if (!bootstrap && !force && !isNew) {
const dir = join(RESOURCES_DIR, folderPath);
const fileExists =
existsSync(join(dir, `${resourceId}.md`)) ||
existsSync(join(dir, `${resourceId}.yml`)) ||
existsSync(join(dir, `${resourceId}.yaml`));
if (!fileExists) {
console.log(
` 🗑️ ${resourceId} (deleted locally, intent in state — add to .vapi-ignore to stop tracking)`,
);
upsertState(newStateSection, resourceId, { uuid: resource.id });
skipped++;
continue;
}
}
// Detect platform defaults (orgId is null/missing — read-only, immutable)
const isPlatformDefault =
resource.orgId === null || resource.orgId === undefined;
// Clean, resolve resource references, and replace credential UUIDs with names
const cleaned = cleanResource(resource);
const resolved = resolveReferencesToResourceIds(cleaned, state);
const withCredNames = replaceCredentialRefs(resolved, credReverse);
// Mark platform defaults so apply skips them
if (isPlatformDefault) {
withCredNames._platformDefault = true;
}
if (bootstrap) {
const icon = isPlatformDefault ? "🔒" : isNew ? "✨" : "📝";
console.log(
` ${icon} ${resourceId} -> state only${isPlatformDefault ? " (platform default, read-only)" : ""}`,
);
} else {
// Write to file
const filePath = await writeResourceFile(
resourceType,
resourceId,
withCredNames,
);
const icon = isPlatformDefault ? "🔒" : isNew ? "✨" : "📝";
const relPath = relative(BASE_DIR, filePath);
console.log(
` ${icon} ${resourceId} -> ${relPath}${isPlatformDefault ? " (platform default, read-only)" : ""}`,
);
}
if (isNew) created++;
else updated++;
// Update state with new content hash + timestamp.
// Hashing the resolved-with-credentials payload (the form we will save
// to disk) keeps `lastPulledHash` aligned with the source-of-truth diff
// basis used by drift detection.
upsertState(newStateSection, resourceId, {
uuid: resource.id,
lastPulledHash: hashPayload(withCredNames),
lastPulledAt: new Date().toISOString(),
});
}
// Update state with new mappings
state[resourceType] = newStateSection;
return { created, updated, skipped };
}
// ─────────────────────────────────────────────────────────────────────────────
// Main Pull Engine
// ─────────────────────────────────────────────────────────────────────────────
export async function runPull(options: PullOptions = {}): Promise<PullResult> {
const force = options.force ?? process.argv.includes("--force");
const bootstrap = options.bootstrap ?? BOOTSTRAP_SYNC;
const typeFilter = options.typeFilter ?? APPLY_FILTER.resourceTypes;
const resourceIds = options.resourceIds ?? APPLY_FILTER.resourceIds;
if (resourceIds?.length) {
if (!typeFilter?.length || typeFilter.length !== 1) {
throw new Error(
"Single-resource pull requires exactly one resource type. Example: npm run pull -- <org> --type squads --id <uuid>",
);
}
}
console.log(
"═══════════════════════════════════════════════════════════════",
);
console.log(
`🔄 Vapi GitOps Pull - Environment: ${VAPI_ENV}${force ? " (force)" : ""}${bootstrap ? " (bootstrap)" : ""}`,
);
console.log(` API: ${VAPI_BASE_URL}`);
if (typeFilter?.length) {
console.log(` Filter: ${typeFilter.join(", ")}`);
}
if (resourceIds?.length) {
console.log(` IDs: ${resourceIds.join(", ")}`);
}
if (bootstrap) {
console.log(
" Mode: state sync only (remote resources are not written locally)",
);
}
console.log(
"═══════════════════════════════════════════════════════════════",
);
// Default mode: skip locally changed files (local is source of truth)
// Force mode: overwrite everything (platform is source of truth)
let changedFiles: Set<string> | undefined;
const gitEnabled = !force && !bootstrap && isGitRepo() && gitHasCommits();
if (gitEnabled) {
changedFiles = getLocallyChangedFiles();
// Only keep resource files — non-resource changes don't matter
for (const f of changedFiles) {
if (!f.startsWith(`resources/${VAPI_ENV}/`)) changedFiles.delete(f);
}
if (changedFiles.size > 0) {
console.log(
`\n📦 ${changedFiles.size} locally modified file(s) will be preserved`,
);
console.log(
" Use --force to overwrite all local files with platform state",
);
}
}
const ignorePatterns = !bootstrap && !force ? loadIgnorePatterns() : [];
if (ignorePatterns.length > 0) {
console.log(
`\n🚫 ${ignorePatterns.length} pattern(s) loaded from .vapi-ignore — matching resources will be skipped`,
);
}
if (force) {
console.log(
"\n⚡ Force mode: overwriting all local files with platform state",
);
} else if (bootstrap) {
console.log(
"\n🧭 Bootstrap mode: refreshing state and credentials without materializing remote resources",
);
}
const state = loadState();
// Credentials are always pulled first — they're needed to reverse-resolve UUIDs in resource files
await pullCredentials(state);
const zero: PullStats = { created: 0, updated: 0, skipped: 0 };
const stats: Record<ResourceType, PullStats> = {
tools: { ...zero },
structuredOutputs: { ...zero },
assistants: { ...zero },
squads: { ...zero },
personalities: { ...zero },
scenarios: { ...zero },
simulations: { ...zero },
simulationSuites: { ...zero },
evals: { ...zero },
};
// Pull in reverse-resolution order: pull resources that are referenced by others first,
// so their state is populated when resolving references (UUID → resourceId) in dependent types.
// e.g. structuredOutputs reference assistants, so assistants must be pulled first.
const shouldPull = (type: ResourceType) =>
!typeFilter?.length || typeFilter.includes(type);
if (shouldPull("tools"))
stats.tools = await pullResourceType("tools", state, {
changedFiles,
force,
bootstrap,
resourceIds,
});
if (shouldPull("assistants"))
stats.assistants = await pullResourceType("assistants", state, {
changedFiles,
force,
bootstrap,
resourceIds,
});
if (shouldPull("structuredOutputs"))