npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@contextual-io/tanstack-ai-adapter

v0.1.1

Published

TanStack AI v1 text adapter for the Contextual AI Gateway

Readme

@contextual-io/tanstack-ai-adapter

A TanStack AI v1 text adapter for the Contextual AI Gateway. It runs chat() through Gateway Routes with the caller's Contextual authorization.

import { chat } from "@tanstack/ai"
import { contextualText, createGatewayClient } from "@contextual-io/tanstack-ai-adapter"

const gateway = createGatewayClient({
  url: process.env.CONTEXTUAL_AI_GATEWAY_URL!,
  tenantId: process.env.CONTEXTUAL_TENANT_ID!,
  credentials: { kind: "bearer", token: process.env.CONTEXTUAL_ACCESS_TOKEN! },
})

const stream = chat({
  adapter: contextualText("support-route", { client: gateway }),
  threadId: "conversation-42",
  messages: [{ role: "user", content: "Where is order 42?" }],
})

contextualText(route, { client }) takes a stored Route ID or an inline { id, name, modelProviders } Route whose model providers name a model and a providerConnectionId. The Route selects upstream models and Connections, so provider credentials never pass through the adapter. TanStack's chat() owns the thread, the tool loop, and approvals. client is the client from createGatewayClient or any object with the same generate(request, { signal, wrapFetch }) method. The adapter passes it the request's JSON form, GatewayGenerateRequestJson, which is what the HTTP client sends, reads whatever it resolves to as JSON, and checks that it is a Gateway response.

createGatewayClient options:

  • url: the Gateway's origin. The client posts to /api/v1/generate there.
  • tenantId: sent as the x-org-id header and passed to token providers.
  • credentials: the caller's authorization, described below.
  • objectApiUrl (optional): passed to token providers; defaults to url.
  • fetch (optional): used instead of the global fetch.

Credentials

Use the client on a server. Its credentials authorize Gateway calls as the caller, so tokens and client secrets must never reach browser code. Browsers should reach chat() through your server, for example with TanStack's chat transports.

credentials takes one of the Contextual SDK's credential forms:

  • { kind: "bearer", token } sends Authorization: Bearer <token> on every request.
  • { kind: "provider", getBearerToken, invalidate? } calls getBearerToken(signal, context) before every Gateway request and keeps no token itself, so caching and refresh belong to the provider, such as the SDK's clientCredentials(). signal is the request's abort signal, or one that never aborts when the request has none. context is { tenantId, objectApiUrl, serviceApiUrl }, with the client's url as serviceApiUrl. If getBearerToken throws, the request fails before it is sent, with an aborted error when the request was aborted and otherwise a credentials error, "Could not resolve the caller's Contextual credentials", whose cause is the provider's error.
  • { kind: "apiKey", key, header } is accepted by the type so SDK credentials assign directly, but the Gateway accepts only bearer tokens. The request fails before it is sent with a credentials error, "The Contextual AI Gateway accepts bearer tokens, not API key headers". Use a bearer token or a token provider instead.

When the Gateway answers 401 to a request whose token came from a provider, the adapter passes the rejected token and the same context to the provider's optional invalidate(token, context) and waits for it to finish, including a returned promise, before reporting the 401. The provider's next getBearerToken call can then acquire a fresh token. Aborting the request ends that wait early, so a request made before a slow invalidate finishes can still receive the rejected token. Other statuses do not call invalidate, and the adapter never resends a request. If invalidate throws or rejects before an abort ends the wait, the caller still gets the 401 GatewayError with that failure as its cause. When an abort ends the wait first, the 401 has no cause, and a later failure from invalidate is not reported.

Errors

Failures are GatewayErrors. gateway.generate() throws one with the code aborted, credentials, unreachable, invalid-response, or the Gateway's HTTP status as a string, such as "401". Before any request, the adapter raises unsupported for history, tool schemas, output schemas, or other request values the Gateway cannot take, such as a cycle or a NaN. It raises invalid-response when a client resolves to anything else, including a response with a tool call that lacks its ID, name, or object arguments. A GatewayError also carries status, retryAfterMs from a Retry-After header given in seconds, and effectMayHaveOccurred, which is true when the Gateway may already have done provider work. providerErrors lists failed route attempts with each provider's raw error text, which can echo request details, so keep it on the server. Error messages and the adapter's logs leave that text out.

In a chat() stream the adapter reports a GatewayError as a RUN_ERROR event with its message and code. With @tanstack/ai 1.0.0, retry timing is at event.metadata.tanstack.retryAfterMs. Its rawEvent holds the status, effectMayHaveOccurred, and the provider, model, and status code of each failed attempt. The event does not include the error's cause. Any other failure becomes a generic message with the code adapter-error.

Handle errors from the stream above:

for await (const event of stream) {
  if (event.type === "RUN_ERROR") {
    const retryAfterMs = event.metadata?.tanstack?.retryAfterMs
    console.error(event.message, { code: event.code, retryAfterMs })
  }
}

Limitations

  • The adapter calls the Gateway's HTTP generate endpoint, which returns a complete response, so each answer arrives as one text delta after generation finishes.
  • Aborting ends the HTTP request, but provider work the Gateway already started may still finish, so a request aborted while it waits for the Gateway's response reports effectMayHaveOccurred: true.
  • Multi-turn tool use and toolChoice need Gateway support for tool results and tool choice. Without it, a request whose history includes a tool result fails, and toolChoice has no effect. The adapter sends toolChoice in the Gateway's shape.
  • The Contextual SDK's ctx.ai takes neither tool definitions nor, in a managed handler, an inline Route. With it as the client, a chat() that declares tools or uses an inline Route ends with an adapter-error RUN_ERROR before any Gateway call.
  • History the Gateway cannot carry, such as audio or video parts, provider file handles, provider-executed tool calls, or redacted thinking, fails with an unsupported error before any request.
  • The Gateway reports unknown provider usage as zero tokens.

Requirements

  • Node 22 or later; the package is ESM only, like @tanstack/ai
  • @tanstack/ai 1.x (peer dependency)
  • Zod 4.2 or later for Zod tool and output schemas; the package itself depends on Zod 4.6.7