Generated banner for Vercel Optimize
Generated logo for Vercel Optimize

Vercel Optimize

VercelOfficialPublished by Vercel

  • Skill
  • Workflow
  • Cloud and DevOps
  • MIT
  • Low risk
  • Has scripts

From the author

Use for Vercel cost and performance optimization on deployed projects, especially Next.js, SvelteKit, Nuxt, and limited Astro apps. Collect Vercel metrics, usage, project config, and code scan results first; investigate only metric-backed candidates; produce ranked recommendations grounded in verified files and version-aware Vercel/framework docs. Trigger for Vercel bill reduction, slow or expensive routes, caching opportunities, Function Invocations, Build Minutes, Fast Data Transfer, Core Web Vitals, Bot Management, Fluid compute, or cost breakdown requests.
— the description by Vercel

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

Vercel Optimize is a structured workflow designed to perform data-driven audits of Vercel-deployed projects. It prioritizes production metrics over static code analysis, ensuring that recommendations are grounded in real-world performance data. The tool integrates with the Vercel CLI to collect usage, metrics, and configuration data, which it then correlates with codebase scans to identify specific optimization candidates. It supports Next.js, SvelteKit, and Nuxt, with limited support for Astro, and enforces a strict, deterministic investigation process to ensure recommendations are accurate, version-aware, and actionable.

What it does

  • Collects and merges Vercel production metrics with local codebase scans.
  • Uses deterministic gates to identify high-impact performance and cost candidates.
  • Performs deep-dive investigations into specific routes, files, or project settings.
  • Verifies recommendations against framework-specific documentation and version constraints.
  • Generates a ranked report of actionable optimizations.
  • Provides a structured, repeatable pipeline for continuous performance improvement.

When to use it

  • When you need to reduce Vercel bill costs related to function invocations or build minutes.
  • When investigating slow or expensive routes in your application.
  • When optimizing for Core Web Vitals or improving cache hit rates.
  • When you need a data-backed audit of project configurations and deployment settings.

Advantages

  • Reduces noise by focusing only on metric-backed candidates.
  • Ensures recommendations are relevant to your specific framework version.
  • Prevents speculative optimizations by requiring evidence from production signals.
  • Provides a clear, step-by-step audit trail for every recommendation.

Usage examples

“Run a Vercel optimization audit on this project.”
The agent will initiate the collection of metrics and usage data, scan the codebase, and generate a report of ranked optimization candidates based on your project's actual traffic.
“Why is my Vercel bill so high for function invocations?”
The agent will analyze your function invocation metrics and identify specific routes or patterns that are driving costs, providing recommendations to optimize those areas.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/vercel-labs/vercel-optimize/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip vercel-optimize.zip -d .agents/skills

Documentation by Vercel

Vercel Optimize

Run an observability-first Vercel optimization audit. Do not inspect source files until signals.json exists and a deterministic gate points to a route, file, or project setting.

Core doctrine: read references/doctrine.md if any rule is unclear.

  • Metrics first. Recommendations start from Vercel production signals, not repo-wide grep.

  • Deterministic gates. scripts/gate-investigations.mjs decides what deserves investigation.

  • Candidate-bound scope. Read only files named by a candidate or a route-local import chain.

  • Version-aware citations. Use only references/docs-library.json; invalid or version-mismatched citations are stripped.

  • Customer copy. Read references/voice.md before writing report text or chat output.

Prerequisites

  • Vercel CLI v53+ with vercel metrics, vercel usage, vercel contract, and vercel api.

  • Authenticated CLI session: vercel login.

  • Linked app directory: vercel link. VERCEL_PROJECT_ID can help resolve project config, but vercel metrics still requires directory linkage. The link or environment must include the intended project org/team/user scope so the collector can resolve a CLI-safe --scope and keep vercel metrics, vercel usage, and vercel contract on the same account.

  • Node.js 20+.

  • Observability Plus for route-level metric-backed recommendations.

Never put auth tokens in shell commands. Do not type VERCEL_TOKEN=..., --token ..., or Authorization: Bearer ... into commands that may be echoed in chat.

Framework Support

The preflight reads package.json and sets expectations before metric fan-out.

FrameworkStatusNotes
Next.js App Routersupportedstrongest route mapping, scanners, playbooks, citations
Next.js Pages Routersupportedscoped to Pages Router idioms when detected
SvelteKitsupportedroute mapping for src/routes files and SvelteKit scanner
Nuxtsupportedroute mapping plus generic/platform checks; fewer framework-specific recs
Astrolimitedroute mapping plus generic checks; fewer framework-specific recs
Hono / Remix / unknownblocked by defaultcontinue only if the user accepts a limited platform/code-only audit

