Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,12 @@ default-exports the object (safety rule 5).

The engine resolves IDs and credential names to each org's UUIDs on push.

Assistant subfolders are pushed as derived `metadata.folderPath` (for example
`assistants/support/intake.yml` → `support`). Other metadata keys are preserved.
Root assistants send `folderPath: null`, clearing stale grouping. Pull and drift
exclude this key; don't author it locally. File moves still require the normal
filename/state mapping safeguards below. Other resource types are unchanged.

### Naming and renaming

- **Files you create keep their names.** Resources pulled from the platform
Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,13 @@ To test every pull request automatically, set up [PR checks](docs/guides/pr-chec
- **Secrets stay out of git.** API keys live in `.env.<org>` (gitignored) or
CI secrets. Credentials are referenced by name and bound to each org's own
credentials.
- **Assistant subfolders group the dashboard.** Pushing
`assistants/support/tier2/intake.yml` sets `metadata.folderPath` to
`support/tier2`, preserving other authored metadata. Root assistants send
`folderPath: null` to clear any previous folder. This derived key is omitted
on pull and ignored for drift; do not author it in YAML. Moving files still
follows the normal filename/state mapping safeguards. `apply` uses the same
behavior in its push phase.
- **Each folder is pinned to its org.** The first command that can see which
org a key belongs to records it in `resources/<org>/.vapi-org.json`. After
that, every command checks the key against it before any request, and stops
Expand Down
6 changes: 6 additions & 0 deletions docs/guides/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ The other commands are direct only.

## Interactive Mode

Assistant pushes (including the push phase of `apply`) derive
`metadata.folderPath` from the file's subfolder under `assistants/`, preserving
other authored metadata. Root files send `folderPath: null` to clear grouping.
Pull omits this derived key, and drift comparisons ignore it. Moving a file
still follows the normal rename/state mapping safeguards.

When you run a command without arguments, you get a fully interactive experience:

```bash
Expand Down
35 changes: 35 additions & 0 deletions src/assistant-folder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export function withoutAssistantFolder(
data: Record<string, unknown>,
): Record<string, unknown> {
const metadata = data.metadata;
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
return data;
}
const { folderPath: _, ...rest } = metadata as Record<string, unknown>;
const result = { ...data };
if (Object.keys(rest).length > 0) result.metadata = rest;
else delete result.metadata;
return result;
}

export function withAssistantFolder(
data: Record<string, unknown>,
resourceId: string,
): Record<string, unknown> {
const normalized = resourceId.replace(/\\/g, "/");
const slash = normalized.lastIndexOf("/");
const metadata = data.metadata;
if (
metadata != null &&
(typeof metadata !== "object" || Array.isArray(metadata))
) {
throw new Error("Assistant metadata must be an object");
}
return {
...data,
metadata: {
...(metadata as Record<string, unknown> | undefined),
folderPath: slash < 0 ? null : normalized.slice(0, slash),
},
};
}
4 changes: 2 additions & 2 deletions src/audit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@

import { readFile } from "fs/promises";
import { join } from "path";
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
import { matchesIgnore, RESOURCES_DIR, VAPI_ENV } from "./config.ts";
import { credentialReverseMap } from "./credentials.ts";
import { classifyDrift } from "./drift.ts";
import { readBaseline } from "./hash-store.ts";
import { findOrphanResourceIds } from "./new-file-gate.ts";
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
import { fetchAllResources, listExistingResourceIds } from "./pull.ts";
import { FOLDER_MAP, hashLocalResource } from "./resources.ts";
import { extractBaseSlug, slugify } from "./slug-utils.ts";
Expand Down Expand Up @@ -393,7 +393,7 @@ function checkContentDrift(
// canonicalizeForHash centralizes the 3-step pipeline + _platformDefault
// mutation so the hash agrees with the pull-write baseline basis.
const platformHash = hashPayload(
canonicalizeForHash(remoteResource, state, credReverse),
canonicalizeForHash(remoteResource, state, credReverse, type),
);
const direction = classifyDrift({
localHash,
Expand Down
6 changes: 5 additions & 1 deletion src/canonical.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
// drift, so drift could not import back — it grew a divergent copy instead).
// ─────────────────────────────────────────────────────────────────────────────

import { withoutAssistantFolder } from "./assistant-folder.ts";
import { replaceCredentialRefs } from "./credentials.ts";
import type { ResourceType, StateFile } from "./types.ts";

Expand Down Expand Up @@ -210,9 +211,12 @@ export function canonicalizeForHash(
resource: VapiResource,
state: StateFile,
credReverse: Map<string, string>,
resourceType?: ResourceType,
): Record<string, unknown> {
const cleaned = cleanResource(resource);
const resolved = resolveReferencesToResourceIds(cleaned, state);
const content =
resourceType === "assistants" ? withoutAssistantFolder(cleaned) : cleaned;
const resolved = resolveReferencesToResourceIds(content, state);
const withCredNames = replaceCredentialRefs(resolved, credReverse);
const isPlatformDefault =
resource.orgId === null || resource.orgId === undefined;
Expand Down
12 changes: 8 additions & 4 deletions src/drift.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
// has nothing to compare against — only PATCH (update) is drift-sensitive.
// ─────────────────────────────────────────────────────────────────────────────

import { vapiGet, VapiApiError } from "./api.ts";
import { VapiApiError, vapiGet } from "./api.ts";
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
import { credentialReverseMap } from "./credentials.ts";
import { readBaseline } from "./hash-store.ts";
Expand Down Expand Up @@ -144,7 +144,12 @@ export async function checkDriftForUpdate(options: {
// resource hashed differently here than at pull time → phantom both-diverged.
const credReverse = credentialReverseMap(state);
const platformHash = hashPayload(
canonicalizeForHash(remote as VapiResource, state, credReverse),
canonicalizeForHash(
remote as VapiResource,
state,
credReverse,
resourceType,
),
);
if (platformHash === baseline) {
return { ok: true, reason: "match", platformHash, platformPayload: remote };
Expand All @@ -153,8 +158,7 @@ export async function checkDriftForUpdate(options: {
// On-disk hash in the same basis as the baseline. Absent a local file
// (rare on an update path), fall back to the baseline so the direction is
// dashboard-ahead rather than a phantom both-diverged.
const localHash =
hashLocalResource(resourceType, resourceId) ?? baseline;
const localHash = hashLocalResource(resourceType, resourceId) ?? baseline;

// Local and platform are byte-identical → there is nothing to reconcile and
// the PATCH is a no-op. NEVER block here, even if the baseline disagrees
Expand Down
14 changes: 11 additions & 3 deletions src/pull.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,8 @@ async function fetchPagedList<T extends Listable>(

// A short first page proves we saw everything in one request — the common case
// pays nothing for paging.
if (first.length < LIST_PAGE_SIZE) return { resources: first, complete: true };
if (first.length < LIST_PAGE_SIZE)
return { resources: first, complete: true };

// A full page means the response was capped. Walk backwards through
// `createdAt`, the only cursor these endpoints offer.
Expand Down Expand Up @@ -582,6 +583,7 @@ export async function writeDashboardBackup(
platformPayload,
state,
credReverse,
resourceType,
);
// Filesystem-safe ISO timestamp: 2026-06-04T19-22-33 (no colons, no ms).
const timestamp = new Date()
Expand Down Expand Up @@ -905,7 +907,7 @@ export async function pullResourceType(
// classifier, audit, and resolveBothDiverged sites. Any asymmetry here
// makes every drifted file look `both-diverged` even when content matches.
const platformHash = hashPayload(
canonicalizeForHash(resource, state, credReverse),
canonicalizeForHash(resource, state, credReverse, resourceType),
);
// Note: classifyDrift treats live local + platform agreement as
// `clean` whatever the (possibly stale) baseline says — the clean
Expand Down Expand Up @@ -1064,7 +1066,12 @@ export async function pullResourceType(
// Single canonicalization for both the file write AND the lastPulledHash
// fallback. Encodes the 3-step pipeline (cleanResource → resolve refs →
// replace credential UUIDs) plus the _platformDefault marker.
const withCredNames = canonicalizeForHash(resource, state, credReverse);
const withCredNames = canonicalizeForHash(
resource,
state,
credReverse,
resourceType,
);

if (bootstrap) {
const icon = isPlatformDefault ? "🔒" : isNew ? "✨" : "📝";
Expand Down Expand Up @@ -1218,6 +1225,7 @@ async function resolveBothDivergedResources(options: {
entry.resource,
state,
credReverse,
entry.resourceType,
);

await writeResourceFile(
Expand Down
28 changes: 24 additions & 4 deletions src/push.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { select } from "@inquirer/prompts";
import { relative, resolve } from "path";
import { fileURLToPath } from "url";
import { getDryRunCounts, VapiApiError, vapiRequest } from "./api.ts";
import { withAssistantFolder } from "./assistant-folder.ts";
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
import {
ALLOW_NEW_FILES,
Expand Down Expand Up @@ -156,13 +157,19 @@ async function writeBaselineFromResponse(
uuid: string,
response: unknown,
state: StateFile,
resourceType?: ResourceType,
): Promise<void> {
if (DRY_RUN) return;
if (!response || typeof response !== "object") return;
try {
const credReverse = credentialReverseMap(state);
const hash = hashPayload(
canonicalizeForHash(response as VapiResource, state, credReverse),
canonicalizeForHash(
response as VapiResource,
state,
credReverse,
resourceType,
),
);
await writeBaseline(VAPI_ENV, uuid, hash);
} catch (err) {
Expand Down Expand Up @@ -243,7 +250,12 @@ async function upsertResourceWithStateRecovery(options: {
if (!existingUuid) {
console.log(` ✨ Creating ${resourceLabel}: ${resourceId}`);
const result = await vapiRequest("POST", createEndpoint, createPayload);
await writeBaselineFromResponse(result.id, result, fullState);
await writeBaselineFromResponse(
result.id,
result,
fullState,
RESOURCE_LABEL_TO_TYPE[resourceLabel],
);
if (resourceLabel === "assistant") {
await writeAssistantVersionMetadata({
uuid: result.id,
Expand Down Expand Up @@ -397,7 +409,12 @@ async function upsertResourceWithStateRecovery(options: {
// The PATCH response is the full resource as the platform now stores it —
// the freshest possible "last known platform state." Hash it as the new
// drift baseline so the next push of a further local edit is clean.
await writeBaselineFromResponse(existingUuid, result, fullState);
await writeBaselineFromResponse(
existingUuid,
result,
fullState,
RESOURCE_LABEL_TO_TYPE[resourceLabel],
);
if (resourceLabel === "assistant" && platformPayloadForSnapshot) {
await writeAssistantVersionMetadata({
uuid: existingUuid,
Expand Down Expand Up @@ -874,7 +891,10 @@ export async function applyAssistant(
const existingUuid = state.assistants[resourceId]?.uuid;

// Resolve tool and structured output references
const payload = resolveReferences(data as Record<string, unknown>, state);
const payload = withAssistantFolder(
resolveReferences(data as Record<string, unknown>, state),
resourceId,
);

return upsertResourceWithStateRecovery({
resourceLabel: "assistant",
Expand Down
8 changes: 6 additions & 2 deletions src/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { existsSync } from "fs";
import { readFile } from "fs/promises";
import { basename, extname, join, relative, resolve } from "path";
import { parse as parseYaml } from "yaml";
import { withoutAssistantFolder } from "./assistant-folder.ts";
import { BASE_DIR, matchesIgnore, RESOURCES_DIR } from "./config.ts";
import {
FOLDER_MAP,
Expand All @@ -16,10 +17,10 @@ import { stateUuid } from "./state.ts";
import { hashPayload } from "./state-serialize.ts";
import type { ResourceFile, ResourceType, StateFile } from "./types.ts";

export type { LoadOptions };
// The file-reading half lives in resource-parse.ts (config-free). These are
// re-exported so existing importers keep working.
export { FOLDER_MAP, VALID_EXTENSIONS };
export type { LoadOptions };

function findLocalResourceFile(
type: ResourceType,
Expand All @@ -42,7 +43,10 @@ export function hashLocalResource(
const filePath = findLocalResourceFile(type, resourceId);
if (!filePath) return null;
try {
return hashPayload(parseResourceDataFromFile(filePath));
const data = parseResourceDataFromFile(filePath);
return hashPayload(
type === "assistants" ? withoutAssistantFolder(data) : data,
);
} catch {
return null;
}
Expand Down
Loading
Loading