-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathconfig.ts
More file actions
386 lines (334 loc) · 13.7 KB
/
Copy pathconfig.ts
File metadata and controls
386 lines (334 loc) · 13.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
import { existsSync, readFileSync } from "fs";
import { join, basename, dirname, resolve, relative } from "path";
import { fileURLToPath } from "url";
import type { Environment, ResourceType } from "./types.ts";
import { VALID_RESOURCE_TYPES } from "./types.ts";
// ─────────────────────────────────────────────────────────────────────────────
// CLI Argument Parsing
// ─────────────────────────────────────────────────────────────────────────────
export interface ApplyFilter {
resourceTypes?: ResourceType[]; // Filter by resource types
filePaths?: string[]; // Apply only specific files
resourceIds?: string[]; // Pull only specific remote resource IDs
}
// Group aliases: expand a shorthand into multiple resource types
const RESOURCE_GROUP_MAP: Record<string, ResourceType[]> = {
simulations: [
"personalities",
"scenarios",
"simulations",
"simulationSuites",
],
};
// Path-based aliases: folder paths to resource types
const RESOURCE_PATH_MAP: Record<string, ResourceType> = {
"simulations/personalities": "personalities",
"simulations/scenarios": "scenarios",
"simulations/tests": "simulations",
"simulations/suites": "simulationSuites",
};
const SLUG_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
function parseEnvironment(): Environment {
const envArg = process.argv[2];
if (!envArg) {
console.error("❌ Environment / org name argument is required");
console.error(" Usage: npm run push -- <org>");
console.error(" Flags: --force (enable deletions)");
console.error(
" --type <type> (apply only specific resource type, repeatable)",
);
console.error(" -- <file...> (apply only specific files)");
process.exit(1);
}
if (!SLUG_RE.test(envArg)) {
console.error(`❌ Invalid environment / org name: ${envArg}`);
console.error(
" Must be lowercase alphanumeric with optional hyphens (e.g., dev, my-org)",
);
process.exit(1);
}
return envArg;
}
// Resolve a type argument into resource types (handles groups, paths, and direct types)
function resolveResourceTypes(arg: string): ResourceType[] | null {
// Check group aliases first (e.g., "simulations" → all 4 simulation types)
if (RESOURCE_GROUP_MAP[arg]) {
return RESOURCE_GROUP_MAP[arg];
}
// Check path-based aliases (e.g., "simulations/personalities" → ["personalities"])
if (RESOURCE_PATH_MAP[arg]) {
return [RESOURCE_PATH_MAP[arg]];
}
// Check direct resource type
if (VALID_RESOURCE_TYPES.includes(arg as ResourceType)) {
return [arg as ResourceType];
}
return null;
}
const VALID_TYPE_ARGS = [
...VALID_RESOURCE_TYPES,
...Object.keys(RESOURCE_GROUP_MAP),
...Object.keys(RESOURCE_PATH_MAP),
];
function parseFlags(): {
forceDelete: boolean;
bootstrapSync: boolean;
dryRun: boolean;
applyFilter: ApplyFilter;
} {
const args = process.argv.slice(3);
const result: {
forceDelete: boolean;
bootstrapSync: boolean;
dryRun: boolean;
applyFilter: ApplyFilter;
} = {
forceDelete: args.includes("--force"),
bootstrapSync: args.includes("--bootstrap"),
dryRun: args.includes("--dry-run"),
applyFilter: {},
};
const resourceIds: string[] = [];
const filePaths: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (!arg) continue;
if (arg === "--force" || arg === "--bootstrap" || arg === "--dry-run")
continue;
// --confirm <slug>: consumed by cleanup.ts directly. Eat the value here so
// parseFlags' strict-arg check below doesn't trip on the slug.
if (arg === "--confirm" && args[i + 1]) {
i++;
continue;
}
if (arg.startsWith("--confirm=")) continue;
// --type / -t (repeatable): accumulate resource types
if ((arg === "--type" || arg === "-t") && args[i + 1]) {
const typeArg = args[i + 1]!;
const resolved = resolveResourceTypes(typeArg);
if (!resolved) {
console.error(`❌ Invalid resource type: ${typeArg}`);
console.error(` Must be one of: ${VALID_TYPE_ARGS.join(", ")}`);
process.exit(1);
}
if (!result.applyFilter.resourceTypes) {
result.applyFilter.resourceTypes = [];
}
result.applyFilter.resourceTypes.push(...resolved);
i++;
continue;
}
// --id (repeatable)
if (arg === "--id" && args[i + 1]) {
resourceIds.push(args[i + 1]!);
i++;
continue;
}
// Positional resource type / group
const resolved = resolveResourceTypes(arg);
if (resolved) {
if (!result.applyFilter.resourceTypes) {
result.applyFilter.resourceTypes = [];
}
result.applyFilter.resourceTypes.push(...resolved);
continue;
}
// File path
if (arg.includes("/") || /\.(yml|yaml|md|ts)$/.test(arg)) {
filePaths.push(arg);
continue;
}
// Unknown long flags pass through (forward-compatibility for future
// flags consumed by individual commands like cleanup/eval).
if (arg.startsWith("--")) continue;
// Bare positional that didn't match anything. Refuse explicitly so the
// user does not silently run a full apply when they meant a partial. The
// previous behavior was to silently drop the argument; for bare resource
// ids (e.g. `npm run push -- <org> foo`) this triggered a full apply
// with full orphan-deletion check, which can wipe state with `--force`.
console.error(`❌ Unrecognized argument: ${arg}`);
console.error(
` Expected a resource type (e.g. assistants, tools), a folder path ` +
`(e.g. assistants/foo.yml or resources/<org>/assistants/foo.yml), or ` +
`a flag (--force, --bootstrap, --type, --id).`,
);
process.exit(1);
}
if (filePaths.length > 0) {
result.applyFilter.filePaths = filePaths;
}
if (resourceIds.length > 0) {
result.applyFilter.resourceIds = resourceIds;
}
return result;
}
// ─────────────────────────────────────────────────────────────────────────────
// Environment File Loading
// ─────────────────────────────────────────────────────────────────────────────
function loadEnvFile(env: string, baseDir: string): void {
const envFiles = [
join(baseDir, `.env.${env}`), // e.g. .env.my-org
join(baseDir, `.env.${env}.local`), // e.g. .env.my-org.local (local overrides)
join(baseDir, ".env.local"), // .env.local (always loaded last)
];
for (const envFile of envFiles) {
if (existsSync(envFile)) {
const content = readFileSync(envFile, "utf-8");
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eqIndex = trimmed.indexOf("=");
if (eqIndex === -1) continue;
const key = trimmed.slice(0, eqIndex).trim();
let value = trimmed.slice(eqIndex + 1).trim();
// Remove quotes if present
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
// Only set if not already defined (env vars take precedence)
if (process.env[key] === undefined) {
process.env[key] = value;
}
}
console.log(`📁 Loaded env file: ${basename(envFile)}`);
}
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Configuration
// ─────────────────────────────────────────────────────────────────────────────
// Base directory for the gitops project
const __dirname = dirname(fileURLToPath(import.meta.url));
export const BASE_DIR = join(__dirname, "..");
// Parse environment, flags, and load env files
export const VAPI_ENV = parseEnvironment();
export const {
forceDelete: FORCE_DELETE,
bootstrapSync: BOOTSTRAP_SYNC,
dryRun: DRY_RUN,
applyFilter: APPLY_FILTER,
} = parseFlags();
loadEnvFile(VAPI_ENV, BASE_DIR);
// API configuration
export const VAPI_TOKEN = process.env.VAPI_TOKEN;
export const VAPI_BASE_URL = process.env.VAPI_BASE_URL || "https://api.vapi.ai";
if (!VAPI_TOKEN) {
console.error("❌ VAPI_TOKEN environment variable is required");
console.error(
` Create a .env.${VAPI_ENV} file with: VAPI_TOKEN=your-token`,
);
process.exit(1);
}
// Paths
export const RESOURCES_DIR = join(BASE_DIR, "resources", VAPI_ENV);
export const STATE_FILE_PATH = join(BASE_DIR, `.vapi-state.${VAPI_ENV}.json`);
// ─────────────────────────────────────────────────────────────────────────────
// Update Exclusions - Keys to remove when updating resources (PATCH)
// Add keys here that should not be sent during updates
// ─────────────────────────────────────────────────────────────────────────────
export const UPDATE_EXCLUDED_KEYS: Record<ResourceType, string[]> = {
tools: ["type"],
assistants: [],
structuredOutputs: ["type"],
squads: [],
personalities: [],
scenarios: [],
simulations: [],
simulationSuites: [],
evals: ["type"],
};
export function removeExcludedKeys(
payload: Record<string, unknown>,
resourceType: ResourceType,
): Record<string, unknown> {
const excludedKeys = UPDATE_EXCLUDED_KEYS[resourceType];
if (excludedKeys.length === 0) return payload;
const filtered = { ...payload };
for (const key of excludedKeys) {
delete filtered[key];
}
return filtered;
}
// ─────────────────────────────────────────────────────────────────────────────
// Ignore Patterns (.vapi-ignore)
//
// Resources matching any pattern in resources/<env>/.vapi-ignore are skipped
// during pull (never written, never tracked). This is the explicit opt-out
// mechanism for resources that exist on the dashboard but should not be
// managed by this repo.
//
// Pattern syntax (gitignore-flavored, simplified):
// - Matches against `<folderPath>/<resourceId>` (no extension)
// e.g. `assistants/ab-assistant-56b80091`
// - `*` matches any run of characters within a single path segment
// - `**` matches across path segments (zero or more)
// - Lines starting with `#` are comments
// - Blank lines are ignored
// - Leading `!` is reserved for future negation; treated as a comment today
// ─────────────────────────────────────────────────────────────────────────────
let cachedIgnorePatterns: string[] | null = null;
function getIgnoreFilePath(): string {
return join(BASE_DIR, "resources", VAPI_ENV, ".vapi-ignore");
}
export function loadIgnorePatterns(): string[] {
if (cachedIgnorePatterns !== null) return cachedIgnorePatterns;
const path = getIgnoreFilePath();
if (!existsSync(path)) {
cachedIgnorePatterns = [];
return cachedIgnorePatterns;
}
const raw = readFileSync(path, "utf-8");
cachedIgnorePatterns = raw
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0 && !line.startsWith("#") && !line.startsWith("!"));
return cachedIgnorePatterns;
}
// Convert a gitignore-flavored glob to a RegExp. We keep the implementation
// intentionally small (no node_modules) since pull.ts is the only consumer.
function compilePattern(pattern: string): RegExp {
// Escape regex metacharacters except the glob ones we handle explicitly.
// `*` and `?` are translated below; everything else is literal.
let regex = "";
for (let i = 0; i < pattern.length; i++) {
const c = pattern[i];
if (c === "*") {
// `**` → match any characters including path separators
// `*` → match any characters within a single segment (no `/`)
if (pattern[i + 1] === "*") {
regex += ".*";
i++; // consume the second `*`
} else {
regex += "[^/]*";
}
} else if (c === "?") {
regex += "[^/]";
} else if ("\\^$.|+(){}[]".includes(c as string)) {
regex += `\\${c}`;
} else {
regex += c;
}
}
return new RegExp(`^${regex}$`);
}
// Check whether a resource at `<folderPath>/<resourceId>` matches the ignore list.
// Returns the matched pattern (truthy) or null.
export function matchesIgnore(
folderPath: string,
resourceId: string,
patterns: string[] = loadIgnorePatterns(),
): string | null {
if (patterns.length === 0) return null;
const target = `${folderPath}/${resourceId}`;
for (const pattern of patterns) {
if (compilePattern(pattern).test(target)) return pattern;
}
return null;
}
// Test-only: clear the cache. Production code does not need to call this.
export function _resetIgnoreCache(): void {
cachedIgnorePatterns = null;
}