If unsupported, stop and ask before scanning or gating:

This project uses <framework>. Vercel Optimize supports metric-backed code recommendations for Next.js, SvelteKit, and Nuxt. Astro support is limited. For <framework>, I can still run a limited platform/scanner audit, but route-level Vercel metrics may not map back to source files.

Do you want me to continue with the limited audit, or stop here?

If the user continues, rerun collection with --continue-unsupported-framework.

Run Directory

Use a fresh run directory for every audit. Do not reuse briefs, sub-agent outputs, or reports across runs.

RUN_DIR="$(mktemp -d -t vercel-optimize-XXXXXX)"

Pipeline

1. Collect, scan, and merge signals

Run from the linked app directory or pass --cwd where a script supports it. Keep stdout JSON separate from stderr logs. Do not combine streams.

node scripts/collect-signals.mjs [projectId] > "$RUN_DIR/vercel-signals.json" 2> "$RUN_DIR/collect.stderr"
node -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' "$RUN_DIR/vercel-signals.json"

node scripts/scan-codebase.mjs <repo-root> > "$RUN_DIR/codebase.json"
node scripts/merge-signals.mjs "$RUN_DIR/vercel-signals.json" "$RUN_DIR/codebase.json" --out "$RUN_DIR/signals.json"

Collection details, schemas, metric IDs, and degradation behavior live in references/data-collection.md. The metric registry is lib/queries.mjs; keep all queries on the shared 14-day window.

collect-signals.mjs resolves the linked project owner to commandScope.cliScope and verifies that the resolved account can read the resolved project before it checks Observability Plus. Downstream scripts reuse that scope for every Vercel CLI command that accepts --scope. Do not run vercel usage, vercel metrics, or vercel contract manually without the same scope; unscoped usage can report the user's personal organization while route metrics come from the team project.

If project or scope resolution is ambiguous, stop and ask the user which Vercel project and team/personal scope they want audited. Do not infer the intended scope from the current vercel whoami team, and do not proceed with metrics, usage, or contract collection until the link, an exact project match in .vercel/repo.json, or VERCEL_PROJECT_ID + VERCEL_ORG_ID identifies the intended account.

Use this prompt for PROJECT_SCOPE_UNRESOLVED, SCOPE_UNRESOLVED, or PROJECT_SCOPE_MISMATCH:

I can't safely identify the Vercel project and account for this audit yet.

Please confirm the Vercel project name or ID and the team slug/name, or tell me it's under your personal account. Once confirmed, I'll relink or rerun collection against that exact scope before checking metrics.
1.1 Stop on blockers

Check blockers before gating:

jq '{frameworkSupportBlocker, observabilityPlus, observabilityPlusUsable, observabilityPlusBlocker, observabilityPlusBlockerDetail}' "$RUN_DIR/signals.json"

Required actions:

  • frameworkSupportBlocker === "unsupported_framework": use the unsupported-framework prompt above.

  • PROJECT_SCOPE_UNRESOLVED, SCOPE_UNRESOLVED, or PROJECT_SCOPE_MISMATCH: stop and ask which Vercel project and team/personal scope the user wants audited. For team projects, rerun after vercel link --yes --project <project-name-or-id> --team <team-slug>; for personal projects, rerun after linking under the intended user account or after setting both VERCEL_PROJECT_ID and VERCEL_ORG_ID.

  • observabilityPlusBlocker === null: continue.

  • no_traffic: tell the user route metrics are sparse; continue only if they accept limited output.

  • payment_required or no_oplus_probe: render references/observability-plus.md verbatim and ask.

  • project_disabled: tell the user to enable Observability Plus for the project or accept a limited audit.

  • daily_quota_exceeded: stop and tell the user the Observability query quota is exhausted; retry after the next UTC midnight reset, or ask whether to continue with a limited code-only audit.

  • not_linked: link the app directory, then rerun Step 1. If app path and project are known:

vercel link --yes --project <project-name-or-id> --cwd <app-dir>
# add --team <team-id-or-slug> when known
  • forbidden or project_not_found: fix auth/team scope. Do not pitch Observability Plus.

  • all_failed_other: show the raw error code and ask whether to continue in limited code-only mode.

Do not silently fall back to code-only mode. If the user accepts a limited audit, rerun collection with:

node scripts/collect-signals.mjs [projectId] --continue-without-observability > "$RUN_DIR/vercel-signals.json" 2> "$RUN_DIR/collect.stderr"

Then scan and merge again.

2. Gate candidates
node scripts/gate-investigations.mjs "$RUN_DIR/signals.json" > "$RUN_DIR/gate.json"

