> ## Documentation Index
> Fetch the complete documentation index at: https://docs.impact.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript integrations

> Find native versions, initialization order, applicable operations, and capture limits for each JavaScript integration.

Find the entry for your application's client, operation, and route before enabling capture. The automatic
owners select the application dependencies already installed. Set `integrations: { openAI: 'disabled' }` to
leave an owner inactive. [Review startup and provider ownership](https://docs.impact.ai/sdk/javascript/setup.md).

Automatic selection defaults to `auto` for `openAI`, `anthropic`, `google`, `googleADK`, `vercelAI`,
`langChain`, `openAIAgents`, `awsBedrock`, and `mcp`. Direct Google Gen AI and the ADK runner have separate
selectors. `vercelAI: 'scoped'` selects only calls using the per-call helper. Mastra and Realtime use explicit registration.

## Look up compatibility for your deployment

This catalogue describes `impact-ai@0.4.0-rc.10`. The complete operation sets listed here are **Unassessed** for
that package. `runtime.status().integrationDetails` gives the installed package's exact operation sets, native
package and capture-owner versions, activation, limits, and actions. The runtime lists alternate native versions
as complete tuples in `supportedNativeVersions`. The selected capture-owner version still applies.
`qualificationApplicability` is `unknown` when an installed version cannot be observed.

An npm peer range controls package installation. Check the actual operation and capture owner separately, then
verify a representative [Product Trace](https://docs.impact.ai/sdk/javascript/troubleshooting.md). Framework and provider spans can
describe distinct work in a single paid call.

## First Trace profiles

* **OpenAI Responses.** Use `openai 7.53.0` with Node 22 or 24 ESM and an OpenAI client constructed after init.
  This profile uses the OpenTelemetry OpenAI owner `0.23.0` and Impact's Responses supplement with the managed route or
  the application's OTel API `1.10.0`, SDK `3.1.0`, and an explicit Impact destination. Start with unary
  Responses, a parsed native helper, or a consumed stream prefix. Early close preserves that prefix.
  [Run the OpenAI quickstart](https://docs.impact.ai/quickstart.md#javascript-example).
* **Google Gen AI Developer API.** The selected starting operation is unary `models.generateContent` on
  `@google/genai 2.21.0`, Node 24 ESM, without a native automatic function-calling loop. Construct the
  client after init with the application trace SDK `2.11.0`, logs SDK `0.222.0`, and its API `1.9.1`
  context owner passed explicitly. The Models owner captures available model input, answer, usage, and
  native parentage within the request. Native automatic callable-tool loops expose one logical operation
  and its final response. Intermediate identities and usage are unassessed. Explicit application calls
  retain their individual boundaries.

## Admitted application peers

Impact bundles the capture machinery. The application installs only the clients and frameworks it uses.
The selected instrumentation uses Impact's OTel API `1.10.0` and SDK `3.1.0`. A native framework can
require its own OTel version and explicit bridge. Disabling an integration changes activation work while
keeping the installation's dependency closure. Imported modules stay resident after shutdown.

| Integration mechanism | Customer package range · SDK-managed owner |
| - | - |
| AI SDK telemetry | `ai >=7.0.34 <8` · bundled `@ai-sdk/otel 1.0.164` |
| OpenAI | `openai >=6.46.0 <8` · `@opentelemetry/instrumentation-openai 0.23.0` |
| Anthropic | `@anthropic-ai/sdk 1.6.0` · OpenInference derivative `1.0.1+impact.1` |
| Google Gen AI | `@google/genai >=2.21.0 <2.23.0 \|\| 2.31.0 \|\| 2.32.0 \|\| 3.0.0` |
| LangChain | `@langchain/core >=1.2.9 <1.3.0 \|\| 1.3.0 \|\| 1.3.5` · OpenInference `4.1.5` |
| OpenAI Agents | `@openai/agents >=0.17.0 <0.19.0 \|\| 0.21.0` · OpenInference `0.3.3` |
| Bedrock Runtime | `@aws-sdk/client-bedrock-runtime >=3.1127.0 <4` · AWS instrumentation `0.80.0` |
| Google ADK | `@google/adk 2.3.0 \|\| 2.4.0` · native telemetry plus Impact runner events |
| MCP | client/server `2.3.0 \|\| 2.4.0` · native protocol plus Impact tool-content supplement |
| Mastra | core `1.60.0 \|\| 1.82.0 \|\| 1.83.0-alpha.0` · current SDK-managed Observability `1.23.2-alpha.0` · public native bridge |
| Bedrock Knowledge Bases | `@aws-sdk/client-bedrock-agent-runtime >=3.1127.0 <4` · Impact supplement |

Use the application-owned OpenTelemetry setup for its sampler, context manager, providers and other
destinations. [Attach an Impact destination](https://docs.impact.ai/sdk/javascript/setup.md#use-your-opentelemetry-provider).

## OpenAI

### OpenAI public inference

`js.openai.public.v1` · OpenAI `7.53.0` · official owner `0.23.0` plus Impact supplement

**Operations.** Responses, Chat Completions and Embeddings create · unary, selected helpers and consumed
streams.

**Limits.** Official owner declares OpenAI `<7` · ESM is selected, while CJS and multiple builds are
unassessed.

### Azure OpenAI

`js.openai.azure.v1` · `AzureOpenAI` through the same selected client/owner

**Operations.** Responses, Chat Completions and Embeddings create.

**Limits.** Deployment, API version, credentials, region and entitlement remain customer-owned.

### Microsoft Foundry

`js.openai.foundry.v1` · Standard OpenAI client at an explicit Foundry endpoint

**Operations.** Responses, Chat Completions and Embeddings create.

**Limits.** No Foundry project, resource, retrieval, Search or control-plane claim.

### OpenAI-compatible endpoints

`js.openai.compatible.v1` · Standard OpenAI client at an explicit private/local base URL

**Operations.** Responses, Chat Completions and Embeddings create.

**Limits.** No arbitrary dialect, named vendor, tool, stream or usage compatibility follows.

### OpenAI background, resumed, and media operations

`js.openai.extended.v1` · `openai 7.53.0` · Impact supplement

**Operations**

* `openai.responses.create(background=true)`, `openai.responses.retrieve`, `openai.responses.cancel`,
  `openai.responses.retrieve(stream=true,starting_after)`.
* `openai.images.generate`, `openai.images.edit`.
* `openai.audio.speech.create`, `openai.audio.transcriptions.create`, `openai.audio.translations.create`.

**Limits.** Provider resumed-stream replay can stall before headers or events even after normal completion.
This entry applies only to public OpenAI. Unread raw/media bodies remain unobserved. Background operation
availability and media model entitlement belong to the provider.

The listed routes use the native `openai 7.53.0` package. Construct the client after init. For public Responses, follow
[stream and helper capture](https://docs.impact.ai/sdk/javascript/capture.md#openai-structured-output-and-helpers). For a compatible URL,
confirm that route's payloads, tool calls and usage in your Trace. If background replay stalls, use ordinary
retrieval for a completed response. [Migrate from Assistants](https://docs.impact.ai/sdk/javascript/upgrade.md#migrate-from-the-openai-assistants-api).

## Anthropic

### Anthropic Messages

`js.anthropic.public.v1` · Anthropic `1.6.0` · bundled OpenInference derivative `1.0.1+impact.1`

**Operations.** Messages create/stream, selected helpers and consumed streams.

**Limits.** Public Messages only · Claude on Google Cloud is not supported.

Anthropic 1.6 owns its resolved native telemetry settings. To opt in to full bounded content on an application-owned
client, configure the native option explicitly:

```js theme={null}
const client = new Anthropic({
  openTelemetry: { traces: { contentMode: 'content' } },
});
```

Native defaults and `metadata_only` keep native metadata telemetry, disabled tracing stays disabled, and explicit
native tracer providers keep their route. Impact's content settings cannot widen those controls or the native
`maxContentBytes` limit. When an existing global customer provider is retained, or `init` attaches to an external provider, extra OpenInference
model capture is declined to preserve native tracing. At startup, add an Impact destination to the native provider
and initialize with that provider and destination. The external-provider recipe shows the constructor order. [Use your OpenTelemetry provider](https://docs.impact.ai/sdk/javascript/setup.md#use-your-opentelemetry-provider).
Native-only content and usage follow the native client's limits and may omit facets available from the bounded
derivative. Explicit Protect enforcement remains available.

Input-token totals include cache reads and writes. Uncached and individual cache counters
remain separate facts. ToolRunner and cloud endpoints are outside the selected Messages claim.

## Google Gen AI

### Google Models via the Developer API

`js.google.models.developer.v1` · Google Gen AI `2.21.0` · Impact Models owner

**Operations.** `generateContent`, `generateContentStream`, `embedContent`.

**Limits.** Clients created before init and direct `ReadableStream` reader use are not captured.

### Google Models via Vertex AI

`js.google.models.vertex.v1` · Vertex-configured Google Gen AI client · same owner

**Operations.** The same selected Models operations.

**Limits.** Project, location, ADC and model entitlement remain customer/cloud responsibilities.

### Google Interactions via the Developer API

`js.google.interactions.v1` · Google Gen AI `2.21.0` · Developer API · Impact Interactions owner

**Operations.** Model create/stream/tool continuation plus application-called get/cancel/delete.

**Limits.** Background/reconnect and unary built-in-agent create have separate exact claims · agent
streaming/lifecycle and Vertex require independent evidence.

### Google Interactions background and resumed operations

`js.google.background.v1` · `@google/genai 2.21.0` · Developer API v1beta · Impact supplement

**Operations.** `google.interactions.create(background=true,store=true)`, later
`google.interactions.get(stream=false)`, then `google.interactions.get(stream=true,last_event_id)`.

**Limits.** Developer API background creation and application-driven terminal/reconnected observation with
`gemini-3.7-flash`. No SDK polling or resume orchestration · availability remains model-owned. Cancel/delete
belong to the base Interactions claim. Built-in agents and Vertex Interactions have separate route
boundaries.

### Google Interactions built-in agent creation

`js.google.interactions.agent-create.v1` · Google Gen AI `2.31.0` · Developer API · retained client-response
owner

**Operations.** Application-called unary `interactions.create(agent=...)`.

**Limits.** Available native agent/interaction/environment IDs, code call/result, native status and separate
explicit input/output/thought/total usage. Native incomplete stays incomplete. No inferred final
answer/thought text, local execution span, SDK polling/continuation, agent stream/get/cancel/delete parity
or hosted telemetry acquisition.

Google Gen AI `2.32.0` has separate Models generate, stream and embeddings and model Interactions create/get/cancel/delete
operation boundaries in the catalogue. The `2.31.0` Developer API boundary covers generate/stream/tool/close/error and
model Interactions-create. It does not extend embed, Vertex, background or lifecycle support. Unary agent-create has
its own exact boundary.

The current direct Google client selection also admits exact `@google/genai 3.0.0`. Its Developer API default is `v1`.
Vertex stays on `v1beta1`, and explicit `apiVersion` keeps precedence over `GOOGLE_GENAI_API_VERSION`.
Impact requires Node.js 22.15 or later. Unary code-execution results retain either native text
or the native typed text/image/audio/video/document content array, within the existing capture limits and tools/media
policies. This does not select a new ADK3 pairing, video generation, hosted agent execution, or Live connection behavior.
Older 2.x tuples retain their catalogue boundaries. Check the installed support state for the selected client and operation.

## AWS Bedrock

### Bedrock Converse

`js.bedrock.converse.v1` · Bedrock Runtime `3.1164.0` · AWS owner `0.80.0` plus Impact supplement

**Operations.** Converse and caller-consumed ConverseStream.

**Limits.** InvokeModel, ApplyGuardrail, partner dialects and other AWS commands are outside this claim.

### Bedrock Nova InvokeModel

`js.bedrock.invoke.v1` · `@aws-sdk/client-bedrock-runtime 3.1164.0` · Impact supplement

**Operations.** `bedrock-runtime.InvokeModel(Nova)`, `bedrock-runtime.InvokeModelWithResponseStream(Nova)`.

**Limits.** This entry covers the selected Nova dialects. Claude through Bedrock, ApplyGuardrail, Agents and
other clients or partner dialects are unassessed. Caller-stopped or incomplete streams remain partial.

### Bedrock Knowledge Bases

`js.bedrock.knowledge-bases.v1` · `@aws-sdk/client-bedrock-agent-runtime 3.1164.0` · Impact supplement

**Operations.** `bedrock-agent-runtime.Retrieve`, `bedrock-agent-runtime.RetrieveAndGenerate`.

**Limits.** Application-called Knowledge Base retrieval/generation · check the installed catalogue for its
current support state. Agent orchestration, source crawling and extra retrieval are unassessed. Cloud
Knowledge Base access and model entitlement remain application-owned.

## Google ADK

### Google ADK Runner

`js.google-adk.runner.v1` · Google ADK `2.4.0` / GenAI `2.32.0` · native SDK2 provider attachment plus
Impact runner events

**Operations.** `Runner.runAsync`, including model/tool/session events.

**Limits.** Shutdown marks the observation partial and stops capture without closing the native iterator.

### Start ADK 2.3 with managed telemetry

ADK `2.3.0` obtains its OpenTelemetry tracer during module evaluation. For a static ADK import on Node 22 or
24 ESM, use the explicit preload.

```sh theme={null}
node --import impact-ai/register app.mjs
```

`impact-ai/register` activates Impact before Node evaluates the application module graph. It reads
`IMPACT_ENDPOINT`, `IMPACT_API_KEY`, and optional `IMPACT_SERVICE_NAME`. Get the same attempt's handle with
`import { runtime } from 'impact-ai/register'`. The application owns the completion boundary and calls
`runtime.shutdown()`. The exported handle does not retry initialization. Node also applies `--import` to worker
threads, forks, and cluster children that inherit the option. Use explicit `execArgv` for child processes
and workers that should start without the preload.

### Start ADK 2.4 with an application provider

The listed runner profile uses Node.js `24.21.0` ESM. For ADK `2.4.0`, use its required API `1.9.1` / native trace/context SDK `2.12.0` / logs `0.223.0`
with GenAI `2.32.0`. Construct the native provider first and pass that actual provider (or its API 1.9 public proxy)
to Impact before importing the ADK application. The older managed SDK3 preload recipe above does not select this tuple.

Applications that own an existing OpenTelemetry provider keep an explicit application bootstrap so they can pass the
customer provider to `init()` before importing the ADK application module:

```js theme={null}
import * as impact from 'impact-ai';

const runtime = await impact.init({
  tracerProvider: customerTracerProvider,
});
try {
  const { main } = await import('./app.mjs');
  await main();
} finally {
  await runtime.shutdown();
}
```

When managed preload startup needs explicit settings, load a small application preload file that awaits
`impact.init({ integrations: { googleADK: 'disabled' } })` with Node's `--import`. The built-in preloader
reads managed environment settings.

## Vercel AI SDK and LangGraph

### Vercel AI SDK text and structured output

`js.vercel-ai.core.v1` · Vercel AI SDK `ai==7.0.164` · SDK-managed `@ai-sdk/otel==1.0.164`

**Operations.** `generateText`, `streamText` · structured output through `Output.object`.

**Limits.** Native telemetry registration cannot be removed · per-call opt-out can bypass capture ·
deprecated `generateObject` and `streamObject` are not advertised.

### Select individual AI SDK calls

Use scoped capture when a framework already observes its model calls, or only selected application calls
should reach Impact. Initialize once, then pass `aiTelemetry` through AI SDK's native `telemetry` option:

```ts theme={null}
import { init, interaction } from 'impact-ai';
import { aiTelemetry } from 'impact-ai/vercel-ai';
import { generateText } from 'ai';

const runtime = await init({ integrations: { vercelAI: 'scoped' } });
const answer = await interaction({ name: 'answer', interactionId, sessionId, userId }, () =>
  generateText({ model, prompt, telemetry: aiTelemetry('answer') }),
);
// Flush at the host's actual completion boundary; shut down when its runtime stops.
```

This mode does not register a process-wide AI SDK owner. Calls without the helper keep their native behavior.
Pass existing native settings as `aiTelemetry('answer', { telemetry: existingTelemetry })`; customer callbacks
remain in order, explicit opt-out remains off, and an existing OpenTelemetry owner is preserved instead of
duplicated. Inspect the runtime's integration limitation when a customer owner supplies that route.
`{ content: 'metadata' }` restricts Impact's copy for one call without changing the application's result or
customer callbacks. Scoped capture excludes headers, provider metadata and runtime-context payloads from its copy.
Supply `contextApi` at initialization when the application owns a different OpenTelemetry API copy.

Keep Mastra's own model calls on its native bridge; use this helper for separate AI SDK work. The helper does
not add a model request, provide an authentication boundary, or replace the host's flush lifecycle.

### LangChain runnables and LangGraph streams

`js.langgraph.langchain.v1` · LangChain core `1.3.5` / LangGraph `1.7.1` · OpenInference `4.1.5`

**Operations.** Runnable invoke/stream and compiled graph stream.

**Limits.** Consumer close is not proof of graph cancellation · provider work is separate.

The listed LangGraph profile uses Node.js `24.21.0` ESM. Alternate LangChain core and LangGraph tuples in the catalogue are `1.2.9` with `1.4.14`, and `1.3.0` with
`1.5.2`. Per-call Vercel AI SDK settings control native telemetry and output capture.
[See content policy](https://docs.impact.ai/sdk/javascript/capture.md#choose-what-impact-captures).

## OpenAI Agents

### OpenAI Agents Runner

`js.openai-agents.runner.v1` · OpenAI Agents current `0.21.0` / catalogue reference `0.17.0` · OpenInference
`0.3.3` plus provider owner

**Operations.** `Runner.run` and `Runner.run(..., { stream: true })` · tools, handoffs and final usage.

**Limits.** Node 24.21.0 · automatic capture is unavailable on Bun. Individual framework processors cannot
be removed · restart after shutdown.

The optional OpenInference Agents peer is only an ownership check for an application that already installs its own
owner: Impact checks that owner's public ESM and CJS `isPatched()` state and declines automatic Agents capture when
it is active or cannot be assessed. Ownership is checked at initialization. If the application activates another owner later, disable Impact Agents
capture at startup. This does not discover arbitrary custom native trace processors. Additive customer processors
remain application-owned.

On Node, automatic OpenAI Agents activation preserves application shutdown handlers and existing native processors.
When Impact's import creates the native trace provider, shutdown makes a bounded call to that provider's public
`forceFlush` before disabling Impact capture. This also flushes processors the application later adds. Impact never
removes or shuts them down. A provider created before Impact retains its hooks and is neither flushed nor shut down
by Impact. Automatic OpenAI Agents capture is unavailable on Bun, where the terminating import-time hooks cannot
be isolated safely.

## MCP

### MCP client tools

`js.mcp.client-tools.v1` · Official MCP client `2.4.0` · customer-owned connections

**Operations.** Caller-owned connect/initialize, listTools, callTool and close over stdio and Streamable
HTTP.

**Limits.** Passive observation of capabilities, public tool definitions, protocol/request IDs and actual
tool input/result/error · no SDK-owned connection, discovery or invocation.

### MCP server tools

`js.mcp.server-tools.v1` · MCP server `2.4.0` · Impact tool-content supplement

**Operations.** `mcp.server.tools.call`.

**Limits.** Selected when Impact initializes before server construction and handler registration over stdio
and Streamable HTTP. Existing pre-init servers, resources, prompts and custom transports are unassessed. No
SDK-owned connection or invocation.

### Deploy MCP over HTTP

For a new HTTP deployment, use the application-owned MCP `2.4.0` client/server tuple with current patched
transport packages. The peer range also admits `2.3.0`. The legacy Mastra core `1.60.0` graph resolves an
affected MCP server. Keep that graph to the documented Bun Agent `fullStream` compatibility route and keep its MCP
server off HTTP. For Mastra `1.82.0` or `1.83.0-alpha.0`, check the bridge and operation for your native tuple. Confirm the
resolved MCP dependencies before exposing an HTTP server.
[MCP HTTP request body and batch limits advisory](https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/GHSA-f897-62hf-6gxq)

The upstream `2.3.0` release introduced the
[OAuth issuer](https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/GHSA-6qxp-vccf-f47h)
and [HTTP redirect](https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/GHSA-6prh-2h8m-c8cw)
fixes. Impact does not change authentication or transport policy. Applications using OAuth must retain `issuer`
when storing credentials, stamp or clear existing unstamped credentials, and configure `expectedIssuer` on bundled
providers where applicable. Use final endpoint URLs for cross-origin redirects. `redirectPolicy: 'follow'` restores
the exposed behavior. The upstream advisories describe remaining application configuration limits.

For MCP HTTP servers, use a factory that creates a server per request, or one server/transport per session.
The server reuse restriction introduced in `2.3.0` rejects shared server and stateless transport reuse to prevent
[cross-client delivery](https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/GHSA-jm63-cq47-j5jp).
The other patched server controls require application configuration: set `maxToolInputElements` on `McpServer`
and `maxRequestBodySize` on `createMcpHandler()` or the transport (and bound any separate body parser) for
[validation limits](https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/GHSA-46jr-4wx8-v453).
For [bearer audience validation](https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/GHSA-rvq5-wwqv-78pq),
set `expectedResource` on the auth helper and return the verified token audience as `AuthInfo.resource`.
Express users also need `@modelcontextprotocol/express` 2.0.2 or later. Upgrading alone enables neither the tool-input
element limit nor the audience check. Impact preserves caller-owned options and authentication. It does not configure these policies.

## OpenAI Realtime

### OpenAI Realtime server WebSocket

`js.openai-realtime.server.v1` · OpenAI `7.53.0` · explicit Impact event attachment

**Operations.** Caller-owned server WebSocket control, response, tool, usage and terminal events.

**Limits.** WebRTC media, SIP, RTP, playback and SDK-owned connections are outside this claim.

#### Observe a server Realtime connection

Attach the caller-owned connection before its first response request. For logical correlation, pick a
metadata field your app already sets to a unique string in `response.create.response.metadata`. This
example uses `request_id`.

```js theme={null}
runtime.attachRealtime(connection, { connectionId, correlationMetadataKey: 'request_id' });
```

The SDK snapshots the active Interaction, Session, User, and native parent at the send boundary. A unique
matching metadata echo on the first observed response event binds later events for that `response_id` to
the snapshot. The app supplies the metadata and the SDK uses its value only as a correlation key.
Without a configured key or verified echo, automatic, VAD, and unmatched responses retain native facts
with unassigned logical identity, regardless of arrival order or active receive context.

Use a nonempty field name up to 64 UTF-8 bytes and nonempty values up to 512 UTF-8 bytes. Keep each value
unique for the lifetime of the native connection, including across capture detachment. Observed reuse
stays unmatched. After 4,096 retained key identities, further associations are unavailable and the SDK
reports capacity as the reason.

Late events can use the retained response binding while the Interaction stays ended. Await the actual
result inside the owning Interaction, or use the explicit application handoff for longer work.
[Group work into an Interaction](https://docs.impact.ai/sdk/javascript/api.md#group-work-into-an-interaction) ·
[Continue work after a queue handoff](https://docs.impact.ai/sdk/javascript/api.md#continue-work-after-a-queue-handoff)

Keep provider session, conversation, and response IDs and the provider's `gen_ai.interaction.id`
separate from Impact's `impact.session.id` and `impact.interaction.id`.

### Browser Realtime control channel

`js.realtime.browser-control.v1` · `impact-ai/realtime-events` · authenticated server submission

**Operations.** Application-visible JSON RTC data-channel control traffic.

**Limits.** No browser exporter, ingest credential, media-track or general WebRTC claim.

The browser control profile uses Chrome `152.0.7977.77` with a Node.js 22 or 24 authenticated application bridge.

#### Forward browser data-channel observations

On the browser, call `observeRealtimeDataChannel` from `impact-ai/realtime-events` on the existing
channel. Choose the per-event `observe` callback or `deliverBatch` to forward observations through the
application's authenticated route. The application owns `send()`, listeners, closure, and media.
For batched delivery, the callback receives `{ batchId, observations }` and `{ signal, keepalive }`;
pass those request options to the application's network call. The server submits each authorized observation
from the envelope in its original order.

```js theme={null}
import { observeRealtimeDataChannel } from 'impact-ai/realtime-events';

const observer = observeRealtimeDataChannel(channel, {
  connectionId: browserConnectionId,
  deliverBatch: forwardThroughAuthenticatedRoute,
});
```

On the server, authorize the forwarded observations and choose their connection identity. Establish the
original request context before submitting the client `response.create` observation. Association
requires that context and a matching provider metadata echo regardless of incoming source labels or
the context active during later HTTP receipt.

```js theme={null}
runtime.observeRealtime(observation, { connectionId, correlationMetadataKey: 'request_id' });
```

Batched delivery retains at most 64 observations. Each envelope carries at most 16 observations and
60 KiB, leaving room under the browser's 64 KiB keepalive request bound. Delivery uses a two-second
timeout and one bounded retry. The observer reports loss in a later envelope and local `status()`.

At the application's channel lifecycle boundary, await `observer.stop()` for batched delivery. It
restores the native channel immediately, aborts any active delivery, and makes one bounded final
keepalive attempt. The final batch keeps the newest events in order and reports observations omitted
by the limit. Repeated calls share the same completion.

An accepted callback confirms local delivery. Check Product admission and readback separately.

## Mastra

### Mastra agents and workflows

`js.mastra.native.v1` · Mastra core `1.83.0-alpha.0` · bundled Observability `1.23.2-alpha.0` · Impact
public native bridge + schema supplement

**Operations.** `Agent.stream` `fullStream` and selected `Workflow.run.stream` completion/error/cancellation
boundaries · model inference usage without aggregate duplication.

**Limits**

* The private Bun 1.3.14 / core 1.60.0 / Hono 1.6.0 / server 1.58.0 path is the Agent HTTP stream route,
  with bundled Observability or an explicit 1.20.0 factory and customer API 1.9.1/provider 2.11.
  Its Workflow and MCP HTTP server are outside this boundary.
* Cross-API request joining requires the explicit caller contextApi · logical scope remains separate.
* Native-internal and excluded spans are omitted · visible children retain the closest exported ancestor.
* Inference input is a native preview · generation spans retain full available native messages.
* Unended bridge spans close as partial with unknown outcome.

### Start with private Impact capture

Use `initMastra` for a new Impact route. Keep existing application telemetry startup as it is; the SDK
owns its private provider, logger, bridge and cleanup, including the bundled Observability instance:

```ts theme={null}
import { context as callerContext } from '@opentelemetry/api';
import { initMastra } from 'impact-ai/mastra';

const capture = await initMastra({
  serviceName: 'agent',
  endpoint: process.env.IMPACT_ENDPOINT,
  apiKey: process.env.IMPACT_API_KEY,
  contextApi: callerContext,
});
const mastra = new Mastra({ agents, observability: capture.observability });

// Inside the application's verified request scope, after its admission checks:
return capture.request(
  { name: 'answer', interactionId, sessionId, userId, signal: request.signal },
  () => existingMastraHandler(request),
);
```

The app owns authentication, identifiers, routing and the native handler. The SDK does not install middleware
or change that handler's abort signal. `shouldCapture(context)` can further restrict eligible requests.
If the application selects its own compatible Observability package, pass
`createObservability: (config) => new Observability(config)`; this constructs a new Impact-owned instance.
Use `content` for capture policy, `capture.status()` for startup diagnosis and `capture.shutdown()` when the
application stops. `capture.runtime` is the same core runtime for separately selected capabilities, so do not
initialize another runtime for Simulation. Its transport and application effect rules remain separate.

`capture.request` observes a fresh, local successful Mastra/Hono Agent SSE Response. It forwards bytes on demand
and reports successful completion only after a native run finish, the SSE trailer and consumed EOF. It forwards
native read failures and cancellation without retrying application work. Unknown formats, observation limits and
unfinished bodies leave completion unobserved; arbitrary Fetch responses, BYOB reads and other stream protocols
are outside this adapter. Unwrapped Responses keep the ordinary opaque-result behavior.

The private route does not register a global OpenTelemetry provider or add Impact content to Azure's exporter.
It reads the supplied native parent context, while active Impact spans stay in an SDK-local context scope.
Existing application instrumentation retains its own context owner. The private Impact provider records admitted
requests even when the Azure parent is unsampled, preserving its parent IDs without changing Azure's sampling.
Mastra admission and content restrictions still apply; a matching logical Interaction ID alone does not prove native parentage.
Private capture omits opaque native exception and failure-log details because those can contain transport
credentials; status, severity and correlation remain available, and the application keeps its original errors.

For separate AI SDK calls inside recorded requests, add `vercelAI: 'scoped'` at startup and use
[`aiTelemetry`](https://docs.impact.ai/sdk/javascript/integrations#select-individual-ai-sdk-calls) at those calls. Other automatic
integrations are disabled on this path to avoid duplicating Mastra's own model capture.

### Use Impact-managed Observability on a shared provider

Mastra needs one preparation before the application constructs its OpenTelemetry provider, followed by native
startup against that provider. Pass the same `content` policy accepted by root `init()` when categories must be
omitted from Mastra native spans and the tool-schema supplement. `callsites` likewise accepts the configured absolute
application root and immutable source basis for relative automatic locations:

```js theme={null}
import { prepareMastraIntegration } from 'impact-ai/mastra';

const impactMastra = await prepareMastraIntegration({ serviceName: 'agent', connection: {} });
const tracerProvider = new TracerProvider({
  spanProcessors: [...impactMastra.spanProcessors, ...customerSpanProcessors],
});
const runtime = await impactMastra.start({ tracerProvider });
if (!runtime) console.warn(impactMastra.status());
const mastra = new Mastra({ observability: impactMastra.observability, agents });
// At the host's actual completion boundary, after application work has drained:
await impactMastra.shutdown();
```

`connection: {}` resolves the configured Product key before the customer's provider is constructed. Its Traces grant
is required for this capture helper. The explicit direct OTLP form `{ serviceName, endpoint, apiKey }` remains
synchronous for existing ingestion-only keys. `enabled: false` performs no connection discovery or capture setup.
`start()` returns the same active runtime that owns this prepared destination. Disabled or unsuccessful startup
returns `undefined`. Inspect `impactMastra.status()` and keep native application startup independent. A shutdown
racing startup likewise returns no active handle. An equivalent repeated start shares the same attempt and handle.

### Use Simulation or Protect with Mastra

The simple path exposes `capture.runtime`; the advanced shared-provider path returns its runtime from `start()`.
Use that same runtime for Simulation or Protect, without another `init()` call:

```js theme={null}
const runtime = await impactMastra.start({ tracerProvider });
if (runtime) {
  const target = await runtime.registerSimulationTarget({
    effects: { boundary: 'simulated' },
    invoke: (request, execution) => runExistingApplication(request, execution),
  });
  // Activate Protect separately only when deliberately selected for this application.
}
```

The Product key must have each requested grant. Registration/activation does not establish readiness or enforcement.
Simulation/Protect-only applications use ordinary root initialization and its returned runtime.

When a Simulation callback invokes the application's existing Mastra HTTP handler, the SDK can consume its
native SSE result directly:

```ts theme={null}
import { consumeMastraResponse } from 'impact-ai/mastra';

// Inside the registered invoke callback, after app-owned effect/resource checks:
const response = await invokeAuthenticatedApplication(request, signal);
return consumeMastraResponse(response, { signal, emit });
```

This explicitly reads the body and returns `{ text }` after native `stop`, `[DONE]` and EOF. In the assembled
result, recognized credential-bearing URLs become `[credential-bearing URL omitted]`, including when split across
text deltas. The original HTTP/SSE response is unchanged; general Simulation callbacks keep their own result contract.
The helper forwards only observed tool IDs, names and result/error status to `emit`. It rejects incomplete,
failed and over-limit results, and cancels its reader on abort or failure. The result limit is 512 KiB; framing,
total inspected bytes and observation time are bounded too. Authentication, history/state mapping, allowed
effects and Simulation transport remain with their existing owners. When invoking `capture.request` inside this
callback, forward the Simulation request's `interactionId`, `sessionId` and verified `user.id` explicitly.

### Keep your own Observability

The managed path implements Mastra's public bridge contract directly on the current OpenTelemetry API, creates its
Observability instance, and uses an Impact-owned private logger route for
the bounded tool-schema supplement. It does not register, flush, or stop the customer tracer provider. An application
that supplies its own `Observability` passes it to `start`. The handle exposes it unchanged and does not manage its
lifecycle. Use the public preparation's bridge factory for that native configuration. No private package imports or
span-discard callback are required:

```js theme={null}
import { context as callerContext } from '@opentelemetry/api';

const impactMastra = await prepareMastraIntegration({ serviceName: 'agent', connection: {} });
const tracerProvider = new TracerProvider({
  spanProcessors: [...impactMastra.spanProcessors, ...customerSpanProcessors],
});
const loggerProvider = new LoggerProvider({
  processors: [...impactMastra.logRecordProcessors, ...customerLogProcessors],
});
const bridge = await impactMastra.createBridge({
  tracerProvider,
  loggerProvider,
  contextApi: callerContext, // The same app API used to register its context manager.
});
// This native config has no bridge yet; keep its existing exporters, filters and policies.
const observability = new Observability({
  ...existingObservabilityOptions,
  configs: {
    customer: {
      ...existingCustomerConfig,
      ...(bridge ? { bridge } : {}),
      spanOutputProcessors: [
        ...(existingCustomerConfig.spanOutputProcessors ?? []),
        ...impactMastra.spanOutputProcessors,
      ],
    },
  },
});
// start inherits the selected context owner; it need not be supplied twice.
const runtime = await impactMastra.start({ tracerProvider, loggerProvider, observability });
const mastra = new Mastra({ observability, agents });
```

Native Observability selects one configuration per trace. Multiple configs are not parallel routes. Attach this bridge
to the existing selected config while preserving its exporters and policies. If it already has a bridge, retain that
customer component instead of replacing it implicitly. Native filters apply to bridge capture too: an inference or
content category suppressed by the caller remains unavailable to this route. The SDK does not bypass native policy.

`contextApi` is the caller's public structural API with `active()` and `with(context, callback, thisArg?, ...args)`.
It defaults to Impact's API. Supply the API that owns the application's registered context manager when API versions
differ, such as the API 1.9.1/provider 2.11 customer tuple. This lets bridge parent lookup, callback execution and
schema-log correlation use that same owner. It does not replace a global manager or provider. Explicit native parent
overrides still apply. Factory and `start()` share one owner: omission inherits the selection, while an explicit
conflicting owner is rejected before activation. SDK-managed startup may select it through `start({ contextApi, ... })`.

If a request trace and its Agent appear disconnected, verify this public owner selection and inspect the actual
incoming/request/native parent IDs. Do not rewrite trace IDs or infer parentage from a matching Session. Supply
per-request `interactionId`/`sessionId` and verified `userId` through `impact.context` from the application's verified scope. These logical
fields use a separate scope and do not reparent spans or overwrite an earlier HTTP wrapper's metadata. This explicit
bridge path does not establish context propagation for unrelated instrumentation owners.

### Lifecycle and troubleshooting

The factory takes public provider APIs and returns a caller-owned native bridge. It returns `undefined` for an inert,
unavailable or closed helper and loads no native owner in that case. Use the same providers for the factory and
`start()`. If `loggerProvider` is omitted, bridge logs use the helper's selected logger only after startup. Native
work before `start()` reaches the caller's own telemetry, while the Impact destination remains inactive.

`runtime.shutdown()` and `impactMastra.shutdown()` join the same Impact cleanup. They stop the SDK-owned destination
and schema supplement and, on the managed path, the SDK-owned bridge/Observability. They never stop the caller-owned
bridge, Observability or providers in the advanced path. Those native components can continue customer telemetry.
At the application's completion boundary, the caller flushes/shuts down its Observability and providers.
Native filtering completes the associated observation without exporting a suppressed span.

The same handle is safe to shut down before or after startup. `enabled: false` or `IMPACT_ENABLED=false`, and wholly
absent direct endpoint/key configuration, leave it inert with empty processor arrays. Direct preparation and
operational startup failures return a diagnostic through `impactMastra.status()`. Product-key discovery failures return
an unavailable preparation with no processors or hooks. `start()` returns no runtime. Repair the connection and prepare
again explicitly. Malformed API arguments and conflicting repeated startup calls remain errors. Status is
`disabled`, `prepared`, `starting`, `active`, `unavailable` or `shutdown`. `status().impact` contains root runtime facts
only when that runtime exists. Read the discriminant before using those facts. An unavailable Mastra bridge can leave
other Impact capture active. The helper does not take over application shutdown ordering.

### Captured Mastra fields

The Mastra bridge preserves native outcome and stop reason when supplied. It omits native-internal and excluded work,
and visible children use the closest exported ancestor. Inference inputs are limited to the native preview. Generation
spans retain the available native messages and any native tool definitions under the input policy. Per-inference tool
definitions require their own native observation. Tool proposals retain IDs, names and arguments under the applicable
content policy, with opaque provider metadata excluded from Impact copies. Executed tools retain their own spans.
Mastra response headers retain only recognized noncredential diagnostics, such as request IDs.
Generation tool definitions describe that generation's offer, not the effective validator after a step-local
tool replacement. The Mastra 1.60 path does not expose that validator with the execution span before
validation. Argument validation remains unchecked when that evidence is unavailable, including refusals before effects.
An explicit enclosing `impact.span` can record the application's delivered Workflow result when that adds useful context.

The catalogue also lists Mastra core `1.82.0` with Observability `1.23.2-alpha.0`. For the Bun `1.3.14`
Agent path, preserve a peer-consistent hoisted lock: the app uses OpenTelemetry API `1.9.1`, while Impact's
exporters resolve API `1.10.0`. Clean npm installation and the selected application's frozen Bun lock provide
that layout. A fresh Bun hoisted solve can misplace those peers; isolated linking can instead create duplicate
native TypeScript class identities. Those install layouts are not substitutes for the verified graph.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.