Skip to content

feat: enhance environment variable management and refactor API route handling: - #294

Merged
yashdev9274 merged 2 commits into
mainfrom
supercode-cli
Sep 5, 2026
Merged

feat: enhance environment variable management and refactor API route handling:#294
yashdev9274 merged 2 commits into
mainfrom
supercode-cli

Conversation

@yashdev9274

@yashdev9274 yashdev9274 commented Sep 5, 2026

Copy link
Copy Markdown
Owner

Description

  • Added global environment variables to turbo.json for better configuration management.
  • Refactored API route handlers to simplify parameter resolution, improving code readability and maintainability.
  • Updated AI gateway integration to support dual provider functionality, enhancing the review generation process with fallback options.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactor (no functional changes)

How Has This Been Tested?

Please describe the tests that you ran to verify your changes.

  • bun test passes
  • bun run typecheck passes
  • bun run lint passes (if applicable)

Checklist:

  • My code follows the project's style guidelines
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works

Summary by CodeRabbit

  • New Features

    • AI-powered PR reviews can use Vercel AI Gateway or Merge as a fallback provider.
    • Review generation retries across configured models and providers when requests are rate-limited or blocked.
    • Embedding generation supports the selected gateway provider.
  • Documentation

    • Added environment variable guidance for configuring AI Gateway providers and models.
  • Reliability

    • Improved handling of route parameters and build-time environment configuration for more consistent deployments.

…handling:

- Added global environment variables to turbo.json for better configuration management.
- Refactored API route handlers to simplify parameter resolution, improving code readability and maintainability.
- Updated AI gateway integration to support dual provider functionality, enhancing the review generation process with fallback options.
@vercel

vercel Bot commented Sep 5, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
supercli Error Error Sep 5, 2026 1:49pm UTC
supercli-client Ready Ready Preview Sep 5, 2026 1:49pm UTC
supercli-docs Ready Ready Preview Sep 5, 2026 1:49pm UTC
1 Skipped Deployment
Project Deployment Actions Updated
vercel-supercodeai-integration Skipped Skipped Sep 5, 2026 1:49pm UTC

@coderabbitai

coderabbitai Bot commented Sep 5, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

Next included review available in 16 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 2 included reviews currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Team

Run ID: ee39a930-50c5-494a-91b9-852949bf1e0d

📥 Commits

Reviewing files that changed from the base of the PR and between cb23208 and f29b796.

📒 Files selected for processing (4)
  • apps/web/.env.example
  • apps/web/lib/gateway.ts
  • apps/web/modules/ai/lib/generate-pr-review.ts
  • apps/web/package.json

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Team

Run ID: 03d7004c-33d6-455a-a2e0-1f5c4bf94b9a

📥 Commits

Reviewing files that changed from the base of the PR and between dbfe9bb and cb23208.

📒 Files selected for processing (8)
  • apps/marketplace/app/v1/installations/[installationId]/resources/[resourceId]/route.ts
  • apps/marketplace/app/v1/products/[productId]/plans/route.ts
  • apps/marketplace/lib/vercel/auth.ts
  • apps/web/.env.example
  • apps/web/lib/gateway.ts
  • apps/web/modules/ai/lib/generate-pr-review.ts
  • apps/web/modules/pinecone/rag/index.ts
  • turbo.json

Included review availability: Your plan provides up to 2 included reviews per hour; 0 remain after this review.


Walkthrough

The change standardizes promise-based marketplace route parameters, adds Vercel and Merge AI gateway fallback support, updates review and embedding model selection, documents gateway variables, and declares required Turbo build environment variables.

Changes

Marketplace route context

Layer / File(s) Summary
Promise-based route context
apps/marketplace/lib/vercel/auth.ts
withAuth now uses the exported AppRouteHandlerContext type with promise-based parameters.
Handler parameter access
apps/marketplace/app/v1/installations/..., apps/marketplace/app/v1/products/...
Resource and plan handlers await context.params, destructure identifiers, and remove non-null assertions and resolveParams.

AI gateway provider fallback