Output shape:

  • toLaunch: code-scope candidates to investigate.

  • platform: project/account-scope recommendations.

  • gated: skipped, covered, or disqualified candidates that must still appear in the report.

  • budget: candidate budget and selection mode.

Default budget is 6 code-scope candidates with a diversity guardrail. To expand:

node scripts/gate-investigations.mjs "$RUN_DIR/signals.json" --max-candidates 12 > "$RUN_DIR/gate.json"
node scripts/gate-investigations.mjs "$RUN_DIR/signals.json" --max-candidates all > "$RUN_DIR/gate.json"

Generated candidate docs: references/candidates.md.

2.1 Ask about audit scope when needed

Before deep-dive, run:

node scripts/budget-summary.mjs "$RUN_DIR/gate.json" --format json > "$RUN_DIR/budget-summary.json"

If shouldAsk is false, continue.

If shouldAsk is true:

  1. Print exactChatMessage.body exactly as returned. Do not summarize, truncate, reorder, or rewrite it.

  2. Then ask questionText using questionPayload when the host supports structured questions.

  3. If the user chooses a different number, rerun the gate with --max-candidates <choice>.

Never put the long preview inside the question field. The preview and the question are separate surfaces.

2.2 Deep-dive and reconcile
node scripts/deep-dive.mjs "$RUN_DIR/signals.json" "$RUN_DIR/gate.json" --cwd <project-dir> > "$RUN_DIR/investigation-evidence.json"

node scripts/reconcile-candidates.mjs "$RUN_DIR/investigation-evidence.json" \
  --gate "$RUN_DIR/gate.json" \
  --out "$RUN_DIR/reconciled-investigation.json"

--cwd must be the linked project directory so deep-dive.mjs can verify the same project link and reuse signals.json.commandScope.cliScope for any follow-up vercel metrics calls.

Reconciliation deterministically converts disproven candidates into observations before any source investigation:

  • metric_mismatch

  • error_storm

  • deployment_regression

  • scanner_only_no_metric

2.3 Generate briefs and investigate

List the work:

node scripts/prepare-investigation-brief.mjs "$RUN_DIR/signals.json" "$RUN_DIR/reconciled-investigation.json" --list > "$RUN_DIR/briefs-manifest.json"

Generate one brief for every entry in briefs-manifest.json.briefs. The group can be toLaunch or platform; do not generate only toLaunch briefs.

mkdir -p "$RUN_DIR/briefs" "$RUN_DIR/sub-agent-outputs"
node scripts/prepare-investigation-brief.mjs "$RUN_DIR/signals.json" "$RUN_DIR/reconciled-investigation.json" \
  --group <brief.group> --index <brief.index> --out "$RUN_DIR/briefs/<brief.group>-<brief.index>.md"

Use briefs-manifest.json.briefs[].label for visible worker names, for example Low cache-hit route on /docs/llm-digest/[...slug], not toLaunch-7.

Fan-out rule:

  • 1-2 briefs: investigate inline.

  • 3+ briefs: spawn one sub-agent per brief when the host supports it.

  • Hosts without sub-agents: run inline serially.

Sub-agent contract:

  • The brief is the whole prompt.

  • Read only files listed in the brief, plus route-local imports when needed.

  • Emit one JSON recommendation or one JSON no-change finding using references/recommendations.md.

  • Do not cite URLs outside the provided citation subset.

  • Do not recommend framework features unavailable in the detected version.

If a sub-agent reaches for repo-wide grep, the candidate is malformed; drop or abstain rather than widening scope.

2.4 Collect outputs

Save each raw investigation result in $RUN_DIR/sub-agent-outputs/, then collect:

node scripts/collect-sub-agent-outputs.mjs \
  --manifest "$RUN_DIR/briefs-manifest.json" \
  --out "$RUN_DIR/recommendations.json" \
  "$RUN_DIR/sub-agent-outputs/"

The collector extracts JSON, prepends pre-resolved records, enforces manifest order, and fails on missing, duplicate, unknown, or mismatched candidateRef values.

3. Verify recommendations
node scripts/verify-and-regen.mjs "$RUN_DIR/recommendations.json" \
  --signals "$RUN_DIR/signals.json" \
  --repo-root <project-dir> \
  --out "$RUN_DIR/verify.json"

This script extracts claims, verifies files/citations/version fit, grades quality, applies sanitizers, emits verifiedRecommendations, withheldRecommendations, renderableRecommendations, and creates regenPlan for failed or unsafe recommendations.

Recommendation schema, writing rules, sanitizer order, and grading rules: references/recommendations.md. Verification rules: references/verification.md.

For each regenPlan entry, rerun the same brief with a Previous attempt failed these checks section listing topFailures. Keep the regenerated output only if verification improves without gutting citations.

