Skip to content
Open
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
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,8 @@ VAPI_PRIVATE_API_KEY=your-vapi-private-key-here
# Set to the EU endpoint for EU-region orgs.
# VAPI_BASE_URL=https://api.vapi.ai
# VAPI_BASE_URL=https://api.eu.vapi.ai

# Optional max GitOps RPM: client-side ceiling, NOT a Vapi org rate limit.
# Overrides resources/<org>/.vapi-org.json maxGitopsRpm (default 100).
# Must be a positive integer; shell/CI takes precedence over this file.
# VAPI_MAX_GITOPS_RPM=100
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,13 +203,20 @@ More detail: [How the engine works](docs/guides/how-it-works.md).

## Commands

Vapi requests use a per-org [max GitOps RPM](docs/guides/configuration.md#max-gitops-rpm)
client ceiling (default 100), configured by `maxGitopsRpm` in the committed
`.vapi-org.json` or overridden by `VAPI_MAX_GITOPS_RPM`. This is not a Vapi org limit.
Reads and writes use the same limiter, without an extra write delay; retry
backoff still applies. The burst capacity is capped at 20 requests (20 at the
default 100 RPM), allowing up to 120 requests in a minute at the default.

| Command | What it does |
| --- | --- |
| `npm run setup` | Connect an org: create `.env.<org>` and `resources/<org>/` |
| `npm run validate -- <org>` | Check resource files offline before deploying |
| `npm run apply -- <org>` | Deploy: pull, merge, then push (the default) |
| `npm run pull -- <org>` | Sync platform changes down without overwriting local edits |
| `npm run push -- <org>` | Push without pulling first (prefer `apply`) |
| `npm run push -- <org>` | Push without pulling first (prefer `apply`); paced by max GitOps RPM |
| `npm run rollback -- <org>` | Restore a pre-deploy snapshot |
| `npm run cleanup -- <org>` | Find, and optionally delete, platform resources with no file |
| `npm run audit -- <org>` | Report drift between files, state and the platform |
Expand Down
8 changes: 8 additions & 0 deletions docs/guides/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@

The other commands are direct only.

Every command that contacts Vapi observes the per-org
[max GitOps RPM](configuration.md#max-gitops-rpm) client ceiling (default 100).
Set committed `maxGitopsRpm` or override with `VAPI_MAX_GITOPS_RPM`; this does
not change the Vapi org API rate limit. Setup validates the key and region
using the default client ceiling before asking for the org folder; subsequent
requests use that org’s configured ceiling. Reads and writes share this
limiter without an additional write delay; retry backoff still applies.

| Command | Usage | What it does |
| --- | --- | --- |
| `npm run setup` | `npm run setup [-- <org>]` | Connect an org: creates `.env.<org>` and `resources/<org>/`. |
Expand Down
39 changes: 38 additions & 1 deletion docs/guides/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ gitignored: never commit them.
| Variable | Required | Description |
| --- | --- | --- |
| `VAPI_PRIVATE_API_KEY` | ✅ | The org's private API key, from [Private API Keys](https://dashboard.vapi.ai/org/api-keys). The older name `VAPI_TOKEN` is also accepted. |
| `VAPI_MAX_GITOPS_RPM` | | Override the org’s GitOps client request ceiling, in requests per minute. Positive integer; defaults to `maxGitopsRpm`, then 100. |
| `VAPI_BASE_URL` | | API base URL. Defaults to `https://api.vapi.ai`; EU orgs use `https://api.eu.vapi.ai` (`npm run setup -- <org> --region eu` sets it). |
| `VAPI_CREDENTIAL_<NAME>`, `VAPI_PHONE_NUMBER_<NAME>` | | Generated by `setup` and `pull` inside a marked block: the org's credential and phone-number IDs, by name. Values you set outside the block are kept and take precedence. |

Expand Down Expand Up @@ -49,7 +50,7 @@ Set these in GitHub under **Settings → Secrets and variables → Actions**.
| --- | --- |
| `promotion.yml` | Promotion pipelines between orgs. Start from `promotion.example.yml`. |
| `vapi-checks.yml` | PR checks. Start from `vapi-checks.example.yml`. |
| `resources/<org>/.vapi-org.json` | The Vapi org ID the folder belongs to. Written by the first command that can see the key's org, then checked by every command before any request: a key for another org stops the command. If a folder genuinely moves to another org, delete the file in a reviewed commit. |
| `resources/<org>/.vapi-org.json` | The Vapi org ID and optional `maxGitopsRpm` client ceiling (default 100). Written by the first command that can see the key's org, then checked by every command before any request: a key for another org stops the command. If a folder genuinely moves to another org, delete the file in a reviewed commit. |
| `resources/<org>/.vapi-ignore` | Platform resources this repo shouldn't manage, as glob patterns. See `resources/.vapi-ignore.example` and [YAML conventions](../learnings/yaml-conventions.md). |

## Other environment variables
Expand All @@ -59,3 +60,39 @@ Set these in GitHub under **Settings → Secrets and variables → Actions**.
| `CI=true` | Suppresses interactive warnings, such as the one `pull --force` prints. Set automatically by most CI systems. |
| `VAPI_CALL_DEBUG=1` | Makes `npm run call` log message types it would otherwise ignore. |
| `VAPI_GITOPS_ROOT` | Overrides the repository root that `npm run promote` and `npm run check` read from. Mainly for tests. |

## max GitOps RPM

max GitOps RPM caps the requests this client sends for an org, including
reads, writes, probes and retries. It is a GitOps client limit, not a Vapi
org limit. Set it in the committed `resources/<org>/.vapi-org.json`:

```json
{ "orgId": "your-org-id", "maxGitopsRpm": 100 }
```

The default is 100 requests per minute, below Vapi's default org API limit
of 200 RPM. Leave headroom for other clients. Values must be positive
integers; an invalid winning setting stops the command and names its source.
A settings-only file is valid before pinning, which preserves existing fields.

Precedence is shell/CI `VAPI_MAX_GITOPS_RPM`, then `.env.<org>`,
`.env.<org>.local` and `.env.local` (first file wins), then committed
`maxGitopsRpm`, then 100. Quoted values, `export` prefixes and inline
comments work the same way in the env files for every command. Only the
winning value is validated; each org's limiter is configured once per process.

On a 429, the warning names the org and effective RPM, suggests lowering
`maxGitopsRpm` or setting `VAPI_MAX_GITOPS_RPM`, and links to the org API
rate limit: [EU](https://dashboard.eu.vapi.ai/settings/organization) for
`api.eu.vapi.ai`, otherwise
[US](https://dashboard.vapi.ai/settings/organization).
Reads and writes use this limiter equally, with no extra write delay.
Existing retry backoff still applies.

Each org shares one token bucket per process. It refills at
`maxGitopsRpm / 60` tokens per second, with a small burst capacity of
`max(1, min(20, floor(maxGitopsRpm / 5)))` (20 requests at the default).
The default allows up to 120 requests in a minute including the initial burst,
below the default 200 RPM org limit. Separate processes do not coordinate,
so their combined traffic can exceed the client ceiling.
14 changes: 14 additions & 0 deletions docs/guides/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,17 @@ have. Build `.ts` resources from files in the repository instead.

A folder under `resources/` that isn't a valid org name (lowercase letters,
digits and hyphens) fails too. Rename it, or move it out of `resources/`.

## 429: max GitOps RPM may be too high

GitOps warns once per org per process on a Vapi 429. Lower `maxGitopsRpm`
in `resources/<org>/.vapi-org.json`, or its `VAPI_MAX_GITOPS_RPM` override.
This is a GitOps client limit, not a Vapi org limit. Other clients and other
GitOps processes can also use the org's API quota.

The warning links to your org-level API rate limit at
https://dashboard.eu.vapi.ai/settings/organization when the org uses
`api.eu.vapi.ai`, otherwise https://dashboard.vapi.ai/settings/organization.
Existing retry/backoff remains in effect; the client ceiling does not
guarantee that the server will never rate-limit you. See
[configuration](configuration.md#max-gitops-rpm) for precedence and burst behavior.
10 changes: 10 additions & 0 deletions improvements.md
Original file line number Diff line number Diff line change
Expand Up @@ -2076,3 +2076,13 @@ dependency check, as `check-payload.ts` already does.
`AGENTS.md`. Don't conflate that with drift detection.
- **Renaming `npm run eval` to disambiguate from `npm run sim`.**
Backwards-incompatible script change; raise as a separate issue.

## 2026-11-17 — Per-org max GitOps RPM

- **Problem:** Independent request paths could burst without a shared client ceiling.
- **Current behavior:** [rate-limit.ts](src/rate-limit.ts) shares a token bucket per org; [vapi-fetch.ts](src/vapi-fetch.ts) routes every Vapi fetch through it, including retries.
- **Risk:** Multiple processes or other clients may still exhaust the platform quota.
- **Current mitigation:** Committed `maxGitopsRpm` (default 100), overridden by `VAPI_MAX_GITOPS_RPM`; invalid winning settings stop requests. A 429 warns with the org's region-specific dashboard link.
- **Possible fix:** Coordinate budgets across processes if deployments need a global client ceiling.
- **Status:** Implemented; existing retry backoff retained; reads and writes paced only by the shared limiter. This is a GitOps client limit, not a Vapi org limit.
- **Review hardening:** Invalid limits exit cleanly without a stack trace. The setup wizard keeps key/region validation first, using the default client ceiling until the folder is selected. Shared env parsing supports exports and comments without leaking one org’s override to another; 429 advice names the org and effective RPM.
31 changes: 10 additions & 21 deletions src/api.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import {
BASE_DIR,
DRY_RUN,
MAX_GITOPS_RPM,
VAPI_BASE_URL,
VAPI_ENV,
VAPI_TOKEN,
VAPI_TOKEN_SOURCE,
} from "./config.ts";
import { ORG_PIN_FILE, OrgPinMismatchError, orgPinCheck } from "./org-pin.ts";
import { orgLimiter } from "./rate-limit.ts";
import type { VapiResponse } from "./types.ts";
import { userAgentGet, vapiClientGet } from "./user-agent.ts";
import {
Expand All @@ -16,6 +18,7 @@ import {
shouldRetry,
VapiApiError,
} from "./vapi-client.ts";
import { limitedVapiFetch } from "./vapi-fetch.ts";

// ─────────────────────────────────────────────────────────────────────────────
// Dry-run accounting
Expand Down Expand Up @@ -45,6 +48,7 @@ export function orgPinGuard(): Promise<void> {
rootDir: BASE_DIR,
org: VAPI_ENV,
connection: {
limiter: orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM),
token: VAPI_TOKEN ?? "",
baseUrl: VAPI_BASE_URL,
userAgent: userAgentGet(),
Expand Down Expand Up @@ -103,26 +107,10 @@ function formatBodyPreview(body: Record<string, unknown>): string {
// existing importers and `instanceof` checks see one class.
export { VapiApiError };

// Minimum gap between writes, to stay under rate limits. Reads skip it: a pull
// is a handful of list requests, and a 700ms gap before each one was most of a
// pull's run time. A 429 on a read is still retried with backoff.
const REQUEST_DELAY_MS = 700;

let lastRequestTime = 0;

async function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}

async function throttle(): Promise<void> {
const now = Date.now();
const timeSinceLastRequest = now - lastRequestTime;
if (timeSinceLastRequest < REQUEST_DELAY_MS) {
await sleep(REQUEST_DELAY_MS - timeSinceLastRequest);
}
lastRequestTime = Date.now();
}

export async function vapiRequest<T = VapiResponse>(
method: "POST" | "PATCH",
endpoint: string,
Expand All @@ -146,8 +134,8 @@ export async function vapiRequest<T = VapiResponse>(
}

for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
await throttle();
const response = await fetch(url, {
const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM);
const response = await limitedVapiFetch(limiter, url, {
method,
headers: {
"Content-Type": "application/json",
Expand Down Expand Up @@ -193,7 +181,8 @@ export async function vapiGet<T = unknown>(endpoint: string): Promise<T> {
const url = `${VAPI_BASE_URL}${endpoint}`;

for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
const response = await fetch(url, {
const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM);
const response = await limitedVapiFetch(limiter, url, {
method: "GET",
headers: {
Authorization: `Bearer ${VAPI_TOKEN}`,
Expand Down Expand Up @@ -243,8 +232,8 @@ export async function vapiDelete(endpoint: string): Promise<void> {
}

for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
await throttle();
const response = await fetch(url, {
const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM);
const response = await limitedVapiFetch(limiter, url, {
method: "DELETE",
headers: {
Authorization: `Bearer ${VAPI_TOKEN}`,
Expand Down
5 changes: 4 additions & 1 deletion src/call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import { createRequire } from "module";
import { dirname, join, resolve } from "path";
import * as readline from "readline";
import { fileURLToPath } from "url";
import { orgLimiterOrExit } from "./rate-limit.ts";
import type { Environment, StateFile } from "./types.ts";
import { userAgentGet, vapiClientGet } from "./user-agent.ts";
import { limitedVapiFetch } from "./vapi-fetch.ts";

const require = createRequire(import.meta.url);

Expand Down Expand Up @@ -360,7 +362,8 @@ async function createCall(

console.log(`📞 Creating call...`);

const response = await fetch(url, {
const limiter = orgLimiterOrExit(BASE_DIR, config.env);
const response = await limitedVapiFetch(limiter, url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Expand Down
13 changes: 11 additions & 2 deletions src/check-cmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
} from "./check-status.ts";
import type { OrgConnection } from "./org-connection.ts";
import { childRun, connectionLoad, tokensParse } from "./org-connection.ts";
import { orgLimiterOrExit } from "./rate-limit.ts";
import { userAgentGet, vapiClientGet } from "./user-agent.ts";
import type { VapiConnection } from "./vapi-client.ts";

Expand Down Expand Up @@ -188,6 +189,7 @@ function connectionsLoad(
const envKey = process.env.VAPI_PRIVATE_API_KEY ?? process.env.VAPI_TOKEN;
const connections = new Map<string, OrgConnection>();
for (const runOrg of runOrgs) {
orgLimiterOrExit(root, runOrg);
const baseUrl = checks.find(
(check) => check.runOrg === runOrg && check.baseUrl,
)?.baseUrl;
Expand Down Expand Up @@ -277,6 +279,7 @@ function reportWrite(
}

async function liveRun(
root: string,
parsed: CheckArgs,
jobs: CheckJob[],
connections: Map<string, OrgConnection>,
Expand All @@ -293,7 +296,13 @@ async function liveRun(
const vapiClient = vapiClientGet("check");
const vapi = (job: CheckJob): VapiConnection => {
const connection = connections.get(job.check.runOrg)!;
return { token: connection.token, baseUrl: connection.baseUrl!, userAgent, vapiClient };
return {
limiter: orgLimiterOrExit(root, job.check.runOrg),
token: connection.token,
baseUrl: connection.baseUrl!,
userAgent,
vapiClient,
};
};
const post = async (status: CommitStatus) => {
if (statusEnv) await commitStatusPost(statusEnv, status);
Expand Down Expand Up @@ -391,7 +400,7 @@ async function checksRun(
mockNotices: [],
durationMs: 0,
}))
: await liveRun(parsed, jobs, connections, statusEnv);
: await liveRun(root, parsed, jobs, connections, statusEnv);
reportWrite(root, parsed, results, skipped);
return { code: exitCode(results), results };
}
Expand Down
2 changes: 2 additions & 0 deletions src/check-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ export function mockNoticesCollect(items: SimRunItem[]): string[] {
}

function errorReason(error: unknown): string {
if (error instanceof Error && error.name === "AbortError")
return "not started: interrupted";
if (error instanceof VapiApiError && error.statusCode === 402)
return `billing: the run org can't start simulations (402: ${error.apiMessage})`;
return error instanceof Error ? error.message : String(error);
Expand Down
20 changes: 10 additions & 10 deletions src/cleanup.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,36 @@
import { resolve } from "path";
import { fileURLToPath } from "url";
import {
BASE_DIR,
loadIgnorePatterns,
matchesIgnore,
MAX_GITOPS_RPM,
VAPI_BASE_URL,
VAPI_ENV,
VAPI_TOKEN,
} from "./config.ts";
import { orgPinGuard } from "./api.ts";
import { orgLimiter } from "./rate-limit.ts";
import { FOLDER_MAP } from "./resource-parse.ts";
import { slugify } from "./slug-utils.ts";
import { loadState } from "./state.ts";
import type { ResourceType } from "./types.ts";
import { userAgentGet, vapiClientGet } from "./user-agent.ts";
import { limitedVapiFetch } from "./vapi-fetch.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 orgPinGuard();
await sleep(REQUEST_DELAY_MS);
const response = await fetch(`${VAPI_BASE_URL}${endpoint}`, {
const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM);
const url = `${VAPI_BASE_URL}${endpoint}`;
const response = await limitedVapiFetch(limiter, url, {
headers: {
Authorization: `Bearer ${VAPI_TOKEN}`,
"User-Agent": userAgentGet(),
Expand Down Expand Up @@ -72,8 +71,9 @@ async function vapiGet<T>(endpoint: string, debug = false): Promise<T> {

async function vapiDelete(endpoint: string): Promise<void> {
await orgPinGuard();
await sleep(REQUEST_DELAY_MS);
const response = await fetch(`${VAPI_BASE_URL}${endpoint}`, {
const limiter = orgLimiter(BASE_DIR, VAPI_ENV, MAX_GITOPS_RPM);
const url = `${VAPI_BASE_URL}${endpoint}`;
const response = await limitedVapiFetch(limiter, url, {
method: "DELETE",
headers: {
Authorization: `Bearer ${VAPI_TOKEN}`,
Expand Down
Loading
Loading