Layer / File(s) Summary
Provider selection and model helpers
apps/web/.env.example, apps/web/lib/gateway.ts
The gateway supports Vercel and Merge providers, provider selection, chat and embedding helpers, and ordered fallback providers.
PR review generation fallback
apps/web/modules/ai/lib/generate-pr-review.ts
Review generation resolves configured models, retries retryable gateway errors, and aggregates failures across provider and model attempts.
Embedding provider wiring
apps/web/modules/pinecone/rag/index.ts
Embedding generation uses the direct embeddingModel helper.

Build environment configuration

Layer / File(s) Summary
Turbo build environment declarations
turbo.json
The build task and global Turbo configuration declare seven application environment variables.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Merge Risk: ⚪ Minimal · up to cb232

The reviewed environment, route-context, and gateway fallback changes have no identified merge-blocking risk.

Sequence Diagram(s)

sequenceDiagram
  participant runGeneratePrReview
  participant generateReviewText
  participant GatewayProvider
  participant ModelProvider
  runGeneratePrReview->>generateReviewText: submit prompt
  generateReviewText->>GatewayProvider: get ordered providers
  generateReviewText->>ModelProvider: request configured model
  ModelProvider-->>generateReviewText: return text or retryable error
  generateReviewText-->>runGeneratePrReview: return review text or aggregated error
Loading

Poem

A rabbit reads each line,
The patch grows clear beneath the moon,
Small changes hop in place,
Tests guard the garden path,
Reviews bloom before the dawn.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 6 files. (2 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the environment variable updates and API route refactoring. It omits the AI gateway provider fallback changes, but it remains clear and related to major changes in the p…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 6 files. (2 skipped: 2 unsupported.)

✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch supercode-cli

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Sep 5, 2026

Copy link
Copy Markdown

Greptile Summary

The PR updates Marketplace route contexts for promise-based Next.js parameters and introduces provider-aware AI gateway selection with model fallback for reviews and embeddings.

  • Adds Vercel AI Gateway support while retaining Merge as a fallback.
  • Adds configurable review-model ordering and multi-provider retry behavior.
  • Routes Pinecone embedding generation through the selected gateway.
  • Expands documented and Turbo-managed environment configuration.
  • Simplifies Marketplace route parameter resolution.

Confidence Score: 4/5

The PR appears safe to merge, though its fallback loop should be bounded to avoid excessive calls and latency on terminal gateway errors.

Route and provider-selection changes have no established blocking failure, but the new catch logic retries every remaining model/provider combination even when the error is classified as non-retryable.

Files Needing Attention: apps/web/modules/ai/lib/generate-pr-review.ts

Important Files Changed

Filename Overview
apps/web/lib/gateway.ts Adds Vercel and Merge gateway factories, environment-based provider selection, and provider fallback ordering.
apps/web/modules/ai/lib/generate-pr-review.ts Adds configurable provider/model fallback, but non-retryable errors traverse the entire fallback matrix rather than one additional combination.
apps/web/modules/pinecone/rag/index.ts Routes the existing embedding model identifier through the newly selected gateway abstraction.
apps/marketplace/lib/vercel/auth.ts Updates route-handler context typing to the promise-based Next.js parameter contract.
turbo.json Adds shared build and global environment declarations without an established runtime regression.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Generate PR review] --> B[Resolve preferred gateway]
  B --> C[Resolve ordered model list]
  C --> D[Call provider and model]
  D -->|Success| E[Return generated review]
  D -->|Failure and combinations remain| F[Advance to next combination]
  F --> D
  D -->|Final failure| G[Throw gateway error]
  G --> H[Background-job retry or failure handling]
Loading

Reviews (1): Last reviewed commit: "feat: enhance environment variable manag..." | Re-trigger Greptile

Comment on lines +107 to +121
if (!isLast && isRetryableGatewayModelError(error)) {
console.warn(
`[generate-pr-review] ${label} rejected; trying next:`,
message,
)
continue
}