4. Render report and final message
node scripts/render-report.mjs "$RUN_DIR/verify.json" "$RUN_DIR/gate.json" "$RUN_DIR/signals.json" \
  --project <name> \
  --out "$RUN_DIR/report.md" \
  --message-out "$RUN_DIR/final-message.json"

Use --debug-out "$RUN_DIR/debug.json" only when developing the skill. Customer Markdown and chat output must not expose passRate, quality, sanitizer trails, raw sub-agent names, or other implementation fields.

After rendering, print final-message.json.body verbatim and stop. Do not add highlights, debug notes, raw counts, sub-agent summaries, or extra explanation. Render-time dedupe, platform caps, and hard-safety drops can change the customer-visible count, so never summarize from raw verify.json.

Report structure and impact framing: references/scoring.md.

Recommendation Rules

Every recommendation must:

  • Trace to a launched candidate, platform candidate, pre-resolved observation, or verified traffic-independent scanner finding.

  • Include observed metric evidence from signals.json or evidence.deepDive.

  • Cite verified files with line numbers when code is involved.

  • Include at least one allowed citation that applies to the detected framework/version.

  • Use precise observed performance numbers.

  • Use cost magnitude phrases only; never customer-facing $N savings.

  • Do not recommend duration reductions for Vercel Workflow runtime endpoints (/.well-known/workflow/v1/*). These are generated orchestration routes for durable step/flow execution and should be hard-gated before investigation.

  • Workflow recommendations must name the boundary being changed. Valid examples: enqueue durable work and return a run ID instead of awaiting completion, fix stream replay/closure/locks, or reduce verified excess Workflow Steps/Storage. Do not infer cost savings from Workflow endpoint wall-clock duration.

  • For streaming, SSE, resumable chat, or other intentionally long-lived routes, do not frame wall-clock function duration as a problem by itself. Require evidence of avoidable pre-first-byte work, high active CPU, duplicate invocations, or post-response work that can move out of the user-visible path.

  • Name a specific cache policy when recommending caching.

  • Keep unsafe responses dynamic unless evidence proves they are safe to cache: auth-sensitive paths, errors, fallback responses, missing content, invalid requests, geolocation/device-varying output, and unversioned dynamic URLs.

Never recommend "verify X is on" for facts already present in signals.project, including Fluid compute status, memory tier, regions, in-function concurrency, and timeout.

Scanner Rules

Scanner findings are supplementary. Drop findings annotated COLD-PATH or NO-ROUTE-MAPPING unless the scanner declares metadata.trafficIndependent === true.

Traffic-independent examples: middleware matcher, source maps, React Compiler config, build settings. Route-local cache or data-fetch patterns need route-level traffic evidence.

Scanner docs: references/scanner-patterns.md.

Final Customer Terms

Use:

  • recommendations ready

  • observations from investigation

  • investigated, no change recommended

  • not investigated in this run

Avoid:

  • sub-agent

  • abstention

  • passRate

  • quality score

  • gate

  • LLM

Failure Copy

Use these messages without adding sales copy or process detail.

No traffic in the last 14 days:

This project has no meaningful traffic in the last 14 days, so route-level metrics are sparse. I can still check traffic-independent scanner findings and project settings, but I cannot rank route fixes until traffic accumulates.

Route-level metrics unavailable:

Use the verbatim choice template in references/observability-plus.md. Do not silently fall back to code-only mode; present the two-path choice: enable Observability Plus and rerun the metric-backed audit, or accept a limited code-only run.

Project is not linked:

This worktree is not linked to a Vercel project. Run vercel link --yes --project <project-name-or-id> --cwd <app-dir> and rerun the audit. If the team is known, add --team <team-id-or-slug>.

Most route-to-file mappings failed:

The route inventory matched fewer than half of the routes we saw in observability. This is common in monorepos with custom routing. I've surfaced what I can match; the rest appear in the "Not investigated in this run" section.

Files

references/data-collection.md

Data collection

What the skill collects in Step 1, where each signal comes from, and how it degrades when a capability is missing.

All shapes here are covered by sanitized CLI fixtures in packages/vercel-optimize-tests/test/fixtures/real-cli-output/.

Table of contents

  • The signals.json shape

  • Per-signal source matrix

  • Error states and fallbacks

  • Real JSON shapes

  • Why we avoid stderr grep

The signals.json shape

node scripts/collect-signals.mjs emits the Vercel-side signal document. node scripts/scan-codebase.mjs <repo-root> emits the local codebase scan. node scripts/merge-signals.mjs vercel-signals.json codebase.json --out signals.json combines them into the artifact consumed by the gate, deep-dive, verifier, and renderer. The merge step also annotates scanner findings with route-level observability, COLD-PATH, or NO-ROUTE-MAPPING; scanner gates reject non-traffic-independent findings that do not carry one of those deterministic annotations.

The merged signals.json has this top-level shape:

{
  "schemaVersion": "1.2",
  "collectedAt": "2026-05-12T20:48:44.123Z",
  "timeWindow": "14d",
  "projectId": "prj_xxx",
  "orgId": "team_xxx",
  "projectIdSource": "repo.json" | "project.json" | "arg" | "env" | "arg+repo.json" | "arg+project.json" | "env+repo.json" | "env+project.json",
  "commandScope": {
    "ok": true,
    "cliScope": "team-slug-or-username",
    "source": "team-api" | "whoami-current-team" | "whoami-user" | "linked-org-scope" | "missing-org-scope",
    "required": true,
    "detail": "..."
  },
  "frameworkSupport": {
    "ok": true,
    "status": "supported" | "limited" | "unsupported",
    "blocker": null | "unsupported_framework",
    "framework": "next",
    "label": "Next.js",
    "detail": "..."
  },
  "frameworkSupportBlocker": null | "unsupported_framework",
  "frameworkSupportDetail": "...",
  "observabilityPlus": true | false | null,
  "observabilityPlusPreflight": { /* CLI/API configuration probe result */ },
  "observabilityPlusUsable": true | false | null,
  "observabilityPlusBlocker": null | "no_oplus_probe" | "project_disabled" | "payment_required" | "forbidden" | "daily_quota_exceeded" | "project_not_found" | "not_linked" | "all_failed_other" | "no_traffic",
  "observabilityPlusBlockerDetail": "...",
  "plan": { "plan": "hobby" | "pro" | "enterprise" | "uncertain", "reason": "..." },
  "project": { /* /v9/projects/:id response; team-owned projects include ?teamId */ },
  "contract": { "context": "...", "commitments": [], "totalCommitments": 0 },
  "usage": { /* vercel usage --format json --breakdown daily, or null */ },
  "usageError": null | "USAGE_UNAVAILABLE" | "USAGE_CONTEXT_MISMATCH" | "NOT_COLLECTED_OBSERVABILITY_BLOCKED" | "NOT_COLLECTED_UNSUPPORTED_FRAMEWORK" | "EXIT_<n>" | "UNKNOWN",
  "stack": { /* framework + version + router + ORM + monorepo */ },
  "codebase": { /* scan-codebase output: stack + routes + findings */ },
  "metrics": { /* per-metric query results (only when observabilityPlus=true) */ },
  "metricsSchema": [ /* array of {id, description} */ ]
}

All metric queries use the same timeWindow constant (14d) — defined as TIME_WINDOW in lib/queries.mjs and covered by the repo test suite. Mixing windows silently produces incompatible rollups; never pin a per-query since.

All Vercel CLI commands that accept scope must use commandScope.cliScope (--scope <team-slug-or-username>). Linked project files often contain raw team_... or usr_... IDs, but several CLI subcommands silently fall back to the current team when --scope receives a raw account ID. collect-signals.mjs resolves raw team IDs to slugs and raw user IDs to usernames before running vercel metrics, vercel usage, or vercel contract; deep-dive.mjs reuses the same scope for follow-up metric queries. If the project link lacks an owner account or the CLI-safe scope cannot be resolved, stop and ask the user which Vercel project and team/personal scope they want audited. Do not infer scope from the current vercel whoami team.

Downstream consumers reference signals.<field> paths verbatim. Bumping schemaVersion is required when any consumed path is renamed or removed.

Per-signal source matrix

SignalCLI commandRequired forFallback when missing
Authvercel whoamiEverythingExit with "run vercel login"
CLI versionvercel --versionEverythingExit with "upgrade to v53+" — v53 is the skill's compatibility floor
Project ID + Org ID.vercel/repo.json (newer) or .vercel/project.json (legacy) → VERCEL_PROJECT_ID + VERCEL_ORG_ID → argv. When the user passes a project ID and multi-project repo.json contains exactly one matching entry, the collector uses that entry's owner account.EverythingExit with "run vercel link or pass projectId". Multi-project repo.json without an explicit matching project ID, or any project ID without owner account scope, is ambiguous; ask the user to clarify the intended project/account
Framework supportlocal package.json via detectStack() + classifyFrameworkSupport()Code-backed route recommendationsStop before metric fan-out on unsupported frameworks unless the user chooses --continue-unsupported-framework
CLI command scopevercel whoami --format json, then vercel api /v2/teams/:orgId when a linked team_... ID must be converted to a slugKeeps vercel metrics, vercel usage, and vercel contract on the linked project's account instead of the user's current/personal scopePROJECT_SCOPE_UNRESOLVED or SCOPE_UNRESOLVED; stop and ask the user to clarify the intended project/account, then re-link under the intended team or personal account
Project/scope verificationvercel api /v9/projects/:id?teamId=<orgId> for team-owned projects; omit teamId for usr_... user-owned projectsProves the resolved account can read the resolved project before Observability Plus or billing conclusionsPROJECT_SCOPE_MISMATCH; stop and ask the user to confirm the exact project and team/personal scope. Do not report Observability Plus as missing until this check passes
Observability Plus configurationVercel CLI/API probe plus one metric access check; user-owned projects skip the team configuration endpoint and rely on the scoped metrics probeAll metrics.* signalsStop early when the account lacks Observability Plus or this project is disabled
Observability Plus metrics accessOne canary vercel metrics vercel.request.count --since 14d --limit 1, then full fan-out only if it succeedsAll metrics.* signalsSet observabilityPlusUsable=false with blocker detail; emit a blocker document after project/scope verification but before billing collection unless --continue-without-observability is passed
Project configVerified project API response from project/scope verificationFluid Compute, BotID, Speed Insights, security flagsStop on ownership mismatch; otherwise gates that need missing optional fields skip
Plan tiervercel api /v2/teams/:orgId (or /v2/user for user-owned projects) → billing.plan, then scoped vercel contract --format json fallback → inferPlan()Cost-context framing onlyplan="uncertain"; cost magnitudes still computed from usage.services[].billedCost
Billing usageScoped vercel usage --format json --from <14d> --to <today> with best-effort project grouping when supported by the installed CLICost magnitude framing, billing-driven candidatesnull + usageError set when queried and unavailable; NOT_COLLECTED_* when a preflight stop happened before billing collection
Stacklocal package.json + dir scanVersion-aware citation filtering, scanner gating"unknown" framework → all framework-specific citations filtered
metrics.fnDurationP95ByRoutevercel metrics vercel.function_invocation.function_duration_ms -a p95 --group-by route --since 14dslow_route, platform_fluid_compute gates{ok:false}; gate emits no candidates
metrics.requestsByRouteCachevercel metrics vercel.request.count --group-by route --group-by cache_result --since 14duncached_route, traffic-total computation{ok:false}
metrics.fnStatusByRoutevercel metrics vercel.function_invocation.count --group-by route --group-by http_status --since 14dCanonical function-level 5xx source for route_errors and slow_route error disqualification{ok:false}; fall back to requestsByRouteStatus only for older fixtures
metrics.requestsByRouteStatusvercel metrics vercel.request.count --group-by route --group-by http_status --since 14dCompatibility fallback for request-level status{ok:false}
metrics.externalApiP75vercel metrics vercel.external_api_request.request_duration_ms -a p75 --group-by origin_hostname --since 14dexternal_api_slow gate{ok:false}
metrics.fnStartTypeByRoutevercel metrics vercel.function_invocation.count -a sum --group-by route --group-by function_start_type --since 14dcold_start, platform_fluid_compute{ok:false}; gate dormant. function_start_type ∈ {cold,hot,prewarmed} is the public way to read cold-start rate on CLI v53.4.0+ (replaces the old "not derivable" gap).
metrics.fnGbHrByRoutevercel metrics vercel.function_invocation.function_duration_gbhr -a sum --group-by route --since 14dCost ranking / report breakdown{ok:false}
metrics.fnCpuMsByRoutevercel metrics vercel.function_invocation.function_cpu_time_ms -a sum --group-by route --since 14dActive CPU ranking (Fluid Compute billing unit){ok:false}
metrics.fnPeakMemoryByRoutevercel metrics vercel.function_invocation.peak_memory_mb -a max --group-by route --since 14doversized_memory gate{ok:false}
metrics.fnProvisionedMemoryByRoutevercel metrics vercel.function_invocation.provisioned_memory_mb -a max --group-by route --since 14doversized_memory gate{ok:false}
metrics.fnTtfbP95ByRoutevercel metrics vercel.function_invocation.ttfb_ms -a p95 --group-by route --since 14dTTFB cross-check for slow routes{ok:false}
metrics.fdtByRoutevercel metrics vercel.request.fdt_total_bytes -a sum --group-by route --since 14dBandwidth-cost ranking{ok:false}
metrics.fdtByBotvercel metrics vercel.request.fdt_total_bytes -a sum --group-by bot_category --since 14dStrengthens platform_bot_protection with observed bot bandwidth share{ok:false}; gate falls back to config-only signal
metrics.fdtByCachevercel metrics vercel.request.fdt_total_bytes -a sum --group-by cache_result --since 14dUncached-bandwidth narrative{ok:false}
metrics.middlewareCountvercel metrics vercel.middleware_invocation.count -a sum --group-by request_path --since 14dmiddleware_heavy gate{ok:false}; gate dormant
metrics.middlewareDurationP95vercel metrics vercel.middleware_invocation.duration_ms -a p95 --group-by request_path --since 14dMiddleware latency narrative{ok:false}
metrics.isrReadsByRoutevercel metrics vercel.isr_operation.read_units -a sum --group-by route --since 14disr_overrevalidation gate (denominator){ok:false}
metrics.isrWritesByRoutevercel metrics vercel.isr_operation.write_units -a sum --group-by route --since 14disr_overrevalidation gate (numerator){ok:false}

