@vvedantb/server 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +43 -0
- package/README.md +12 -4
- package/dist/ai/cost.d.ts +17 -0
- package/dist/ai/cost.js +20 -0
- package/dist/ai/errors.d.ts +35 -0
- package/dist/ai/errors.js +84 -0
- package/dist/ai/index.d.ts +3 -0
- package/dist/ai/index.js +3 -0
- package/dist/ai/serviceTier.d.ts +55 -0
- package/dist/ai/serviceTier.js +29 -0
- package/dist/convex/index.d.ts +1 -1
- package/dist/convex/index.js +1 -1
- package/dist/convex/vPlan.d.ts +1 -3
- package/dist/convex/vPlan.js +2 -4
- package/docs/ai.md +135 -0
- package/docs/convex.md +2 -2
- package/package.json +17 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,48 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.11.0
|
|
4
|
+
|
|
5
|
+
Additive: Vercel AI Gateway helpers on a new subpath, `@vvedantb/server/ai`, taken from three apps' local copies. The root is unchanged and does not re-export them. No new dependency: `ai` (`>=5`) and `@ai-sdk/gateway` (`>=1`) are new optional peers, needed only by the subpath. See `docs/ai.md`.
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Export `./ai` (`dist/ai/index.js`). Works in the Convex default runtime: no Node built-ins, no `"use node"`.
|
|
10
|
+
- `GatewayServiceTier` (`"flex" | "default" | "ultrafast"`), `gatewayServiceTier(tier)` and its alias `gatewayTier`: `{}` for `"default"`, else `{ gateway: { serviceTier: tier } }`.
|
|
11
|
+
- `FLEX_GATEWAY_PROVIDER_OPTIONS` (replaces inline `{ gateway: { serviceTier: "flex" } }` literals) and its alias `FLEX_PROVIDER_OPTIONS`, frozen.
|
|
12
|
+
- `withFlexGatewayOptions(extra?)`: flex with the caller's provider options on top. Unlike the local `buildChatProviderOptions` it replaces, a caller `gateway` key is merged over flex instead of replacing it.
|
|
13
|
+
- `readGatewayCost(metadata)`: `gateway.cost`, else `gateway.marketCost`, as a number or numeric string. Takes a structural type that the SDK's `ProviderMetadata` fits; no SDK import.
|
|
14
|
+
- `classifyGatewayError(error)`, `errorMessageOf(error)`, `GatewayErrorKind` and `GatewayFailure` (from a local `gatewayErrors.ts`). Changes from that copy:
|
|
15
|
+
- New kind `quota`: status 402, a billing message, or "quota" on a Gateway error that is not a rate limit. Not retryable. A rate-limit error that only says "quota" stays `rate_limit`.
|
|
16
|
+
- `auth` also matches the error that `generateText` and the other `ai` calls put in place of `GatewayAuthenticationError` (a plain `Error` named `GatewayAuthenticationError`, or in production an `AISDKError` named `GatewayError`). The local copy returned `other` for both.
|
|
17
|
+
- The Gateway's `GatewayTimeoutError` is `timeout` (retryable), not `gateway`.
|
|
18
|
+
- `statusCode` is set for every Gateway error; `message` has ANSI colour codes removed.
|
|
19
|
+
- Types `GatewayServiceTierOptions`, `GatewayProviderOptions`, `GatewayJsonObject`, `GatewayJsonValue`, `GatewayCostMetadata`.
|
|
20
|
+
- `docs/ai.md`, with which app files can be deleted once each app adopts it.
|
|
21
|
+
|
|
22
|
+
### Tests
|
|
23
|
+
|
|
24
|
+
- `tests/ai/`: tier builder, flex merge, cost parsing, every classifier branch with real SDK error instances, marker matching for a foreign copy, and errors built by `generateText` through `createGateway` with a fake `fetch` (429, 402, 401, 404, 400, 503). Types are checked against the SDK's `providerOptions` and `ProviderMetadata`.
|
|
25
|
+
- `tests-node/esm-exports.mjs`: the exports map has `./ai`; the root has no AI exports; `./ai` fails with a missing package when the peers are absent and runs when they are installed; the published `./ai` types check alone and fit the SDK.
|
|
26
|
+
- `tests-node/bundle.mjs`: a Convex V8 bundle of an action that uses `./ai` has no Node built-in with the SDK external, and imports no Node built-in with the SDK bundled. The SDK itself carries guarded `process.getBuiltinModule("node:…")` calls; the test allows those and nothing else.
|
|
27
|
+
- `ai` and `@ai-sdk/gateway` are dev dependencies.
|
|
28
|
+
|
|
29
|
+
## 0.10.0
|
|
30
|
+
|
|
31
|
+
Retires the per-app `vibot_pro` plan. Only the shared `v_pro` plan counts as V Pro. No new dependency.
|
|
32
|
+
|
|
33
|
+
### Removed
|
|
34
|
+
|
|
35
|
+
- `V_PRO_LEGACY_PLAN_KEY` (`"vibot_pro"`). Breaking for any consumer that imports it.
|
|
36
|
+
|
|
37
|
+
### Changed
|
|
38
|
+
|
|
39
|
+
- `V_PRO_PLAN_KEYS` is now `["v_pro"]`. The export stays.
|
|
40
|
+
- `hasVPlan` no longer treats `vibot_pro` (`u:vibot_pro`, `o:vibot_pro` or bare) as V Pro; it returns `false`.
|
|
41
|
+
|
|
42
|
+
### Tests
|
|
43
|
+
|
|
44
|
+
- `tests/convex/vPlan.test.ts` and `tests-node/esm-exports.mjs` check that `vibot_pro` no longer counts.
|
|
45
|
+
|
|
3
46
|
## 0.9.0
|
|
4
47
|
|
|
5
48
|
Shared "V Pro" plan check for every Project V app. Additive; no new dependency.
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @vvedantb/server
|
|
2
2
|
|
|
3
|
-
Server-side helpers for Convex backends, Convex optimistic updates, Node-side MCP OAuth client helpers, a QuickJS code sandbox and an artifacts core, from one root import.
|
|
3
|
+
Server-side helpers for Convex backends, Convex optimistic updates, Node-side MCP OAuth client helpers, a QuickJS code sandbox and an artifacts core, from one root import. Vercel AI Gateway helpers are on the `@vvedantb/server/ai` subpath.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
6
|
npm install @vvedantb/server
|
|
@@ -10,7 +10,11 @@ npm install @vvedantb/server
|
|
|
10
10
|
import { createMcpHttpHandler, extractBearerToken, registerMcpRoutes, sha256Hex } from "@vvedantb/server";
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
```ts
|
|
14
|
+
import { classifyGatewayError, FLEX_GATEWAY_PROVIDER_OPTIONS, readGatewayCost } from "@vvedantb/server/ai";
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The one subpath export is `./ai` (0.11.0). The root does not re-export it, so a root import never loads the AI SDK. 0.2.0 removed `/convex` and `/mcp`; see [CHANGELOG.md](CHANGELOG.md).
|
|
14
18
|
|
|
15
19
|
| Area | What it holds | Docs |
|
|
16
20
|
| --- | --- | --- |
|
|
@@ -20,6 +24,7 @@ There are no subpath exports (0.2.0 removed `/convex` and `/mcp`; see [CHANGELOG
|
|
|
20
24
|
| Optimistic updates | `mapLoadedQuery` (also `forEachLoadedQuery`, `updateAllCachedQueries`), `patchLoadedQuery`, `tempId`, `createMemoryOptimisticStore`. Client-side, no React. | [docs/convex.md](docs/convex.md#optimistic-updates-client-side) |
|
|
21
25
|
| MCP OAuth client | Node only (Electron main): OAuth provider over injected storage, sign-in, refresh, revocation, loopback redirect server. Node built-ins and the MCP SDK load on first use, so Convex V8 bundles of the root stay clean. | [docs/mcp-oauth-client.md](docs/mcp-oauth-client.md) |
|
|
22
26
|
| Artifacts core | Pure, no DOM: Zod contract for artifact rows and typed bodies (`createArtifactSchemas`, `validateArtifactBody`), state limits and ops, the host's save debounce, built-in quiz and flashcards pages, and `wrapArtifactDocument` (CSP plus a guest state bridge with host-given global aliases). | [docs/artifacts.md](docs/artifacts.md) |
|
|
27
|
+
| AI Gateway (`@vvedantb/server/ai`) | Service tier provider options (`gatewayServiceTier`, `FLEX_GATEWAY_PROVIDER_OPTIONS`, `withFlexGatewayOptions`), `readGatewayCost` from provider metadata, and `classifyGatewayError` (AI SDK and Gateway errors to `invalid_request`, `auth`, `model_not_found`, `rate_limit`, `quota`, `gateway`, `malformed_response`, `timeout` or `other`). Convex default runtime safe. | [docs/ai.md](docs/ai.md) |
|
|
23
28
|
| Code sandbox | Node only: `runSandboxedScript` runs untrusted JavaScript in QuickJS (WASM) with a `tools` proxy to host handlers, time, heap, stack, call and log limits, injected `globals`, and an `onCall` hook for allow-lists and dry runs. QuickJS loads on first call. | [docs/sandbox.md](docs/sandbox.md) |
|
|
24
29
|
|
|
25
30
|
Migration steps per app: [docs/migration.md](docs/migration.md).
|
|
@@ -28,6 +33,7 @@ Migration steps per app: [docs/migration.md](docs/migration.md).
|
|
|
28
33
|
|
|
29
34
|
All are optional. None is imported when the root loads.
|
|
30
35
|
|
|
36
|
+
- `ai` `>=5` and `@ai-sdk/gateway` `>=1`: only for `@vvedantb/server/ai`, which imports their error classes statically, so that subpath needs both installed. The root never imports them.
|
|
31
37
|
- `@clerk/backend` `>=1`: only for `getClerkClient` and `verifyClerkAccessToken`, which take its client or factory as an argument.
|
|
32
38
|
- `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`, or your `z` to `createMcpOAuthStateSchema` or `createArtifactSchemas`.
|
|
33
39
|
- `convex` `^1.24.0`: types only, for the optimistic-update helpers. The package never imports `convex` at runtime: `registerMcpRoutes` and `createClerkUserAuth` type the router and ctx structurally, and `createMemoryOptimisticStore` carries its own copy of `getFunctionName` (`convex` is a dev dependency, used to check that real Convex types fit).
|
|
@@ -39,13 +45,15 @@ No React, no web dependencies. `"sideEffects": false`. Compiled ESM with types i
|
|
|
39
45
|
## Layout
|
|
40
46
|
|
|
41
47
|
```
|
|
42
|
-
src/index.ts the
|
|
48
|
+
src/index.ts the root export: re-exports the six folders below (not ai/)
|
|
49
|
+
src/ai/ the ./ai subpath: AI Gateway tier, cost and error helpers (static ai and @ai-sdk/gateway imports)
|
|
43
50
|
src/convex/ Convex helpers and optimistic updates
|
|
44
51
|
src/mcp/ MCP scaffolding (imports ../convex by relative path)
|
|
45
52
|
src/mcp-oauth-client/ MCP OAuth client helpers (Node only; lazy node:http and SDK imports)
|
|
46
53
|
src/crypto/ WebCrypto primitives
|
|
47
54
|
src/sandbox/ QuickJS code sandbox (Node only; lazy QuickJS import)
|
|
48
55
|
src/artifacts/ artifacts core (pure strings and data; runs anywhere)
|
|
56
|
+
tests/ai/ vitest, including errors built by generateText through the Gateway provider with a fake fetch
|
|
49
57
|
tests/convex/ vitest
|
|
50
58
|
tests/mcp/ vitest, with fixtures/ (SDK captures, app references)
|
|
51
59
|
tests/mcp-oauth-client/ vitest, against fake MCP and authorization servers
|
|
@@ -54,7 +62,7 @@ tests/sandbox/ vitest, against real QuickJS
|
|
|
54
62
|
tests/artifacts/ vitest, including the guest bootstrap in a VM realm and a no-app-name check
|
|
55
63
|
tests-node/ plain Node checks of the built package: exports map and peers (esm-exports.mjs),
|
|
56
64
|
Convex V8 and Node/Electron bundles with esbuild (bundle.mjs)
|
|
57
|
-
docs/ convex.md, mcp.md, mcp-oauth-client.md, crypto.md, sandbox.md, artifacts.md, migration.md, migrated/<app>/
|
|
65
|
+
docs/ ai.md, convex.md, mcp.md, mcp-oauth-client.md, crypto.md, sandbox.md, artifacts.md, migration.md, migrated/<app>/
|
|
58
66
|
scripts/ capture-sdk-fixtures.mjs
|
|
59
67
|
```
|
|
60
68
|
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The part of AI SDK `providerMetadata` that `readGatewayCost` reads. The SDK's `ProviderMetadata` is
|
|
3
|
+
* assignable to it; no AI SDK import is needed at runtime.
|
|
4
|
+
*/
|
|
5
|
+
export type GatewayCostMetadata = {
|
|
6
|
+
readonly gateway?: {
|
|
7
|
+
readonly cost?: unknown;
|
|
8
|
+
readonly marketCost?: unknown;
|
|
9
|
+
readonly [key: string]: unknown;
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* AI Gateway cost in USD from a result's `providerMetadata`: `gateway.cost` (what was billed), else
|
|
14
|
+
* `gateway.marketCost` (list price), so budget guards still see a value. Each may be a number or a numeric
|
|
15
|
+
* string. Returns `undefined` when neither is a finite number.
|
|
16
|
+
*/
|
|
17
|
+
export declare function readGatewayCost(metadata: GatewayCostMetadata | null | undefined): number | undefined;
|
package/dist/ai/cost.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Gateway cost in USD from a result's `providerMetadata`: `gateway.cost` (what was billed), else
|
|
3
|
+
* `gateway.marketCost` (list price), so budget guards still see a value. Each may be a number or a numeric
|
|
4
|
+
* string. Returns `undefined` when neither is a finite number.
|
|
5
|
+
*/
|
|
6
|
+
export function readGatewayCost(metadata) {
|
|
7
|
+
const gateway = metadata?.gateway;
|
|
8
|
+
if (typeof gateway !== "object" || gateway === null)
|
|
9
|
+
return undefined;
|
|
10
|
+
const { cost, marketCost } = gateway;
|
|
11
|
+
return parseCost(cost) ?? parseCost(marketCost);
|
|
12
|
+
}
|
|
13
|
+
function parseCost(cost) {
|
|
14
|
+
if (typeof cost === "number")
|
|
15
|
+
return Number.isFinite(cost) ? cost : undefined;
|
|
16
|
+
if (typeof cost !== "string" || cost.trim().length === 0)
|
|
17
|
+
return undefined;
|
|
18
|
+
const parsed = Number(cost);
|
|
19
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
20
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What went wrong with an AI SDK / AI Gateway call, in terms a caller can act on.
|
|
3
|
+
*
|
|
4
|
+
* - `invalid_request`: bad arguments or a request the Gateway rejected. Not retryable.
|
|
5
|
+
* - `auth`: missing or invalid Gateway key or OIDC token. Not retryable.
|
|
6
|
+
* - `model_not_found`: unknown model ID. Not retryable.
|
|
7
|
+
* - `rate_limit`: too many requests. Retryable after a wait.
|
|
8
|
+
* - `quota`: out of credits, spend limit or quota reached: HTTP 402, a billing message, or "quota" on a Gateway
|
|
9
|
+
* error other than a rate limit. Not retryable until someone tops up or the period resets.
|
|
10
|
+
* - `gateway`: any other Gateway error. `retryable` is the SDK's `isRetryable`.
|
|
11
|
+
* - `malformed_response`: the response did not match what the SDK expected. Retryable.
|
|
12
|
+
* - `timeout`: the call timed out or was aborted. Retryable.
|
|
13
|
+
* - `other`: anything else. Not retryable.
|
|
14
|
+
*/
|
|
15
|
+
export type GatewayErrorKind = "invalid_request" | "auth" | "model_not_found" | "rate_limit" | "quota" | "gateway" | "malformed_response" | "timeout" | "other";
|
|
16
|
+
export type GatewayFailure = {
|
|
17
|
+
kind: GatewayErrorKind;
|
|
18
|
+
/** The error's own message, without ANSI colour codes. Never the request body; the SDK does not put the key in it. */
|
|
19
|
+
message: string;
|
|
20
|
+
retryable: boolean;
|
|
21
|
+
/** HTTP status, set for every Gateway error (the SDK defaults it to 500 when the response had none). */
|
|
22
|
+
statusCode?: number;
|
|
23
|
+
};
|
|
24
|
+
/** `error.message` for an `Error`, the string itself for a string, else `"Unknown error"`. */
|
|
25
|
+
export declare function errorMessageOf(error: unknown): string;
|
|
26
|
+
/**
|
|
27
|
+
* Maps an AI SDK / AI Gateway failure to a `GatewayFailure`. A `RetryError` is unwrapped to its `lastError`.
|
|
28
|
+
* Checks use the SDK's `isInstance`, which matches by marker, so errors from another copy of `ai` or
|
|
29
|
+
* `@ai-sdk/gateway` in the bundle are still recognised; the auth error that `ai` rewraps is matched by name.
|
|
30
|
+
* The message has ANSI colour codes and outer whitespace removed. Never throws.
|
|
31
|
+
*
|
|
32
|
+
* Order matters: invalid request, auth and model-not-found win over quota; quota wins over rate limit; a Gateway
|
|
33
|
+
* timeout is `timeout`, not `gateway`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function classifyGatewayError(error: unknown): GatewayFailure;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { InvalidArgumentError, InvalidResponseDataError, NoSuchModelError, RetryError } from "ai";
|
|
2
|
+
import { GatewayAuthenticationError, GatewayError, GatewayInvalidRequestError, GatewayModelNotFoundError, GatewayRateLimitError, } from "@ai-sdk/gateway";
|
|
3
|
+
/** `error.message` for an `Error`, the string itself for a string, else `"Unknown error"`. */
|
|
4
|
+
export function errorMessageOf(error) {
|
|
5
|
+
if (error instanceof Error)
|
|
6
|
+
return error.message;
|
|
7
|
+
if (typeof error === "string")
|
|
8
|
+
return error;
|
|
9
|
+
return "Unknown error";
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The Gateway has no quota error type: an out-of-credits or spend-limit reply arrives as a rate-limit or
|
|
13
|
+
* generic Gateway error, so the status (402) or the message is all there is to go on.
|
|
14
|
+
*
|
|
15
|
+
* Billing words (credits, funds, billing, payment, spend limit, budget) mean quota on any Gateway error. The bare
|
|
16
|
+
* word "quota" is ambiguous on a rate-limit error ("requests per minute quota"), so there it stays `rate_limit`;
|
|
17
|
+
* on any other Gateway error (for example a 403) it means quota.
|
|
18
|
+
*/
|
|
19
|
+
const BILLING_MESSAGE = /\b(?:insufficient[ _-]?(?:funds|credits?|balance)|out of credits?|credits? (?:exhausted|limit|balance)|billing|payment required|spend(?:ing)? limit|budget (?:exceeded|limit))\b/i;
|
|
20
|
+
const QUOTA_MESSAGE = /\bquota\b/i;
|
|
21
|
+
function isQuotaError(error, message) {
|
|
22
|
+
if (error.statusCode === 402 || BILLING_MESSAGE.test(message))
|
|
23
|
+
return true;
|
|
24
|
+
return !GatewayRateLimitError.isInstance(error) && QUOTA_MESSAGE.test(message);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* `generateText`, `streamText` and the other `ai` calls replace a `GatewayAuthenticationError` before it reaches
|
|
28
|
+
* the caller (`wrapGatewayError` in `ai` 5 to 7): outside production with a plain `Error` named
|
|
29
|
+
* `GatewayAuthenticationError`, and in production (`NODE_ENV=production`) with an `AISDKError` named
|
|
30
|
+
* `GatewayError` whose message starts "Unauthenticated". Neither has the Gateway markers, so match them by name.
|
|
31
|
+
*/
|
|
32
|
+
function isWrappedAuthError(error) {
|
|
33
|
+
if (!(error instanceof Error))
|
|
34
|
+
return false;
|
|
35
|
+
return (error.name === "GatewayAuthenticationError" ||
|
|
36
|
+
(error.name === "GatewayError" && !GatewayError.isInstance(error) && /^Unauthenticated\b/.test(error.message)));
|
|
37
|
+
}
|
|
38
|
+
// ANSI colour codes, which the non-production wrapped auth error puts in its message.
|
|
39
|
+
const ANSI = /\u001b\[[0-9;]*m/g;
|
|
40
|
+
/**
|
|
41
|
+
* Maps an AI SDK / AI Gateway failure to a `GatewayFailure`. A `RetryError` is unwrapped to its `lastError`.
|
|
42
|
+
* Checks use the SDK's `isInstance`, which matches by marker, so errors from another copy of `ai` or
|
|
43
|
+
* `@ai-sdk/gateway` in the bundle are still recognised; the auth error that `ai` rewraps is matched by name.
|
|
44
|
+
* The message has ANSI colour codes and outer whitespace removed. Never throws.
|
|
45
|
+
*
|
|
46
|
+
* Order matters: invalid request, auth and model-not-found win over quota; quota wins over rate limit; a Gateway
|
|
47
|
+
* timeout is `timeout`, not `gateway`.
|
|
48
|
+
*/
|
|
49
|
+
export function classifyGatewayError(error) {
|
|
50
|
+
if (RetryError.isInstance(error)) {
|
|
51
|
+
return classifyGatewayError(error.lastError);
|
|
52
|
+
}
|
|
53
|
+
const message = errorMessageOf(error).replace(ANSI, "").trim();
|
|
54
|
+
const statusCode = GatewayError.isInstance(error) ? { statusCode: error.statusCode } : {};
|
|
55
|
+
if (InvalidArgumentError.isInstance(error) || GatewayInvalidRequestError.isInstance(error)) {
|
|
56
|
+
return { kind: "invalid_request", message, retryable: false, ...statusCode };
|
|
57
|
+
}
|
|
58
|
+
if (GatewayAuthenticationError.isInstance(error) || isWrappedAuthError(error)) {
|
|
59
|
+
return { kind: "auth", message, retryable: false, ...statusCode };
|
|
60
|
+
}
|
|
61
|
+
if (NoSuchModelError.isInstance(error) || GatewayModelNotFoundError.isInstance(error)) {
|
|
62
|
+
return { kind: "model_not_found", message, retryable: false, ...statusCode };
|
|
63
|
+
}
|
|
64
|
+
if (GatewayError.isInstance(error) && isQuotaError(error, message)) {
|
|
65
|
+
return { kind: "quota", message, retryable: false, ...statusCode };
|
|
66
|
+
}
|
|
67
|
+
if (GatewayRateLimitError.isInstance(error)) {
|
|
68
|
+
return { kind: "rate_limit", message, retryable: true, ...statusCode };
|
|
69
|
+
}
|
|
70
|
+
if (GatewayError.isInstance(error)) {
|
|
71
|
+
// GatewayTimeoutError is not exported by @ai-sdk/gateway, so match it by name.
|
|
72
|
+
if (error.name === "GatewayTimeoutError") {
|
|
73
|
+
return { kind: "timeout", message, retryable: true, ...statusCode };
|
|
74
|
+
}
|
|
75
|
+
return { kind: "gateway", message, retryable: error.isRetryable, ...statusCode };
|
|
76
|
+
}
|
|
77
|
+
if (InvalidResponseDataError.isInstance(error)) {
|
|
78
|
+
return { kind: "malformed_response", message, retryable: true };
|
|
79
|
+
}
|
|
80
|
+
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
|
|
81
|
+
return { kind: "timeout", message, retryable: true };
|
|
82
|
+
}
|
|
83
|
+
return { kind: "other", message, retryable: false };
|
|
84
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { readGatewayCost, type GatewayCostMetadata } from "./cost.js";
|
|
2
|
+
export { classifyGatewayError, errorMessageOf, type GatewayErrorKind, type GatewayFailure, } from "./errors.js";
|
|
3
|
+
export { FLEX_GATEWAY_PROVIDER_OPTIONS, FLEX_PROVIDER_OPTIONS, gatewayServiceTier, gatewayTier, withFlexGatewayOptions, type GatewayJsonObject, type GatewayJsonValue, type GatewayProviderOptions, type GatewayServiceTier, type GatewayServiceTierOptions, } from "./serviceTier.js";
|
package/dist/ai/index.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Gateway service tier provider options. Pure data: no AI SDK import, so
|
|
3
|
+
* these run anywhere (Convex default runtime, Node, browsers).
|
|
4
|
+
*/
|
|
5
|
+
/** A JSON value the AI SDK accepts in `providerOptions` (mirrors `JSONValue` from `@ai-sdk/provider`). */
|
|
6
|
+
export type GatewayJsonValue = null | string | number | boolean | Readonly<GatewayJsonObject> | readonly GatewayJsonValue[];
|
|
7
|
+
/** A JSON object the AI SDK accepts in `providerOptions` (mirrors `JSONObject` from `@ai-sdk/provider`). */
|
|
8
|
+
export type GatewayJsonObject = {
|
|
9
|
+
[key: string]: GatewayJsonValue | undefined;
|
|
10
|
+
};
|
|
11
|
+
/** Per-provider options for an AI SDK call (`providerOptions`). Assignable to the SDK's `ProviderOptions`. */
|
|
12
|
+
export type GatewayProviderOptions = Record<string, GatewayJsonObject>;
|
|
13
|
+
/**
|
|
14
|
+
* AI Gateway service tier, chosen per call.
|
|
15
|
+
*
|
|
16
|
+
* - `"flex"`: cheaper, may queue and be slower. For background work.
|
|
17
|
+
* - `"default"`: the Gateway's standard tier. No `serviceTier` is sent.
|
|
18
|
+
* - `"ultrafast"`: sent as is. Not confirmed for every model; the Gateway may reject it. Read
|
|
19
|
+
* `providerMetadata.gateway.serviceTier` to see what the Gateway applied.
|
|
20
|
+
*
|
|
21
|
+
* A tier the provider or model does not support is a no-op on the Gateway side.
|
|
22
|
+
*/
|
|
23
|
+
export type GatewayServiceTier = "flex" | "default" | "ultrafast";
|
|
24
|
+
/** The provider options `gatewayServiceTier` returns: empty for `"default"`. */
|
|
25
|
+
export type GatewayServiceTierOptions = {
|
|
26
|
+
gateway?: {
|
|
27
|
+
serviceTier: Exclude<GatewayServiceTier, "default">;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Provider options for a service tier: `{}` for `"default"`, else `{ gateway: { serviceTier: tier } }`.
|
|
32
|
+
* Returns a new object on every call.
|
|
33
|
+
*/
|
|
34
|
+
export declare function gatewayServiceTier(tier: GatewayServiceTier): GatewayServiceTierOptions;
|
|
35
|
+
/** Alias of `gatewayServiceTier`. */
|
|
36
|
+
export declare const gatewayTier: typeof gatewayServiceTier;
|
|
37
|
+
/** `{ gateway: { serviceTier: "flex" } }`, frozen. Spread it into `providerOptions`; do not mutate it. */
|
|
38
|
+
export declare const FLEX_GATEWAY_PROVIDER_OPTIONS: {
|
|
39
|
+
readonly gateway: {
|
|
40
|
+
readonly serviceTier: "flex";
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
/** Alias of `FLEX_GATEWAY_PROVIDER_OPTIONS`. */
|
|
44
|
+
export declare const FLEX_PROVIDER_OPTIONS: {
|
|
45
|
+
readonly gateway: {
|
|
46
|
+
readonly serviceTier: "flex";
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Flex tier plus the caller's provider options, as a new object. Caller options win: other providers' keys
|
|
51
|
+
* (for example `{ alibaba: { enableThinking: false } }`) are added as is, and caller `gateway` keys are merged
|
|
52
|
+
* over `{ serviceTier: "flex" }`, so `{ gateway: { order: ["anthropic"] } }` keeps flex and a caller
|
|
53
|
+
* `serviceTier` replaces it. Neither argument is mutated.
|
|
54
|
+
*/
|
|
55
|
+
export declare function withFlexGatewayOptions(extra?: GatewayProviderOptions): GatewayProviderOptions;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Gateway service tier provider options. Pure data: no AI SDK import, so
|
|
3
|
+
* these run anywhere (Convex default runtime, Node, browsers).
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Provider options for a service tier: `{}` for `"default"`, else `{ gateway: { serviceTier: tier } }`.
|
|
7
|
+
* Returns a new object on every call.
|
|
8
|
+
*/
|
|
9
|
+
export function gatewayServiceTier(tier) {
|
|
10
|
+
return tier === "default" ? {} : { gateway: { serviceTier: tier } };
|
|
11
|
+
}
|
|
12
|
+
/** Alias of `gatewayServiceTier`. */
|
|
13
|
+
export const gatewayTier = gatewayServiceTier;
|
|
14
|
+
/** `{ gateway: { serviceTier: "flex" } }`, frozen. Spread it into `providerOptions`; do not mutate it. */
|
|
15
|
+
export const FLEX_GATEWAY_PROVIDER_OPTIONS = Object.freeze({ gateway: Object.freeze({ serviceTier: "flex" }) });
|
|
16
|
+
/** Alias of `FLEX_GATEWAY_PROVIDER_OPTIONS`. */
|
|
17
|
+
export const FLEX_PROVIDER_OPTIONS = FLEX_GATEWAY_PROVIDER_OPTIONS;
|
|
18
|
+
/**
|
|
19
|
+
* Flex tier plus the caller's provider options, as a new object. Caller options win: other providers' keys
|
|
20
|
+
* (for example `{ alibaba: { enableThinking: false } }`) are added as is, and caller `gateway` keys are merged
|
|
21
|
+
* over `{ serviceTier: "flex" }`, so `{ gateway: { order: ["anthropic"] } }` keeps flex and a caller
|
|
22
|
+
* `serviceTier` replaces it. Neither argument is mutated.
|
|
23
|
+
*/
|
|
24
|
+
export function withFlexGatewayOptions(extra) {
|
|
25
|
+
return {
|
|
26
|
+
...extra,
|
|
27
|
+
gateway: { ...FLEX_GATEWAY_PROVIDER_OPTIONS.gateway, ...extra?.gateway },
|
|
28
|
+
};
|
|
29
|
+
}
|
package/dist/convex/index.d.ts
CHANGED
|
@@ -15,4 +15,4 @@ export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
|
|
|
15
15
|
export { tempId, type TempIdFormat, type TempIdOptions } from "./tempId.js";
|
|
16
16
|
export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, type ClerkLike, type ClerkRequestStateLike, type ClerkTokenType, type ClerkVerifyRejection, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions, } from "./verifyClerkAccessToken.js";
|
|
17
17
|
export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, type AuthenticateClerkBearerOptions, type ClerkOAuthJwtRejection, type VerifiedClerkOAuthJwt, type VerifyClerkOAuthJwtOptions, } from "./verifyClerkOAuthJwt.js";
|
|
18
|
-
export { hasVPlan, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS,
|
|
18
|
+
export { hasVPlan, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, } from "./vPlan.js";
|
package/dist/convex/index.js
CHANGED
|
@@ -15,4 +15,4 @@ export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
|
|
|
15
15
|
export { tempId } from "./tempId.js";
|
|
16
16
|
export { consoleClerkVerifyLogger, verifyClerkAccessToken, } from "./verifyClerkAccessToken.js";
|
|
17
17
|
export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, } from "./verifyClerkOAuthJwt.js";
|
|
18
|
-
export { hasVPlan, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS,
|
|
18
|
+
export { hasVPlan, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, } from "./vPlan.js";
|
package/dist/convex/vPlan.d.ts
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
/** Clerk Billing plan key for the shared V Pro plan ($10/month or $100/year). */
|
|
2
2
|
export declare const V_PRO_PLAN_KEY = "v_pro";
|
|
3
|
-
/** The earlier single-app plan. It still counts as V Pro. */
|
|
4
|
-
export declare const V_PRO_LEGACY_PLAN_KEY = "vibot_pro";
|
|
5
3
|
/** Plan keys that grant V Pro. */
|
|
6
4
|
export declare const V_PRO_PLAN_KEYS: readonly string[];
|
|
7
5
|
/**
|
|
8
|
-
* True when the session's active plan is V Pro (`v_pro`
|
|
6
|
+
* True when the session's active plan is V Pro (`v_pro`).
|
|
9
7
|
* Reads the Clerk session token v2 `pla` claim, `u:<plan>` or `o:<plan>`, from a
|
|
10
8
|
* Convex `ctx.auth.getUserIdentity()` result or raw JWT claims. A bare plan slug
|
|
11
9
|
* also matches. Anything else, including `null`, returns `false`; it never throws.
|
package/dist/convex/vPlan.js
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
/** Clerk Billing plan key for the shared V Pro plan ($10/month or $100/year). */
|
|
2
2
|
export const V_PRO_PLAN_KEY = "v_pro";
|
|
3
|
-
/** The earlier single-app plan. It still counts as V Pro. */
|
|
4
|
-
export const V_PRO_LEGACY_PLAN_KEY = "vibot_pro";
|
|
5
3
|
/** Plan keys that grant V Pro. */
|
|
6
|
-
export const V_PRO_PLAN_KEYS = [V_PRO_PLAN_KEY
|
|
4
|
+
export const V_PRO_PLAN_KEYS = [V_PRO_PLAN_KEY];
|
|
7
5
|
/**
|
|
8
|
-
* True when the session's active plan is V Pro (`v_pro`
|
|
6
|
+
* True when the session's active plan is V Pro (`v_pro`).
|
|
9
7
|
* Reads the Clerk session token v2 `pla` claim, `u:<plan>` or `o:<plan>`, from a
|
|
10
8
|
* Convex `ctx.auth.getUserIdentity()` result or raw JWT claims. A bare plan slug
|
|
11
9
|
* also matches. Anything else, including `null`, returns `false`; it never throws.
|
package/docs/ai.md
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# AI Gateway helpers (`@vvedantb/server/ai`)
|
|
2
|
+
|
|
3
|
+
Small helpers for apps that call models through the [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) with the AI SDK: service tier provider options, the Gateway cost from provider metadata, and one mapping from SDK and Gateway errors to something a caller can act on.
|
|
4
|
+
|
|
5
|
+
They are on their own subpath, not the root:
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import {
|
|
9
|
+
classifyGatewayError,
|
|
10
|
+
FLEX_GATEWAY_PROVIDER_OPTIONS,
|
|
11
|
+
gatewayServiceTier,
|
|
12
|
+
readGatewayCost,
|
|
13
|
+
withFlexGatewayOptions,
|
|
14
|
+
} from "@vvedantb/server/ai";
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The root (`@vvedantb/server`) does not re-export them, so a root import never loads the AI SDK.
|
|
18
|
+
|
|
19
|
+
## Runtime and peers
|
|
20
|
+
|
|
21
|
+
- Works in the Convex default runtime (no `"use node"`), Node and browsers. No Node built-ins. `tests-node/bundle.mjs` bundles a Convex action that uses it the way `convex deploy` does.
|
|
22
|
+
- `ai` (`>=5`) and `@ai-sdk/gateway` (`>=1`) are optional peers, but `classifyGatewayError` imports their error classes statically, so importing `@vvedantb/server/ai` needs both installed. Any app that calls the Gateway through the AI SDK already has them.
|
|
23
|
+
- The service tier and cost helpers import nothing from the SDK. Their types are structural and fit the SDK's `providerOptions` and `ProviderMetadata`.
|
|
24
|
+
- No model IDs, prompts or `generateText` wrappers. Those stay in each app.
|
|
25
|
+
|
|
26
|
+
## Service tier
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
const { text } = await generateText({
|
|
30
|
+
model: TITLE_MODEL, // the app's own constant
|
|
31
|
+
prompt,
|
|
32
|
+
providerOptions: FLEX_GATEWAY_PROVIDER_OPTIONS,
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
// Per-call tier
|
|
36
|
+
providerOptions: gatewayServiceTier(background ? "flex" : "default");
|
|
37
|
+
|
|
38
|
+
// Flex plus other options
|
|
39
|
+
providerOptions: withFlexGatewayOptions({ alibaba: { enableThinking: false } });
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
| Export | What it does |
|
|
43
|
+
| --- | --- |
|
|
44
|
+
| `GatewayServiceTier` | `"flex" \| "default" \| "ultrafast"`. |
|
|
45
|
+
| `gatewayServiceTier(tier)` | `{}` for `"default"` (no `serviceTier` sent), else `{ gateway: { serviceTier: tier } }`. A new object each call. Alias: `gatewayTier`. |
|
|
46
|
+
| `FLEX_GATEWAY_PROVIDER_OPTIONS` | `{ gateway: { serviceTier: "flex" } }`, frozen. Alias: `FLEX_PROVIDER_OPTIONS`. |
|
|
47
|
+
| `withFlexGatewayOptions(extra?)` | A new object: flex, with the caller's options on top. Other providers' keys are added as they are. Caller `gateway` keys are merged over `{ serviceTier: "flex" }`, so `{ gateway: { order: [...] } }` keeps flex, and a caller `serviceTier` replaces it. Nothing is mutated. |
|
|
48
|
+
| `GatewayProviderOptions`, `GatewayJsonObject`, `GatewayJsonValue` | Structural copies of the SDK's provider options and JSON types. |
|
|
49
|
+
|
|
50
|
+
Notes:
|
|
51
|
+
|
|
52
|
+
- Flex is cheaper and may queue. Use it for background work, not for calls a user waits on.
|
|
53
|
+
- A tier the provider or model does not support is a no-op on the Gateway side.
|
|
54
|
+
- `"ultrafast"` is kept because one app defines it, but no app has confirmed it works. The `@ai-sdk/gateway` 4.x types list `serviceTier` as `"flex" | "priority"`. Check `providerMetadata.gateway.serviceTier` to see what the Gateway applied before you rely on it.
|
|
55
|
+
- The local `buildChatProviderOptions(extra)` it replaces was `{ ...FLEX, ...extra }`, where a caller `gateway` key dropped flex. `withFlexGatewayOptions` merges `gateway` instead. For the options passed to it today (a thinking-off option for another provider), the output is the same.
|
|
56
|
+
|
|
57
|
+
## Cost
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const result = await generateText({ model, prompt, providerOptions: FLEX_GATEWAY_PROVIDER_OPTIONS });
|
|
61
|
+
const costUsd = readGatewayCost(result.providerMetadata);
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`readGatewayCost(metadata)` returns `gateway.cost` (what was billed) or, if that is missing or unusable, `gateway.marketCost` (list price), so budget guards still see a value. Each may be a number or a numeric string. It returns `undefined` when neither is a finite number. A cost of `0` is returned as `0`, not skipped.
|
|
65
|
+
|
|
66
|
+
## Errors
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
try {
|
|
70
|
+
return await generateText({ model, prompt, maxRetries: 2 });
|
|
71
|
+
} catch (error) {
|
|
72
|
+
const failure = classifyGatewayError(error);
|
|
73
|
+
// { kind, message, retryable, statusCode? }
|
|
74
|
+
if (failure.kind === "quota") notifyBilling();
|
|
75
|
+
throw new AppError(appCodeFor(failure.kind), failure.message);
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`classifyGatewayError(error)` never throws. It unwraps `RetryError` to its last error, then checks in this order:
|
|
80
|
+
|
|
81
|
+
| `kind` | Matches | `retryable` |
|
|
82
|
+
| --- | --- | --- |
|
|
83
|
+
| `invalid_request` | `InvalidArgumentError`, `GatewayInvalidRequestError` | `false` |
|
|
84
|
+
| `auth` | `GatewayAuthenticationError`, and the error `ai` puts in its place (see below) | `false` |
|
|
85
|
+
| `model_not_found` | `NoSuchModelError`, `GatewayModelNotFoundError` | `false` |
|
|
86
|
+
| `quota` | A Gateway error with status 402, or a billing message (credits, funds, billing, payment required, spend limit, budget), or the word "quota" on a Gateway error that is not a rate limit | `false` |
|
|
87
|
+
| `rate_limit` | `GatewayRateLimitError` | `true` |
|
|
88
|
+
| `timeout` | The Gateway's `GatewayTimeoutError` (matched by name, as the package does not export it) | `true` |
|
|
89
|
+
| `gateway` | Any other Gateway error | the SDK's `isRetryable` |
|
|
90
|
+
| `malformed_response` | `InvalidResponseDataError` | `true` |
|
|
91
|
+
| `timeout` | An `Error` named `TimeoutError` or `AbortError` | `true` |
|
|
92
|
+
| `other` | Anything else | `false` |
|
|
93
|
+
|
|
94
|
+
- `statusCode` is set for every Gateway error. The SDK sets it to 500 when the response had none.
|
|
95
|
+
- `message` is the error's own message with ANSI colour codes and outer whitespace removed. The SDK keeps the Gateway's generation ID suffix (`"... [gen_…]"`). Request bodies and keys are not in it.
|
|
96
|
+
- Checks use the SDK's `isInstance`, which matches a marker symbol, so errors from another copy of `ai` or `@ai-sdk/gateway` in the bundle still match.
|
|
97
|
+
- `errorMessageOf(error)`: `error.message` for an `Error`, the string for a string, else `"Unknown error"`.
|
|
98
|
+
|
|
99
|
+
### Auth errors from `generateText`
|
|
100
|
+
|
|
101
|
+
`generateText`, `streamText` and the other `ai` calls replace a `GatewayAuthenticationError` before the caller sees it (`wrapGatewayError` in `ai` 5 to 7). Outside production it becomes a plain `Error` named `GatewayAuthenticationError`. With `NODE_ENV=production` it becomes an `AISDKError` named `GatewayError` whose message starts "Unauthenticated". Neither has the Gateway markers or a status code, so the local copy this came from classified both as `other`. `classifyGatewayError` matches them by name and returns `auth` with no `statusCode`.
|
|
102
|
+
|
|
103
|
+
### Quota and rate limits
|
|
104
|
+
|
|
105
|
+
The Gateway has no quota error type. An out-of-credits or spend-limit reply arrives as a rate-limit error or a generic Gateway error (an unknown error type becomes `GatewayInternalServerError` with the response status). So the classifier uses the status and the message:
|
|
106
|
+
|
|
107
|
+
- Status 402, or a billing word, means `quota` on any Gateway error.
|
|
108
|
+
- The bare word "quota" is ambiguous on a rate-limit error ("requests per minute quota"). There it stays `rate_limit`, as before. On any other Gateway error (for example a 403) it means `quota`.
|
|
109
|
+
- Errors that are not Gateway errors are never `quota`.
|
|
110
|
+
|
|
111
|
+
Callers that had only `rate_limit` should handle `quota` too. Treat it as not retryable until someone tops up or the period resets.
|
|
112
|
+
|
|
113
|
+
### Changes from the local `gatewayErrors.ts`
|
|
114
|
+
|
|
115
|
+
- New kind `quota`, checked before `rate_limit`.
|
|
116
|
+
- `auth` also matches the error `ai` puts in place of `GatewayAuthenticationError`.
|
|
117
|
+
- The Gateway's own timeout is `timeout`, not `gateway`.
|
|
118
|
+
- `statusCode` is set for every Gateway error, not only the `gateway` kind.
|
|
119
|
+
- `message` has ANSI colour codes and outer whitespace removed.
|
|
120
|
+
- No `"use node"`.
|
|
121
|
+
|
|
122
|
+
## Adopting it in the apps
|
|
123
|
+
|
|
124
|
+
Each app can delete its local copy once it imports from `@vvedantb/server/ai` (0.11.0 or later). Keep model IDs, prompts and app wrappers local. Paths are as found in each app.
|
|
125
|
+
|
|
126
|
+
| Local file | Replace with | Keep local |
|
|
127
|
+
| --- | --- | --- |
|
|
128
|
+
| `src/core/gateway.ts`: `GatewayTier`, `gatewayTier`, `FLEX_PROVIDER_OPTIONS` | `GatewayServiceTier`, `gatewayTier`, `FLEX_PROVIDER_OPTIONS` (same names) | Model IDs, the provider routing and Anthropic option helpers, the gateway factory and its type |
|
|
129
|
+
| `packages/backend/engine/llm/aiGateway.ts`: `FLEX_GATEWAY_PROVIDER_OPTIONS`, `buildChatProviderOptions`, `readGatewayCost`, `parseCost` | `FLEX_GATEWAY_PROVIDER_OPTIONS`, `withFlexGatewayOptions`, `readGatewayCost` | Model IDs, the thinking-off option, the text and embedding wrappers, result types |
|
|
130
|
+
| `systemOneClient.ts` (same app): `classifyError` | Call `classifyGatewayError`, then map `kind` to the app's own errors | The app's error types, key redaction, detail trimming |
|
|
131
|
+
| `packages/backend/convex/_ai/gatewayErrors.ts` (whole file) | `classifyGatewayError`, `errorMessageOf`, `GatewayErrorKind`, `GatewayFailure` | Each caller's own codes and copy; add a case for `quota` |
|
|
132
|
+
| `packages/backend/convex/textGen.ts` (same app): inline `{ gateway: { serviceTier: "flex" } }` | `FLEX_GATEWAY_PROVIDER_OPTIONS` | Prompts and the model constant |
|
|
133
|
+
| Other apps' local Gateway tier, cost and error helpers (not reviewed: those repos were not readable when this was written) | The same exports | App wrappers and model IDs |
|
|
134
|
+
|
|
135
|
+
Since the shared module has no `"use node"`, callers of the old `gatewayErrors.ts` can import it from the default runtime too.
|
package/docs/convex.md
CHANGED
|
@@ -396,7 +396,7 @@ expect(store.getQuery(api.tasks.list, { projectId })).toHaveLength(1);
|
|
|
396
396
|
|
|
397
397
|
## V Pro plan check
|
|
398
398
|
|
|
399
|
-
`hasVPlan` tells whether a session holds the shared V Pro plan (Clerk Billing key `v_pro`, $10/month or $100/year). The
|
|
399
|
+
`hasVPlan` tells whether a session holds the shared V Pro plan (Clerk Billing key `v_pro`, $10/month or $100/year). The retired `vibot_pro` plan no longer counts. It reads the Clerk session token v2 `pla` claim (`u:v_pro`, `o:v_pro`, or a bare slug), because Clerk's `has({ plan })` is not available in Convex. Convex surfaces custom JWT claims on the identity.
|
|
400
400
|
|
|
401
401
|
```ts
|
|
402
402
|
import { hasVPlan } from "@vvedantb/server";
|
|
@@ -405,7 +405,7 @@ const identity = await ctx.auth.getUserIdentity();
|
|
|
405
405
|
if (!hasVPlan(identity)) throw new Error("V Pro required");
|
|
406
406
|
```
|
|
407
407
|
|
|
408
|
-
`null`, a missing `pla` or a malformed value returns `false`; it never throws. `V_PRO_PLAN_KEY
|
|
408
|
+
`null`, a missing `pla` or a malformed value returns `false`; it never throws. `V_PRO_PLAN_KEY` and `V_PRO_PLAN_KEYS` are exported too.
|
|
409
409
|
|
|
410
410
|
## Develop
|
|
411
411
|
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vvedantb/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"license": "MIT",
|
|
5
|
-
"description": "Shared Convex backend helpers, MCP server scaffolding and Node-side MCP OAuth client helpers from one root import: query-limit errors, Clerk auth and token verification, an MCP bearer-token cache, Clerk-user lookups and ensure-user for Convex functions, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools, WebCrypto primitives, Convex optimistic-update helpers, MCP OAuth client helpers (provider, sign-in, refresh, revocation, loopback redirect server) for desktop apps, a QuickJS code sandbox that bridges script tool calls to host handlers, and a pure artifacts core (Zod contract, state limits and ops, quiz and flashcards pages, a sandboxed document wrapper with CSP and a guest state bridge).",
|
|
5
|
+
"description": "Shared Convex backend helpers, MCP server scaffolding and Node-side MCP OAuth client helpers from one root import: query-limit errors, Clerk auth and token verification, an MCP bearer-token cache, Clerk-user lookups and ensure-user for Convex functions, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools, WebCrypto primitives, Convex optimistic-update helpers, MCP OAuth client helpers (provider, sign-in, refresh, revocation, loopback redirect server) for desktop apps, a QuickJS code sandbox that bridges script tool calls to host handlers, and a pure artifacts core (Zod contract, state limits and ops, quiz and flashcards pages, a sandboxed document wrapper with CSP and a guest state bridge); and, from the `@vvedantb/server/ai` subpath, Vercel AI Gateway helpers (service tier provider options, cost from provider metadata, error classification).",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"publishConfig": {
|
|
8
8
|
"access": "public"
|
|
@@ -17,10 +17,15 @@
|
|
|
17
17
|
"types": "./dist/index.d.ts",
|
|
18
18
|
"import": "./dist/index.js"
|
|
19
19
|
},
|
|
20
|
+
"./ai": {
|
|
21
|
+
"types": "./dist/ai/index.d.ts",
|
|
22
|
+
"import": "./dist/ai/index.js"
|
|
23
|
+
},
|
|
20
24
|
"./package.json": "./package.json"
|
|
21
25
|
},
|
|
22
26
|
"files": [
|
|
23
27
|
"dist",
|
|
28
|
+
"docs/ai.md",
|
|
24
29
|
"docs/artifacts.md",
|
|
25
30
|
"docs/convex.md",
|
|
26
31
|
"docs/crypto.md",
|
|
@@ -43,14 +48,19 @@
|
|
|
43
48
|
"prepack": "tsc -p tsconfig.json"
|
|
44
49
|
},
|
|
45
50
|
"peerDependencies": {
|
|
51
|
+
"@ai-sdk/gateway": ">=1",
|
|
46
52
|
"@clerk/backend": ">=1",
|
|
47
53
|
"@jitl/quickjs-singlefile-cjs-release-sync": "^0.32.0",
|
|
48
54
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
55
|
+
"ai": ">=5",
|
|
49
56
|
"convex": "^1.24.0",
|
|
50
57
|
"quickjs-emscripten-core": "^0.32.0",
|
|
51
58
|
"zod": "^3.25.0 || ^4.0.0"
|
|
52
59
|
},
|
|
53
60
|
"peerDependenciesMeta": {
|
|
61
|
+
"@ai-sdk/gateway": {
|
|
62
|
+
"optional": true
|
|
63
|
+
},
|
|
54
64
|
"@clerk/backend": {
|
|
55
65
|
"optional": true
|
|
56
66
|
},
|
|
@@ -60,6 +70,9 @@
|
|
|
60
70
|
"@modelcontextprotocol/sdk": {
|
|
61
71
|
"optional": true
|
|
62
72
|
},
|
|
73
|
+
"ai": {
|
|
74
|
+
"optional": true
|
|
75
|
+
},
|
|
63
76
|
"convex": {
|
|
64
77
|
"optional": true
|
|
65
78
|
},
|
|
@@ -71,9 +84,11 @@
|
|
|
71
84
|
}
|
|
72
85
|
},
|
|
73
86
|
"devDependencies": {
|
|
87
|
+
"@ai-sdk/gateway": "^4.0.135",
|
|
74
88
|
"@jitl/quickjs-singlefile-cjs-release-sync": "^0.32.0",
|
|
75
89
|
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
76
90
|
"@types/node": "^22.0.0",
|
|
91
|
+
"ai": "^7.0.162",
|
|
77
92
|
"convex": "^1.47.0",
|
|
78
93
|
"quickjs-emscripten-core": "^0.32.0",
|
|
79
94
|
"typescript": "^5.9.0",
|