if (!isLast) {
// Non-policy errors: still try next provider/model once (network blips).
console.warn(
`[generate-pr-review] ${label} failed; trying next:`,
message,
)
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Non-retryable errors exhaust fallbacks

The catch logic continues for both retryable and non-retryable failures whenever another combination remains, so an invalid credential, malformed request, or content-policy rejection can trigger every remaining provider/model call. This adds unnecessary latency and potential usage charges, and the enclosing job retries can repeat the entire sequence.

@yashdev9274

Copy link
Copy Markdown
Owner Author

🤖 Supercode AI Review

Summary

This PR modernizes route param handling in the marketplace app by removing an unnecessary resolveParams helper and typing the Next.js App Router params context correctly. It also refactors AI gateway usage in the web app to support a dual-provider setup (Vercel AI Gateway primary, Merge fallback) including ordered model retries, and updates Pinecone embeddings to use the selected gateway provider.

Walkthrough

  • Marketplace route handlers
    • apps/marketplace/app/v1/installations/[installationId]/resources/[resourceId]/route.ts
      • Removed local resolveParams helper and directly awaited context.params, then used resourceId without non-null assertions.
    • apps/marketplace/app/v1/products/[productId]/plans/route.ts
      • Same: removed resolveParams, now const { productId } = await context.params.
    • apps/marketplace/lib/vercel/auth.ts
      • Replaced RouteContext union type with AppRouteHandlerContext where params: Promise<Record<string, string>>, and updated withAuth signature accordingly.
  • Gateway integration (dual-provider + retries)
    • apps/web/lib/gateway.ts
      • Added env-driven provider selection (AI_GATEWAY_PROVIDER, AI_GATEWAY_API_KEY / VERCEL_OIDC_TOKEN) and created:
        • vercelGateway via createGateway (AI SDK native)
        • mergeGateway via createOpenAI URL shim
      • Kept export const gateway = mergeGateway for back-compat, and added:
        • chatModel(modelId, provider?)
        • embeddingModel(modelId, provider?)
        • gatewayProviderChain()
    • apps/web/modules/ai/lib/generate-pr-review.ts
      • Replaced single generateText call with generateReviewText(prompt) that:
        • iterates gatewayProviderChain() and resolveReviewModels() (from REVIEW_MODEL / AI_GATEWAY_MODEL / MERGE_GATEWAY_MODEL + defaults)
        • retries on rate-limit / free-tier blocks / policy-like errors
        • logs fallback usage
    • apps/web/modules/pinecone/rag/index.ts
      • Switched embeddings from gateway.embeddingModel(...) to embeddingModel(...) so embeddings follow the active provider.
  • Config
    • apps/web/.env.example
      • Added AI Gateway env docs for provider/model selection; kept Merge variables.
    • turbo.json
      • Added env for the Next build pipeline and also globalEnv entries for consistent caching/rebuild behavior across tasks.

Changes table

File Summary
apps/marketplace/app/v1/installations/[installationId]/resources/[resourceId]/route.ts Remove resolveParams, use awaited context.params destructuring
apps/marketplace/app/v1/products/[productId]/plans/route.ts Remove resolveParams, use awaited context.params destructuring
apps/marketplace/lib/vercel/auth.ts Update route context typing: params is always a Promise in App Router
apps/web/.env.example Document AI Gateway provider/model env vars and fallback behavior
apps/web/lib/gateway.ts Implement dual-provider gateway, add chatModel, embeddingModel, provider chain
apps/web/modules/ai/lib/generate-pr-review.ts Add ordered provider/model retry loop with retryable error detection
apps/web/modules/pinecone/rag/index.ts Use embeddingModel() instead of merge-only gateway.embeddingModel()
turbo.json Add environment variables to Next build caching via env and globalEnv

Findings

  • high Non-null / missing param validation removed but still assumes required paramsapps/marketplace/app/v1/installations/[installationId]/resources/[resourceId]/route.ts, apps/marketplace/app/v1/products/[productId]/plans/route.ts

    • You removed params.resourceId! / params.productId!, which is good. However, the new code still does const { resourceId } = await context.params and then calls getResource(..., resourceId) without guarding against undefined.
    • Suggested fix:
      • Add a simple guard returning 400 (or 404 depending on intended semantics) if resourceId/productId is missing.
      const { resourceId } = await context.params
      if (!resourceId) return Response.json({ error: "Missing resourceId" }, { status: 400 })
  • medium Over-broad retry classification may mask real failuresapps/web/modules/ai/lib/generate-pr-review.ts

    • isRetryableGatewayModelError() retries on several generic substrings ("rate_limit", "too many requests", and /\b403\b/, /\b429\b/). That can cause extra attempts on errors that won’t succeed with a different model/provider (e.g., auth issues that look like 403).
    • Suggested fix:
      • Narrow 403 handling to “policy/free tier” patterns you already list (e.g., free_tier_*, blocked_by_policy) and avoid retrying on generic 403 unless the message clearly indicates the free-tier restriction.
  • nit Dead/back-compat export may confuse future call sitesapps/web/lib/gateway.ts

    • export const gateway = mergeGateway is explicitly “back-compat”, but the file also adds chatModel / embeddingModel. It’s easy for new code to accidentally keep using gateway.* and accidentally force Merge semantics.
    • Suggested fix:
      • Consider adding a short comment near the gateway export urging usage of chatModel/embeddingModel, or mark it deprecated in JSDoc.

Risk assessment

Medium — AI gateway behavior changes are central to user-visible PR review generation; if model/provider selection or retry classification is off, review generation could fail more often or take longer due to additional retries. Marketplace route typing changes are lower risk but still affect request routing.

Test plan

  • bun run typecheck
  • bun run lint
  • bun test
  • Manual: trigger PR review generation with AI_GATEWAY_API_KEY set and confirm fallback occurs when a configured model is blocked (expect logged fallback messages).
  • Manual: trigger PR review generation with AI_GATEWAY_API_KEY unset (ensure Merge-only path still works).
  • Manual: hit marketplace endpoints:
    • GET /api/v1/installations/:installationId/resources/:resourceId
    • PATCH /api/v1/installations/:installationId/resources/:resourceId
    • GET /api/v1/products/:productId/plans

Suggested PR description

What

  • Refactor marketplace App Router handlers to directly await context.params and update withAuth typing for correct Next.js param semantics.
  • Add dual AI gateway support in the dashboard:
    • Prefer Vercel AI Gateway for PR review generation
    • Fallback to Merge when models are blocked/limited
    • Retry across configured models/providers
  • Make embeddings use the selected gateway provider (not Merge-only).
  • Document new AI gateway env vars and update turbo env handling.

Why

  • Improves correctness/readability of route param resolution in App Router.
  • Reduces failures in PR review generation by automatically trying alternate provider/model configurations when free-tier/policy/rate-limit issues occur.
  • Makes embeddings consistent with the active LLM gateway configuration.

How tested

  • Ran bun test, bun run typecheck, and bun run lint.
  • Manually verified PR review generation using both:
    • Vercel AI Gateway configured (AI_GATEWAY_API_KEY / optional AI_GATEWAY_PROVIDER)
    • Merge fallback when Vercel isn’t configured
  • Manually exercised the updated marketplace route handlers for GET/PATCH/DELETE.

Automated review by Supercode · leave a 👍/👎 reaction to rate this review

…ent:

- Updated .env.example to reflect new AI gateway provider order and added direct API key options for OPENAI, ANTHROPIC, and GOOGLE.
- Added @ai-sdk/anthropic dependency to package.json for improved model support.
- Refactored gateway.ts to support multi-provider routing, including direct API access for enhanced review generation.
- Improved error handling in generate-pr-review.ts to manage provider-specific errors and optimize model selection based on availability.
@vercel
vercel Bot temporarily deployed to Preview – vercel-supercodeai-integration September 5, 2026 13:48 Inactive
@yashdev9274
yashdev9274 merged commit 38cafc4 into main Sep 5, 2026
6 of 10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant