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
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/vercel-labs/vercel-optimize/downloadUnzip 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.mjsdecides 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, andvercel api.Authenticated CLI session:
vercel login.Linked app directory:
vercel link.VERCEL_PROJECT_IDcan help resolve project config, butvercel metricsstill requires directory linkage. The link or environment must include the intended project org/team/user scope so the collector can resolve a CLI-safe--scopeand keepvercel metrics,vercel usage, andvercel contracton 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.
| Framework | Status | Notes |
|---|---|---|
| Next.js App Router | supported | strongest route mapping, scanners, playbooks, citations |
| Next.js Pages Router | supported | scoped to Pages Router idioms when detected |
| SvelteKit | supported | route mapping for src/routes files and SvelteKit scanner |
| Nuxt | supported | route mapping plus generic/platform checks; fewer framework-specific recs |
| Astro | limited | route mapping plus generic checks; fewer framework-specific recs |
| Hono / Remix / unknown | blocked by default | continue 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, orPROJECT_SCOPE_MISMATCH: stop and ask which Vercel project and team/personal scope the user wants audited. For team projects, rerun aftervercel link --yes --project <project-name-or-id> --team <team-slug>; for personal projects, rerun after linking under the intended user account or after setting bothVERCEL_PROJECT_IDandVERCEL_ORG_ID.observabilityPlusBlocker === null: continue.no_traffic: tell the user route metrics are sparse; continue only if they accept limited output.payment_requiredorno_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 knownforbiddenorproject_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:
Print
exactChatMessage.bodyexactly as returned. Do not summarize, truncate, reorder, or rewrite it.Then ask
questionTextusingquestionPayloadwhen the host supports structured questions.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_mismatcherror_stormdeployment_regressionscanner_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.jsonorevidence.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
$Nsavings.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 readyobservations from investigationinvestigated, no change recommendednot investigated in this run
Avoid:
sub-agentabstentionpassRatequality scoregateLLM
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
- AGENTS.md1.9 KiB
- ATTRIBUTION.mdAdded by AutoGineer848 B
- CONTRIBUTING.md2.2 KiB
- README.md4.4 KiB
- SKILL.md16.9 KiB
- lib/auth-route.mjsScript807 B
- lib/budget-summary.mjsScript7.0 KiB
- lib/citations.mjsScript3.9 KiB
- lib/cost-coverage.mjsScript8.4 KiB
- lib/dedup-recs.mjsScript9.9 KiB
- lib/deep-dive.mjsScript10.2 KiB
- lib/display-labels.mjsScript7.4 KiB
- lib/extract-claims.mjsScript18.7 KiB
- lib/framework-support.mjsScript2.1 KiB
- lib/gates/build-minutes-fanout.mjsScript2.9 KiB
- lib/gates/cold-start.mjsScript2.7 KiB
- lib/gates/contract.mjsScript3.1 KiB
- lib/gates/cwv-poor.mjsScript3.3 KiB
- lib/gates/external-api-slow.mjsScript2.1 KiB
- lib/gates/hard-gates.mjsScript2.5 KiB
- lib/gates/index.mjsScript2.0 KiB
- lib/gates/isr-overrevalidation.mjsScript2.4 KiB
- lib/gates/middleware-heavy.mjsScript2.0 KiB
- lib/gates/observability-events-attribution.mjsScript2.2 KiB
- lib/gates/platform-bot-protection.mjsScript5.0 KiB
- lib/gates/platform-fluid-compute.mjsScript3.5 KiB
- lib/gates/region-misconfig.mjsScript3.0 KiB
- lib/gates/route-errors.mjsScript3.0 KiB
- lib/gates/scanner-driven.mjsScript5.1 KiB
- lib/gates/select-candidates.mjsScript4.6 KiB
- lib/gates/slow-route.mjsScript4.3 KiB
- lib/gates/types.d.tsScript893 B
- lib/gates/uncached-route.mjsScript3.9 KiB
- lib/gates/usage-spike-triage.mjsScript5.0 KiB
- lib/grade-recommendation.mjsScript6.7 KiB
- lib/impact-label.mjsScript5.2 KiB
- lib/impact-magnitude.mjsScript2.1 KiB
- lib/investigation-brief.mjsScript34.3 KiB
- lib/observation-safety.mjsScript9.3 KiB
- lib/project-facts.mjsScript4.3 KiB
- lib/queries.mjsScript10.1 KiB
- lib/reconcile-candidates.mjsScript15.6 KiB
- lib/render-report.mjsScript38.2 KiB
- lib/repo-root.mjsScript3.1 KiB
- lib/route-normalize.mjsScript8.4 KiB
- lib/sanitizers/bot-protection-certainty.mjsScript1.9 KiB
- lib/sanitizers/cache-tag-invalidation-certainty.mjsScript1.5 KiB
- lib/sanitizers/count-correct.mjsScript1.9 KiB
- lib/sanitizers/function-duration-invocations.mjsScript1.4 KiB
- lib/sanitizers/index.mjsScript3.0 KiB
- lib/sanitizers/middleware-conflict.mjsScript1.5 KiB
- lib/sanitizers/missing-citation.mjsScript497 B
- lib/sanitizers/pre-release.mjsScript2.2 KiB
- lib/sanitizers/rate-limit.mjsScript2.6 KiB
- lib/sanitizers/rendering-mode-mislabel.mjs1.6 KiB
- lib/sanitizers/undeclared-dep.mjs2.8 KiB
- lib/sanitizers/vercel-directive-strip.mjs1.4 KiB
- lib/sanitizers/window-units.mjs869 B
- lib/scanners/cache-components-suspense-dedupe.mjs4.3 KiB
- lib/scanners/edge-heavy-import.mjs3.7 KiB
- lib/scanners/force-dynamic.mjs1.5 KiB
- lib/scanners/headers-in-page.mjs1.5 KiB
- lib/scanners/index.mjs1.4 KiB
- lib/scanners/large-static-asset.mjs3.2 KiB
- lib/scanners/max-age-without-s-maxage.mjs1.6 KiB
- lib/scanners/middleware-broad-matcher.mjs1.9 KiB
- lib/scanners/missing-cache-headers.mjs3.8 KiB
- lib/scanners/prisma-include-tree.mjs1.5 KiB
- lib/scanners/region-pin-in-config.mjs3.4 KiB
- lib/scanners/source-maps-production.mjs1.3 KiB
- lib/scanners/sveltekit-prerender-missing.mjs2.1 KiB
- lib/scanners/turbo-force-bypass.mjs4.9 KiB
- lib/scanners/unoptimized-image.mjs4.4 KiB
- lib/scanners/use-cache-date-stamp.mjs3.9 KiB
- lib/support-topics.mjs12.5 KiB
- lib/throttle.mjs8.8 KiB
- lib/util.mjs544 B
- lib/vercel.mjs30.4 KiB
- lib/verify-claim.mjs59.6 KiB
- lib/workspace-resolver.mjs17.1 KiB
- metadata.json903 B
- references/candidates.md8.3 KiB
- references/data-collection.md20.4 KiB
- references/docs-library.json30.8 KiB
- references/doctrine.md9.3 KiB
- references/observability-plus.md5.2 KiB
- references/playbooks/README.md2.7 KiB
- references/playbooks/ai-application.md3.8 KiB
- references/playbooks/api-service.md2.4 KiB
- references/playbooks/content-site.md2.4 KiB
- references/playbooks/ecommerce.md2.7 KiB
- references/playbooks/marketing.md2.6 KiB
- references/playbooks/saas.md2.8 KiB
- references/playbooks/sveltekit.md3.9 KiB
- references/recommendations.md10.5 KiB
- references/scanner-patterns.md13.4 KiB
- references/scoring.md12.2 KiB
- references/support-topics/README.md1.7 KiB
- references/support-topics/astro-edge-middleware-scope.md1012 B
- references/support-topics/astro-output-mode-and-isr.md1.1 KiB
- references/support-topics/auth-preserving-parallelization.md1.2 KiB
- references/support-topics/bot-protection-product-guardrails.md1.1 KiB
- references/support-topics/build-minutes-monorepo-fanout.md1.2 KiB
- references/support-topics/cache-components-static-shell-boundaries.md1.1 KiB
- references/support-topics/cache-components-suspense-dedupe-pitfall.md1.3 KiB
- references/support-topics/cdn-cache-auth-safety.md1.0 KiB
- references/support-topics/cold-start-initialization-bundle.md1.1 KiB
- references/support-topics/core-web-vitals-client-bottlenecks.md1.0 KiB
- references/support-topics/database-egress-pooling-region.md1015 B
- references/support-topics/dynamic-rendering-traps.md1.1 KiB
- references/support-topics/external-api-critical-path-platform.md1.1 KiB
- references/support-topics/external-api-critical-path.md978 B
- references/support-topics/fast-data-transfer-payloads.md1.0 KiB
- references/support-topics/fluid-compute-caveats.md1.1 KiB
- references/support-topics/function-duration-io-and-after.md1.0 KiB
- references/support-topics/function-invocation-reduction.md1.2 KiB
- references/support-topics/function-region-misconfiguration-ttfb.md1.2 KiB
- references/support-topics/image-optimization-cost-control.md1.0 KiB
- references/support-topics/isr-revalidation-static-generation.md1.4 KiB
- references/support-topics/middleware-proxy-edge-cost.md991 B
- references/support-topics/next-fetch-revalidate-floor.md1.0 KiB
- references/support-topics/next-font-cls-self-hosting.md906 B
- references/support-topics/next-heavy-ui-lazy-load-boundaries.md1.0 KiB
- references/support-topics/next-image-lcp-preload-sizes.md1.0 KiB
- references/support-topics/next-route-handler-get-cache-defaults.md1.0 KiB
- references/support-topics/next-script-third-party-strategy.md1.0 KiB
- references/support-topics/nextjs-version-cache-semantics.md996 B
- references/support-topics/not-found-catchall-request-waste.md1.2 KiB
- references/support-topics/nuxt-route-rules-cache-isr.md1.2 KiB
- references/support-topics/observability-events-cost-attribution.md1.1 KiB
- references/support-topics/post-response-work-waituntil.md1009 B
- references/support-topics/route-error-durable-offload.md1.3 KiB
- references/support-topics/route-error-runtime-limits.md988 B
- references/support-topics/runtime-cache-reusable-data.md1.2 KiB
- references/support-topics/sveltekit-isr-prerender-safety.md1.1 KiB
- references/support-topics/sveltekit-split-cold-start-tradeoff.md1.0 KiB
- references/support-topics/usage-spike-triage.md1018 B
- references/support-topics/use-cache-date-stamp-isr-write-amplifier.md1.2 KiB
- references/support-topics/use-cache-remote-shared-origin-data.md1.1 KiB
- references/support-topics/workflow-resumable-stream-routes.md1.2 KiB
- references/verification.md8.8 KiB
- references/voice.md3.6 KiB
- scripts/budget-summary.mjs2.0 KiB
- scripts/build-docs.mjs3.3 KiB
- scripts/check-citations.mjs3.4 KiB
- scripts/check-docs-fresh.mjs3.8 KiB
- scripts/collect-signals.mjs21.1 KiB
- scripts/collect-sub-agent-outputs.mjs9.9 KiB
- scripts/deep-dive.mjs12.0 KiB
- scripts/gate-investigations.mjs6.2 KiB
- scripts/merge-signals.mjs6.2 KiB
- scripts/prepare-investigation-brief.mjs7.9 KiB
- scripts/reconcile-candidates.mjs2.4 KiB
- scripts/render-report.mjs17.0 KiB
- scripts/scan-codebase.mjs11.3 KiB
- scripts/verify-and-regen.mjs14.9 KiB
- scripts/verify-finding.mjs698 B
lib/vercel.mjs
// Vercel CLI helpers. All shell-outs use execFile (not exec) — no shell injection. Error detection: exit code + JSON-parse first; stderr grep only as fallback (CLI error strings aren't a stable contract).
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { existsSync, readFileSync } from 'node:fs';
import { readFile, access } from 'node:fs/promises';
import { join, win32 } from 'node:path';
import { getMetricThrottle, isDailyQuotaExceeded, retryOnRateLimit } from './throttle.mjs';
const exec = promisify(execFile);
// On Windows, execFile cannot run the `vercel.cmd` shim directly: PATHEXT is not
// applied by execFile, and .cmd/.bat require `shell: true` since Node 20 — but a
// shell would mangle args containing spaces or URL query strings (e.g.
// `vercel api '/v9/projects/:id?teamId=:org'`, `-f 'http_status ge 500'`). So we
// resolve the Vercel package's JS entry from PATH and run it via `node` directly:
// no shell, every arg passed verbatim. POSIX is unchanged (`vercel` on PATH).
export function resolveVercelCommand({
platform = process.platform,
env = process.env,
execPath = process.execPath,
exists = existsSync,
readText = (file) => readFileSync(file, 'utf-8'),
} = {}) {
if (platform !== 'win32') return { file: 'vercel', prefix: [] };
const pathValue = env.PATH || env.Path || env.path || '';
for (const dir of pathValue.split(win32.delimiter).filter(Boolean)) {
const entry = resolveVercelPackageEntry(dir, exists);
if (entry) return { file: execPath, prefix: [entry] };
const shimEntry = resolveVercelShimEntry(dir, exists, readText);
if (shimEntry) return { file: execPath, prefix: [shimEntry] };
}
return { file: execPath, prefix: [], missing: true };
}
function resolveVercelPackageEntry(dir, exists) {
const packageRoots = [
win32.join(dir, 'node_modules', 'vercel'),
win32.join(win32.dirname(dir), 'vercel'),
];
for (const root of packageRoots) {
for (const rel of ['dist/vc.js', 'dist/index.js']) {
const entry = win32.join(root, rel);
if (exists(entry)) return entry;
}
}
return null;
}
function resolveVercelShimEntry(dir, exists, readText) {
for (const bin of ['vercel.cmd', 'vc.cmd']) {
const shim = win32.join(dir, bin);
if (!exists(shim)) continue;
let raw;
try {
raw = readText(shim);
} catch {
continue;
}
const match = raw.match(/["']([^"'\r\n]*vercel[\\/]+dist[\\/]+(?:vc|index)\.js)["']/i);
if (!match) continue;
const entry = normalizeWindowsShimTarget(match[1], dir);
if (exists(entry)) return entry;
}
return null;
}
function normalizeWindowsShimTarget(target, dir) {
const baseDir = `${dir}${win32.sep}`;
const expanded = target
.replace(/%~dp0/gi, baseDir)
.replace(/%dp0%/gi, baseDir)
.replace(/\$basedir/g, dir);
return win32.normalize(win32.isAbsolute(expanded) ? expanded : win32.resolve(dir, expanded));
}
async function runVercel(args, opts = {}) {
const command = resolveVercelCommand({ env: opts.env });
if (command.missing) {
const err = new Error('VERCEL_NOT_INSTALLED: `vercel` CLI not found in PATH. Install with `npm i -g vercel@latest`.');
err.code = 'ENOENT';
throw err;
}
return await exec(command.file, [...command.prefix, ...args], { windowsHide: true, ...opts });
}
const MIN_CLI_VERSION = [53, 0, 0];
// Pre-v53 lacks `vercel metrics` and `vercel contract`.
export async function checkCliVersion() {
let raw;
try {
const { stdout } = await runVercel(['--version']);
raw = stdout.trim();
} catch (err) {
throw new Error('VERCEL_NOT_INSTALLED: `vercel` CLI not found in PATH. Install with `npm i -g vercel@latest`.');
}
const m = raw.match(/(\d+)\.(\d+)\.(\d+)/);
if (!m) throw new Error(`VERCEL_VERSION_UNPARSEABLE: ${raw}`);
const v = [Number(m[1]), Number(m[2]), Number(m[3])];
for (let i = 0; i < 3; i++) {
if (v[i] > MIN_CLI_VERSION[i]) return v;
if (v[i] < MIN_CLI_VERSION[i]) {
throw new Error(
`VERCEL_CLI_TOO_OLD: have ${v.join('.')}, need >= ${MIN_CLI_VERSION.join('.')}. Upgrade with \`npm i -g vercel@latest\`.`
);
}
}
return v;
}
export async function checkAuth() {
try {
await runVercel(['whoami']);
} catch {
throw new Error('NOT_AUTH: run `vercel login`.');
}
}
export async function getCliIdentity() {
const r = await runVercelJson(['whoami', '--format', 'json']);
return r.ok ? r.data : null;
}
// Supports newer `.vercel/repo.json` (multi-project) + legacy `.vercel/project.json` (single-project).
export async function readProjectJson(cwd = process.cwd()) {
try {
const raw = await readFile(join(cwd, '.vercel', 'repo.json'), 'utf-8');
const parsed = JSON.parse(raw);
const projects = Array.isArray(parsed?.projects) ? parsed.projects.filter((p) => p?.id) : [];
if (projects.length > 1) {
throw new Error('AMBIGUOUS_PROJECT_LINK: `.vercel/repo.json` contains multiple projects. Run from the linked app directory, or pass the intended projectId together with VERCEL_ORG_ID.');
}
const first = projects[0];
if (first?.id) {
return { projectId: first.id, orgId: first.orgId ?? null, source: 'repo.json' };
}
} catch (err) {
if (err?.message?.startsWith('AMBIGUOUS_PROJECT_LINK:')) throw err;
/* fall through */
}
// Legacy single-project format.
try {
const raw = await readFile(join(cwd, '.vercel', 'project.json'), 'utf-8');
const parsed = JSON.parse(raw);
if (parsed?.projectId) {
return { projectId: parsed.projectId, orgId: parsed.orgId ?? null, source: 'project.json' };
}
} catch { /* fall through */ }
return null;
}
// Does NOT auto-run `vercel link` — interactive surprises bad.
export async function resolveProjectId(explicit, cwd = process.cwd()) {
if (explicit) {
const linked = process.env.VERCEL_ORG_ID
? null
: await readLinkedOwnerForProjectId(explicit, cwd);
return {
projectId: explicit,
orgId: process.env.VERCEL_ORG_ID || linked?.orgId || null,
source: linked?.source ? `arg+${linked.source}` : 'arg',
};
}
if (process.env.VERCEL_PROJECT_ID) {
const linked = process.env.VERCEL_ORG_ID
? null
: await readLinkedOwnerForProjectId(process.env.VERCEL_PROJECT_ID, cwd);
return {
projectId: process.env.VERCEL_PROJECT_ID,
orgId: process.env.VERCEL_ORG_ID || linked?.orgId || null,
source: linked?.source ? `env+${linked.source}` : 'env',
};
}
return await readProjectJson(cwd);
}
async function readLinkedOwnerForProjectId(projectId, cwd = process.cwd()) {
try {
const raw = await readFile(join(cwd, '.vercel', 'repo.json'), 'utf-8');
const parsed = JSON.parse(raw);
const matches = (Array.isArray(parsed?.projects) ? parsed.projects : [])
.filter((p) => p?.id && String(p.id) === String(projectId));
if (matches.length > 1) {
throw new Error('AMBIGUOUS_PROJECT_LINK: `.vercel/repo.json` contains multiple entries for the requested projectId. Ask the user to confirm the intended Vercel team/personal scope.');
}
const match = matches[0];
if (match?.orgId) return { orgId: match.orgId, source: 'repo.json' };
} catch (err) {
if (err?.message?.startsWith('AMBIGUOUS_PROJECT_LINK:')) throw err;
/* fall through */
}
try {
const raw = await readFile(join(cwd, '.vercel', 'project.json'), 'utf-8');
const parsed = JSON.parse(raw);
if (String(parsed?.projectId ?? '') === String(projectId) && parsed?.orgId) {
return { orgId: parsed.orgId, source: 'project.json' };
}
} catch { /* fall through */ }
return null;
}
export async function resolveCommandScope(project = {}) {
const orgId = project?.orgId ?? null;
if (!orgId) {
return {
ok: false,
cliScope: null,
source: 'missing-org-scope',
required: true,
error: 'PROJECT_SCOPE_UNRESOLVED',
detail: 'The project was resolved without an owner account, so the collector cannot prove which Vercel scope to query.',
};
}
const identity = await getCliIdentity();
const currentTeam = identity?.team ?? null;
if (String(orgId).startsWith('team_')) {
if (currentTeam?.id === orgId && currentTeam?.slug) {
return {
ok: true,
cliScope: currentTeam.slug,
source: 'whoami-current-team',
required: true,
teamId: orgId,
detail: 'Resolved linked team ID to the current CLI team slug.',
};
}
const team = await getTeamInfo(orgId);
if (team.ok && team.slug) {
return {
ok: true,
cliScope: team.slug,
source: 'team-api',
required: true,
teamId: orgId,
detail: 'Resolved linked team ID to a Vercel CLI scope slug.',
};
}
return {
ok: false,
cliScope: null,
source: 'team-api',
required: true,
teamId: orgId,
error: team.error ?? 'TEAM_SCOPE_UNRESOLVED',
detail: 'Could not resolve the linked team ID to a Vercel CLI scope slug.',
};
}
if (String(orgId).startsWith('usr_')) {
const user = identity?.user ?? identity ?? {};
const userId = user.id ?? identity?.id ?? null;
const username = user.username ?? identity?.username ?? null;
if ((!userId || userId === orgId) && username) {
return {
ok: true,
cliScope: username,
source: 'whoami-user',
required: true,
userId: orgId,
detail: 'Resolved linked user ID to a Vercel CLI username scope.',
};
}
return {
ok: false,
cliScope: null,
source: 'whoami-user',
required: true,
userId: orgId,
error: 'USER_SCOPE_UNRESOLVED',
detail: 'Could not resolve the linked user ID to the authenticated Vercel username.',
};
}
return {
ok: true,
cliScope: orgId,
source: 'linked-org-scope',
required: true,
detail: 'Using the linked org value as the Vercel CLI scope.',
};
}
async function getTeamInfo(teamIdOrSlug) {
const r = await runVercelJson(['api', `/v2/teams/${encodeURIComponent(teamIdOrSlug)}`]);
if (!r.ok) return { ok: false, error: r.code ?? 'UNKNOWN' };
const team = r.data?.team ?? r.data ?? {};
return {
ok: true,
id: team.id ?? null,
slug: team.slug ?? null,
name: team.name ?? null,
};
}
// Some commands emit `{error: {...}}` on stdout AND exit non-zero — parse stdout first; embedded `error` is the most reliable signal.
// 32 MiB buffer: 14d function-duration timeseries across many routes exceeds Node's 1 MiB default.
export async function runVercelJson(args, opts = {}) {
let stdout = '';
let stderr = '';
let exitCode = 0;
try {
const r = await runVercel(args, { maxBuffer: 32 * 1024 * 1024, ...opts });
stdout = r.stdout;
stderr = r.stderr;
} catch (err) {
stdout = err.stdout || '';
stderr = err.stderr || '';
exitCode = err.code ?? err.exitCode ?? 1;
}
const safeStderr = redactSensitiveText(stderr);
if (stdout && stdout.trim().startsWith('{')) {
try {
const data = JSON.parse(stdout);
if (data && typeof data === 'object' && data.error) {
const failure = {
ok: false,
code: data.error.code || `EXIT_${exitCode}`,
message: redactSensitiveText(data.error.message || ''),
allowedValues: data.error.allowedValues,
stderr: safeStderr,
};
return isDailyQuotaExceeded(failure)
? { ...failure, code: 'DAILY_QUOTA_EXCEEDED', originalCode: failure.code }
: failure;
}
if (exitCode === 0) return { ok: true, data };
// Exit non-zero, no `error` key, parseable stdout → still useful.
return { ok: true, data };
} catch {
/* fall through to stderr categorization */
}
}
// Metrics schema returns a top-level array.
if (stdout && stdout.trim().startsWith('[')) {
try {
const data = JSON.parse(stdout);
if (exitCode === 0) return { ok: true, data };
} catch { /* fall through */ }
}
return {
ok: false,
code: categorizeError(exitCode, stderr),
stderr: safeStderr,
};
}
export function redactSensitiveText(value) {
return String(value ?? '')
.replace(/\b(Bearer)\s+[A-Za-z0-9._~+/=-]{12,}/gi, '$1 [REDACTED]')
.replace(/\b(Authorization:\s*)[^\r\n]+/gi, '$1[REDACTED]')
.replace(/\b(x-vercel-id:\s*)[^\r\n]+/gi, '$1[REDACTED]')
.replace(/\b(VERCEL_TOKEN|TURBO_TOKEN|NPM_TOKEN|NODE_AUTH_TOKEN|GITHUB_TOKEN)=("[^"]+"|'[^']+'|[^\s"'`]+)/g, '$1=[REDACTED]')
.replace(/(--token(?:=|\s+))("[^"]+"|'[^']+'|[^\s"'`]+)/gi, '$1[REDACTED]')
.replace(/\b(prj|team|usr)_[A-Za-z0-9]{8,}\b/g, '$1_[REDACTED]')
.replace(/("token"\s*:\s*")[^"]{8,}(")/gi, '$1[REDACTED]$2');
}
// CLI doesn't emit machine-readable error codes for these states — stderr substring is fallback only.
function categorizeError(exitCode, stderr) {
const lc = (stderr || '').toLowerCase();
if (isDailyQuotaExceeded({ ok: false, stderr })) return 'DAILY_QUOTA_EXCEEDED';
if (lc.includes('observability plus')) return 'OPLUS_REQUIRED';
if (lc.includes('costs not found')) return 'USAGE_UNAVAILABLE';
if (lc.includes('project not found')) return 'PROJECT_NOT_FOUND';
if (lc.includes('not linked') || lc.includes('no project')) return 'NOT_LINKED';
if (lc.includes('log in') || lc.includes('credentials')) return 'NOT_AUTH';
if (lc.includes('rate limit') || lc.includes('429')) return 'RATE_LIMIT';
if (lc.includes('permission') || lc.includes('not authorized') || lc.includes('403'))
return 'FORBIDDEN';
return `EXIT_${exitCode}`;
}
// Schema is global per team — pass scope so we hit the right team rather than user's currentTeam.
export async function hasObservabilityPlus(scope) {
const r = await runVercelJson(scopedArgs(['metrics', 'schema', '--format', 'json'], scope));
return r.ok;
}
export async function getMetricsSchema(scope) {
const r = await runVercelJson(scopedArgs(['metrics', 'schema', '--format', 'json'], scope));
return r.ok ? r.data : null;
}
export async function checkObservabilityPlusConfiguration({ orgId, projectId } = {}) {
if (!orgId) {
return {
ok: false,
source: 'observability-configuration-api',
blocker: 'unknown',
detail: 'No team ID was available for the Observability Plus configuration preflight.',
};
}
if (String(orgId).startsWith('usr_')) {
return {
ok: false,
source: 'observability-configuration-api',
access: null,
blocker: 'unknown',
detail: 'The Observability Plus team configuration preflight is not available for a user-owned project; falling back to the scoped metrics probe.',
};
}
const qs = `?teamId=${encodeURIComponent(orgId)}`;
const r = await runVercelJson(['api', `/v1/observability/manage/configuration/projects${qs}`]);
return classifyObservabilityPlusConfiguration(r, { projectId });
}
export function classifyObservabilityPlusConfiguration(result, { projectId } = {}) {
const source = 'observability-configuration-api';
if (result?.ok) {
const disabledProjects = Array.isArray(result.data?.disabledProjects) ? result.data.disabledProjects : [];
const disabled = projectId
? disabledProjects.find((p) => String(p?.id ?? '') === String(projectId))
: null;
if (disabled) {
return {
ok: true,
source,
access: false,
blocker: 'project_disabled',
detail: 'Observability Plus is enabled for the team but disabled for this project.',
disabledProject: {
id: disabled.id,
name: disabled.name ?? null,
disabledAt: disabled.disabledAt ?? null,
},
};
}
return {
ok: true,
source,
access: true,
blocker: null,
detail: 'Observability Plus is enabled for this team/project.',
};
}
const code = String(result?.code ?? 'unknown').toLowerCase();
const text = `${result?.message ?? ''}\n${result?.stderr ?? ''}`.toLowerCase();
const mentionsObservabilityPlusNotEnabled =
/observability plus[\s\S]{0,160}not enabled/.test(text) ||
/not enabled[\s\S]{0,160}observability plus/.test(text) ||
/subscription to observability plus[\s\S]{0,160}required/.test(text);
if (code === 'oplus_required' || ((code === 'not_found' || code === '404') && mentionsObservabilityPlusNotEnabled)) {
return {
ok: true,
source,
access: false,
blocker: 'no_oplus_probe',
detail: 'Route-level metrics are unavailable because Observability Plus is not enabled for this team.',
};
}
if (/forbidden|not_authorized|403/.test(code) || /forbidden|not authorized|permission|403/.test(text)) {
return {
ok: false,
source,
access: null,
blocker: 'forbidden',
detail: 'Could not read Observability Plus configuration for this team. Run `vercel switch <team>` and verify access.',
};
}
if (/not_auth|unauthorized|401/.test(code) || /unauthorized|log in|credentials|401/.test(text)) {
return {
ok: false,
source,
access: null,
blocker: 'forbidden',
detail: 'Could not read Observability Plus configuration because the Vercel CLI is not authenticated.',
};
}
return {
ok: false,
source,
access: null,
blocker: 'unknown',
detail: `Could not determine Observability Plus configuration before querying metrics (code=${code}).`,
};
}
// Returns `{ok, ...}`. CLI summary defaults to top 10 groups under --group-by; widen via opts.limit.
export async function queryMetric(metricId, opts = {}) {
const args = ['metrics', metricId, '--format', 'json'];
if (opts.aggregation) args.push('-a', opts.aggregation);
for (const dim of opts.groupBy ?? []) args.push('--group-by', dim);
if (opts.filter) args.push('-f', opts.filter);
if (opts.since) args.push('--since', opts.since);
if (opts.until) args.push('--until', opts.until);
if (opts.limit) args.push('--limit', String(opts.limit));
// 3-layer protection: semaphore (8 concurrent) + sliding-window (80/60s) + retryOnRateLimit (3× 60-90s jitter). payment_required is terminal.
const throttle = getMetricThrottle();
const onRetry = (attempt, delayMs) => {
console.error(`[queryMetric] ${metricId} hit RATE_LIMITED; retry ${attempt}/3 after ${(delayMs / 1000).toFixed(0)}s`);
};
return await throttle.run(() =>
retryOnRateLimit(() => runVercelJson(scopedArgs(args, opts.scope)), { onRetry })
);
}
// Team-owned projects need `?teamId=<orgId>` to avoid current-team drift. User-
// owned projects use the authenticated user context and should not pass teamId.
export async function getProjectConfig(projectId, orgId) {
const qs = orgId && !String(orgId).startsWith('usr_')
? `?teamId=${encodeURIComponent(orgId)}`
: '';
const r = await runVercelJson(['api', `/v9/projects/${projectId}${qs}`]);
return r.ok ? r.data : { error: r.code, stderr: r.stderr };
}
// USAGE_UNAVAILABLE distinguishes "no Costs feature" from genuine emptiness.
export async function getUsage({ days = 14, scope, groupByProject = true } = {}) {
const toDate = new Date();
const fromDate = new Date(toDate.getTime() - days * 86400000);
const fmt = (d) => d.toISOString().slice(0, 10);
const args = [
'usage',
'--format', 'json',
'--from', fmt(fromDate),
'--to', fmt(toDate),
];
// The CLI rejects --breakdown with --group-by. Project grouping is higher
// value for this skill because every recommendation must be project-scoped.
if (groupByProject) args.push('--group-by', 'project');
else args.push('--breakdown', 'daily');
return await runVercelJson(scopedArgs(args, scope));
}
// CLI `--group-by project` returns project buckets under groupBy.data. Older
// breakdown-shaped fixtures tag service rows with projectId; keep both paths.
export function filterUsageByProject(usage, projectId, projectName = null) {
if (!usage || !projectId) return { filtered: null, matched: false, unattributedTotal: 0 };
if (usage.groupBy?.dimension === 'project' && Array.isArray(usage.groupBy.data)) {
const project = usage.groupBy.data.find((entry) => projectMatches(entry, projectId, projectName));
if (!project) return { filtered: null, matched: false, unattributedTotal: 0 };
return {
filtered: {
...usage,
groupBy: { ...usage.groupBy, data: [project] },
services: Array.isArray(project.services) ? project.services : [],
totals: project.totals ?? null,
project: { name: project.name ?? projectName ?? null, projectId: project.projectId ?? projectId },
},
matched: true,
unattributedTotal: 0,
};
}
const breakdown = usage.breakdown;
if (!breakdown || !Array.isArray(breakdown.data)) {
return { filtered: null, matched: false, unattributedTotal: 0 };
}
const out = {
...usage,
breakdown: { ...breakdown, data: [] },
};
let matchedAny = false;
let projectTotal = 0;
let unattributedTotal = 0;
for (const day of breakdown.data) {
const services = Array.isArray(day.services) ? day.services : [];
const projectRows = services.filter((s) => projectMatches(s, projectId, projectName));
const unattributedRows = services.filter((s) => !s.projectId && !s.project);
for (const r of projectRows) projectTotal += (r.billedCost ?? r.cost ?? 0);
for (const r of unattributedRows) unattributedTotal += (r.billedCost ?? r.cost ?? 0);
if (projectRows.length === 0) continue;
matchedAny = true;
out.breakdown.data.push({ ...day, services: projectRows });
}
if (!matchedAny) return { filtered: null, matched: false, unattributedTotal };
out.services = aggregateServicesByName(out.breakdown.data);
out.totals = { billedCost: projectTotal };
return { filtered: out, matched: true, unattributedTotal };
}
function projectMatches(serviceRow, projectId, projectName = null) {
if (!serviceRow) return false;
if (serviceRow.projectId === projectId) return true;
if (projectName && serviceRow.name === projectName) return true;
if (projectName && serviceRow.project === projectName) return true;
if (serviceRow.project === projectId) return true;
if (serviceRow.project && (serviceRow.project.id === projectId || serviceRow.project.projectId === projectId || serviceRow.project.name === projectName)) return true;
return false;
}
function aggregateServicesByName(days) {
const byName = new Map();
for (const day of days) {
for (const s of (day.services ?? [])) {
const key = s.name ?? '(unnamed)';
const prev = byName.get(key) ?? { name: key, billedCost: 0, pricingQuantity: 0, pricingUnit: s.pricingUnit ?? null };
prev.billedCost += (s.billedCost ?? s.cost ?? 0);
prev.pricingQuantity += (s.pricingQuantity ?? 0);
byName.set(key, prev);
}
}
return Array.from(byName.values()).sort((a, b) => (b.billedCost ?? 0) - (a.billedCost ?? 0));
}
export async function getContract(scope) {
const r = await runVercelJson(scopedArgs(['contract', '--format', 'json'], scope));
return r.ok ? r.data : null;
}
export async function getAccountPlan(scope) {
const currentTeamId = scope ? null : await getCurrentTeamId();
const teamScope = scope || currentTeamId;
if (teamScope && !String(teamScope).startsWith('usr_')) {
const team = await getBillingPlanFromPath(`/v2/teams/${encodeURIComponent(teamScope)}`, 'team.billing.plan');
if (team.plan !== 'unknown' || !/not_found|404/i.test(String(team.error ?? ''))) {
return team;
}
// Older project links can carry a user/org id instead of a team id. If the
// team lookup misses, fall back to the authenticated user's billing record.
}
return await getBillingPlanFromPath('/v2/user', 'user.billing.plan');
}
async function getCurrentTeamId() {
const identity = await getCliIdentity();
return identity?.team?.id ?? null;
}
async function getBillingPlanFromPath(path, source) {
const r = await runVercelJson(['api', path]);
if (!r.ok) {
return {
plan: 'unknown',
reason: `${source} unavailable (${r.code ?? 'unknown'})`,
source,
error: r.code ?? 'unknown',
};
}
const parsed = extractBillingPlan(r.data);
if (!parsed) {
return {
plan: 'unknown',
reason: `${source} missing from Vercel API response`,
source,
};
}
return {
...parsed,
reason: `${source}=${parsed.plan}`,
source,
};
}
export function extractBillingPlan(data) {
const raw =
data?.billing?.plan ??
data?.team?.billing?.plan ??
data?.user?.billing?.plan ??
null;
const plan = normalizeBillingPlan(raw);
return plan ? { plan, rawPlan: raw } : null;
}
function normalizeBillingPlan(raw) {
const value = String(raw ?? '').trim().toLowerCase();
if (value === 'hobby' || value === 'pro' || value === 'enterprise') return value;
return null;
}
// Primary source: billing.plan from `/v2/teams/:team` or `/v2/user`.
// Fallbacks: contract category, then recent billed usage for legacy CLI/API gaps.
export function inferPlan(contract, opts = {}) {
const accountPlan = extractPlanOption(opts?.accountPlan);
if (accountPlan) {
return {
plan: accountPlan.plan,
reason: accountPlan.reason ?? `${accountPlan.source ?? 'billing.plan'}=${accountPlan.plan}`,
};
}
const commits = contract?.commitments ?? [];
if (commits.length > 0) {
const c0 = commits[0] ?? {};
// category field names are tentative — try several.
const category = c0.category ?? c0.commitmentCategory ?? c0.type ?? null;
if (category === 'Spend' || category === 'spend') {
return { plan: 'pro', reason: `commitment category=${category}` };
}
if (category === 'Usage' || category === 'usage') {
return { plan: 'enterprise', reason: `commitment category=${category}` };
}
return { plan: 'uncertain', reason: `unknown commitment category=${category}` };
}
const totalCost = opts?.usageTotalCost;
if (typeof totalCost === 'number' && totalCost > 0) {
return {
plan: 'pro',
reason: `commitments=[] but usage=$${totalCost.toFixed(2)}/window — Pro pay-as-you-go (Hobby teams don't bill)`,
};
}
return {
plan: 'uncertain',
reason: typeof totalCost === 'number' && totalCost === 0
? 'no commitments and no billed usage in window (could be Hobby, or Pro with no recent billing)'
: 'no commitments on contract; usage unavailable',
};
}
function extractPlanOption(accountPlan) {
if (!accountPlan) return null;
if (typeof accountPlan === 'string') {
const plan = normalizeBillingPlan(accountPlan);
return plan ? { plan, reason: `billing.plan=${plan}` } : null;
}
const plan = normalizeBillingPlan(accountPlan.plan);
if (!plan) return null;
return {
plan,
reason: accountPlan.reason ?? (
accountPlan.source
? `${accountPlan.source}=${plan}`
: `billing.plan=${plan}`
),
source: accountPlan.source ?? null,
};
}
export async function detectStack(cwd = process.cwd()) {
const pkgPath = join(cwd, 'package.json');
let pkg = {};
try {
pkg = JSON.parse(await readFile(pkgPath, 'utf-8'));
} catch {
return baselineStack();
}
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
const framework =
deps.next ? 'next' :
deps.nuxt ? 'nuxt' :
deps.astro ? 'astro' :
deps['@sveltejs/kit'] ? 'sveltekit' :
deps['@remix-run/react'] ? 'remix' :
deps.hono ? 'hono' :
'unknown';
const frameworkVersion = (() => {
const m = { next: 'next', nuxt: 'nuxt', astro: 'astro', sveltekit: '@sveltejs/kit', remix: '@remix-run/react', hono: 'hono' };
const dep = m[framework];
if (!dep) return null;
return (deps[dep] || '').replace(/^[\^~]/, '') || null;
})();
const hasAppRouter = await pathExists(join(cwd, 'app')) || await pathExists(join(cwd, 'src/app'));
const hasPagesRouter = await pathExists(join(cwd, 'pages')) || await pathExists(join(cwd, 'src/pages'));
const typescript = await pathExists(join(cwd, 'tsconfig.json'));
const cacheComponents = framework === 'next'
? await detectNextCacheComponents(cwd)
: null;
const orm =
deps.prisma || deps['@prisma/client'] ? 'prisma' :
deps['drizzle-orm'] ? 'drizzle' :
deps.kysely ? 'kysely' :
'none';
const vercelFlagsPackages = [
'@vercel/flags',
'@vercel/flags/next',
'@vercel/flags/sveltekit',
'@vercel/flags/nuxt',
].filter((name) => deps[name]);
const workflowPackages = Object.keys(deps)
.filter((name) => name === 'workflow' || name.startsWith('@workflow/'))
.sort();
const isMonorepo =
!!pkg.workspaces ||
await pathExists(join(cwd, 'pnpm-workspace.yaml')) ||
await pathExists(join(cwd, 'lerna.json'));
return {
framework,
frameworkVersion,
hasAppRouter,
hasPagesRouter,
cacheComponents,
typescript,
orm,
isMonorepo,
rootDirectory: null,
hasVercelFlagsPackage: vercelFlagsPackages.length > 0,
vercelFlagsPackages,
hasWorkflowPackage: workflowPackages.length > 0,
workflowPackages,
};
}
function baselineStack() {
return {
framework: 'unknown', frameworkVersion: null,
hasAppRouter: false, hasPagesRouter: false, cacheComponents: null, typescript: false,
orm: 'none', isMonorepo: false, rootDirectory: null,
hasVercelFlagsPackage: false, vercelFlagsPackages: [],
hasWorkflowPackage: false, workflowPackages: [],
};
}
async function detectNextCacheComponents(cwd) {
for (const name of ['next.config.js', 'next.config.mjs', 'next.config.ts', 'next.config.cjs']) {
try {
const content = await readFile(join(cwd, name), 'utf-8');
if (/\bcacheComponents\s*:\s*true\b/.test(content)) return true;
if (/\bcacheComponents\s*:\s*false\b/.test(content)) return false;
} catch {}
}
return null;
}
async function pathExists(p) {
try { await access(p); return true; } catch { return false; }
}
// `--scope <teamId>` is buggy on several subcommands (silently falls back to
// currentTeam). Resolve raw account IDs to slugs/usernames before scoped calls.
function scopedArgs(args, scope) {
if (!scope) return args;
if (typeof scope === 'string' && /^(team|usr)_/.test(scope)) {
throw new Error('RAW_ID_SCOPE_UNRESOLVED: resolve the linked org/user ID to a CLI scope slug before running Vercel commands.');
}
return [...args, '--scope', scope];
}
// CLI summary field is `<metric_id_with_underscores>_<aggregation>` (e.g. `vercel_request_count_sum`).
export function normalizeSummary(metricResponse, metricId, aggregation, groupBy = []) {
if (!metricResponse || metricResponse.error) return [];
const field = `${metricId.replace(/\./g, '_')}_${aggregation}`;
const rows = Array.isArray(metricResponse.summary) ? metricResponse.summary : [];
return rows.map((row) => {
const out = { value: row[field] ?? null };
for (const dim of groupBy) {
if (row[dim] !== undefined) out[dim] = row[dim];
}
return out;
});
}
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.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download vercel-optimize.zip