ISR read:write ratio caveat. isrReadsByRoute exposes the origin-tier read count only. CDN-tier reads (regional cache hits that never reach the ISR origin) are not separately surfaced today and can dominate total read volume. Before flagging "writes > reads" as inverted, the gate and report must (a) acknowledge CDN-tier reads aren't included, (b) corroborate with requestsByRouteCache cache_result=HIT share before alarming. A high origin-write rate alone does not imply pathological over-revalidation if the CDN is absorbing the steady-state read traffic. | metrics.imageCount, imageByHost, imageSourceBytes | vercel metrics vercel.image_transformation.* | Image-optimization narrative | {ok:false} | | metrics.cwvLcpByRoute, cwvInpByRoute, cwvClsByRoute, cwvTtfbByRoute, cwvCount, cwvCountByRoute | vercel metrics vercel.speed_insights_metric.* (p75 for vitals, sum for counts) --since 14d | cwv_poor gate | Empty when no Speed Insights measurements are returned for the 14-day window — gate stays dormant; do not infer disabled vs no traffic unless another signal proves it | | metrics.firewallByAction | vercel metrics vercel.firewall_action.count -a sum --group-by waf_action --since 14d | Bot-protection narrative; shows existing managed rule activity | {ok:false} | | metrics.botIdChecks | vercel metrics vercel.bot_id_check.count -a sum --since 14d | Confirms whether BotID is actively running | {ok:false} | | metrics.externalApiCount, externalApiBytes | vercel metrics vercel.external_api_request.* grouped by origin_hostname | External-dependency cost narrative | {ok:false} |

Error states and fallbacks

lib/vercel.mjs's runVercelJson() parses stdout as JSON first (the most reliable signal — the CLI emits structured error payloads even when exit code is non-zero), and only falls back to stderr substring matching when JSON parsing fails:

CodeMeaningSkill behavior
unsupported_frameworkDetected framework cannot reliably map Vercel route metrics back to source filesStop before metric fan-out; ask whether to continue with a limited platform/scanner audit
PROJECT_SCOPE_UNRESOLVEDThe project was found without an owner account, or .vercel/repo.json contains multiple linked projects and no explicit matching project ID was suppliedStop before vercel metrics, vercel usage, or vercel contract; ask the user which Vercel project and team/personal scope to audit
SCOPE_UNRESOLVEDThe linked project belongs to a specific team/user, but the collector could not resolve a CLI-safe --scope valueStop before vercel metrics, vercel usage, or vercel contract; ask the user to switch/re-link with the correct team
PROJECT_SCOPE_MISMATCHThe resolved team/personal account cannot read the resolved project, or the project API returns a different owner/projectStop before Observability Plus, metrics, usage, or contract checks; ask the user to confirm the exact Vercel project and team/personal scope
no_oplus_probeObservability Plus not enabled on teamStop before full metric fan-out; ask whether to enable Observability Plus or run scanner-only
project_disabledObservability Plus enabled for team but disabled for projectStop before full metric fan-out; ask the user to enable Observability Plus for this project or continue scanner-only
daily_quota_exceededObservability Plus query quota is exhausted for the dayStop before full metric fan-out; tell the user to retry after the next UTC midnight reset or ask whether to continue scanner-only
USAGE_UNAVAILABLEvercel usage returned no Costs payload after billing usage was actually queriedusage=null; cost-tier gates emit lower-priority candidates; billing section of the report shows the exact usage error
PROJECT_NOT_FOUNDvercel api /v9/projects/<id> 404 (typically wrong scope)project={error}; platform gates that depend on project config skip; report flags the data gap
invalid_filter_dimension / invalid_dimensionMetric query used a dimension the metric doesn't supportMetric returns {ok:false, code, allowedValues}; consumer can introspect and adjust
NOT_LINKEDThe app directory is not linked in the way vercel metrics requiresRun vercel link --yes --project <project-name-or-id> --cwd <app-dir>; add --team <team-id-or-slug> when known. Passing only VERCEL_PROJECT_ID is not enough for route metrics if cwd is unlinked
NOT_AUTHSession expiredCaller exits with "run vercel login"
FORBIDDEN403 — role lacks permissionSkip that endpoint; continue with degraded signal; surface in report
RATE_LIMIT429 from APITreat as "missing data" (no retry implemented yet)
EXIT_NAnything elseTreat as missing data; continue

The skill never crashes the entire collection on a single endpoint failure. Every catch-block uses ?? null or ?? {} so the JSON output is always well-shaped.

Real JSON shapes

vercel metrics <id> --format json
{
  "query": {
    "metric": "vercel.request.count",
    "aggregation": "sum",
    "groupBy": ["route"],
    "startTime": "2026-04-13T04:00:00.000Z",
    "endTime": "2026-05-13T08:00:00.000Z",
    "granularity": { "hours": 4 }
  },
  "summary": [
    { "route": "/dashboard/[sessionId]", "vercel_request_count_sum": 4923 },
    { "route": "/sw.js",               "vercel_request_count_sum": 872 }
  ],
  "data": [
    { "timestamp": "2026-04-13T04:00:00.000Z", "vercel_request_count_sum": 0, "route": "/dashboard/[sessionId]" }
    /* ... */
  ],
  "statistics": { "bytesRead": 10267, "rowsRead": 947, "dbTimeSeconds": 0 }
}

Field naming rule: the metric ID's dots become underscores, and the aggregation suffix is appended — vercel.request.count + sum → vercel_request_count_sum. lib/vercel.mjs::normalizeSummary() flattens summary[] into [{<dim>: v, ..., value: <n>}].

vercel metrics schema --format json

Array of {id, description} entries — NOT an object. Many metric IDs in earlier docs don't exist: there is no vercel.function.cold_starts, no vercel.cache.hits. Cache state is the cache_result dimension on vercel.request.count.

vercel metrics <id> --filter "<bad>"
{
  "error": {
    "code": "invalid_filter_dimension",
    "message": "Filter uses invalid dimension \"status\" for metric \"vercel.request.count\".",
    "allowedValues": [ "asn_id", ..., "http_status", ..., "route" ]
  }
}

Status filtering uses http_status (not status). Both http_status eq '500' and http_status ge 500 work.

vercel api /v9/projects/<id> / ?teamId=<orgId>

Top-level keys relevant to the skill (real, verified):

  • framework (string, e.g. "nextjs")

  • resourceConfig.fluid (boolean) — Fluid Compute toggle

  • defaultResourceConfig.fluid — template for new functions

  • security.botIdEnabled (boolean) — BotID toggle

  • security.managedRules.bot_filter ({active, action}) — firewall rule

  • speedInsights ({id, hasData})

  • webAnalytics ({id}) — installed but features.webAnalytics says enabled state

  • nodeVersion (e.g. "22.x")

Calling without ?teamId= returns 404 when the project belongs to a team other than the user's currentTeam. For user-owned projects (orgId starts with usr_), omit teamId and let the CLI use the authenticated user context.

vercel contract --format json
{ "context": "example-team", "commitments": [], "totalCommitments": 0 }

The direct account billing record is the primary plan signal: billing.plan from vercel api /v2/teams/:orgId or vercel api /v2/user is expected to be hobby, pro, or enterprise.

vercel contract is only a fallback. commitments[] field names are not stable, so inferPlan() tries category, commitmentCategory, and type; category Spend means Pro and Usage means Enterprise. Empty commitments no longer imply Hobby by themselves.

vercel usage --format json

May return Error: Costs not found (404). Treat that queried error as USAGE_UNAVAILABLE and degrade — the skill can still produce a useful report from metrics + scanner. Do not use this explanation when usageError is NOT_COLLECTED_OBSERVABILITY_BLOCKED or another NOT_COLLECTED_* value; those mean the audit stopped before vercel usage ran.

Why we avoid stderr grep

CLI error message strings are not stable contracts — they can change between versions. Detecting OPLUS_REQUIRED by greping stderr.includes('Observability Plus') will break the moment Vercel rewords the message.

runVercelJson() therefore:

  1. Always tries to parse stdout as JSON first. Most failures emit a structured {error:{code,message,allowedValues}} payload that's deterministic.

  2. Only falls back to a lower-case stderr substring match when stdout was not parseable JSON.

  3. Categorizes anything unrecognized as EXIT_N and treats it as "missing data, continue."

The skill is correct without precise category detection. The categories exist to give the user better error messages, not to drive control flow.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Node.js

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Vercel
Publisher
Vercel (Official)
Source
vercel-labs/agent-skills · skills/vercel-optimize · commit 1a2c79d
Licence
MIT License (redistribution allowed)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Vercel or Vercel.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download vercel-optimize.zip