> ## 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 API and application context

> Group native operations into real requests, carry context between services, and manage the SDK runtime.

Use the public root functions to describe application work. The runtime returned by `init()` manages Impact
capture and explicitly selected capabilities. See [application setup](https://docs.impact.ai/sdk/javascript/setup.md) for lifecycle
and OpenTelemetry ownership.

## Public API

| API | Purpose |
| - | - |
| `init(options)` | Starts one compatible runtime and activates available optional integrations. Equivalent concurrent calls converge. Conflicting settings reject. |
| `initMastra(options)` from `impact-ai/mastra` | Creates private Impact capture for native Mastra Observability, with a request boundary and owned cleanup. |
| `consumeMastraResponse(response, options?)` from `impact-ai/mastra` | Explicitly consumes a native Mastra SSE response into a bounded Simulation-compatible result. |
| `aiTelemetry(operation, options?)` from `impact-ai/vercel-ai` | Selects an AI SDK call when initialized with scoped capture, preserving existing native telemetry settings. |
| `createOtlpDestination(options?)` | Prepares an SDK-owned bounded OTLP trace/log destination for a customer provider. `init({ tracerProvider, destination })` activates and owns it. |
| `interaction(options, work)` | Owns one logical request and observes its actual supported completion boundary. |
| `continueInteraction(transferCarrier, work)` | Continues explicitly transferred completion ownership. Ordinary contributor context is insufficient. |
| `context(value, operation)` | Applies validated async-scoped Product context without changing process-wide values. |
| `span(name, options, operation)` | Captures an explicit application boundary while preserving its synchronous result, native Promise result or original error. |
| `wrap(name, options, operation)` | Creates a reusable function wrapper with the same manual span behavior. |
| `injectContext(carrier)` / `extractContext(carrier)` | Encodes or validates contributor context and native W3C context on application-owned carriers. |
| `feedback(input)` | Records [Feedback](https://docs.impact.ai/sdk/feedback.md) with a stable occurrence identity. |
| `runtime.attachRealtime(connection, options)` | Observes an existing server-side OpenAI Realtime connection. The application retains the socket. |
| `runtime.observeRealtime(observation, options)` | Records a browser-forwarded Realtime control event using server-selected connection identity. |
| `observeRealtimeDataChannel(channel, options)` from `impact-ai/realtime-events` | Observes a browser-owned JSON control channel through a callback or bounded authenticated batch delivery. |
| `runtime.status()` | Reports local integration owners, limitations, queues, exports, loss and cleanup state. |
| `runtime.flush()` | Makes a bounded attempt to export finished telemetry. It does not prove platform admission or readback. |
| `runtime.shutdown()` | Flushes and stops SDK-owned work. A safe retry continues only incomplete cleanup phases. |
| `runtime.registerSimulationTarget(options)` | Registers a [Simulation target](https://docs.impact.ai/sdk/javascript/simulation.md) for an existing application entry point. |
| `runtime.activateProtect(options)` | Starts the explicitly selected [Protect runtime](https://docs.impact.ai/sdk/javascript/protect.md). |

Use `impact-ai/register` as the [managed ADK preload](https://docs.impact.ai/sdk/javascript/integrations.md#google-adk) when it fits
your startup. Use `impact-ai/otel` for [application-owned destinations](https://docs.impact.ai/sdk/javascript/setup.md#manage-the-destination-yourself).
`impact-ai/mastra`, `impact-ai/realtime-events`, and `impact-ai/openai-x509` expose the corresponding native helpers.

## Group work into an Interaction

Use one `interaction(options, work)` around a real application request. It preserves the ID you supply or
generates one at that boundary. Plain initialization, context, model calls, and manual spans leave Interaction
identity unchanged. A Session is an optional conversation or coherent job. A Product User key is an opaque
application identifier taken from the application's verified request scope. The application supplies the key
and verifies the user. Route credentials establish Workspace and Product tenancy. You can attach a Session
without an Interaction, and stopping telemetry leaves the business conversation active.

The emitted attributes are `impact.interaction.id`, `impact.session.id`, and `impact.user.id`.
Their scope is the authenticated Product, independent of the ingest key or Source.

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

const runtime = await impact.init();
const { default: OpenAI } = await import('openai');
const client = new OpenAI();
try {
  const answer = await impact.interaction(
    {
      sessionId: 'conversation-1',
      interactionId: 'request-42',
      userId: 'customer-17',
      name: 'answer',
      input: { question: 'Where is my order?' },
    },
    async () => {
      const result = await client.responses.create({
        model: process.env.OPENAI_MODEL ?? 'gpt-6.1-sol',
        max_output_tokens: 512,
        reasoning: { effort: 'low' },
        input: 'Explain how a customer can find their order status.',
      });
      return result.output_text;
    },
  );
  console.log(answer);
} finally {
  await runtime.shutdown();
}
```

Nested work inherits correlation without ending the request. The wrapper preserves native results and errors. It
observes supported synchronous and asynchronous iterators when they exhaust, close, or fail.
Opaque HTTP responses, ReadableStreams and unfamiliar protocol objects have unobserved completion. Use the actual
application drain/close boundary rather than treating the handler's return as completed streaming work. When terminal
observation is needed for a unary native APIPromise, await it inside the owning callback. A returned native stream
that only exposes an iterator factory can still leave completion unobserved. Consume it inside the owning callback
when the application's completion boundary includes that consumption.

For the documented local Mastra/Hono SSE route, `initMastra().request()` observes the consumed response through
the SDK adapter. Its completion requires native terminal evidence and consumed EOF. This does not extend completion
observation to arbitrary HTTP responses or streams. See [Mastra setup](https://docs.impact.ai/sdk/javascript/integrations.md#mastra).

## Continue work after a queue handoff

For queue work, explicitly hand completion to one application continuation after the native publisher confirms
acceptance. Contributor propagation alone cannot transfer ownership:

```js theme={null}
await impact.interaction({ sessionId, name: 'answer', input: question }, async (request) => {
  await request.handoff(async (transfer) => {
    await queue.publishConfirmed({ question, context: transfer.carrier });
    transfer.confirm(); // Only after this application's actual accepted/durable publication boundary.
  });
  return acceptedResponse();
});

await impact.continueInteraction(job.context, () => agent.answer(job.question));
```

`queue.publishConfirmed`, `acceptedResponse` and the queue envelope above belong to the application. A buffered write
or an arbitrary returned object is not confirmation. `confirm()` is scoped to the active publishing callback and is
one-way. No confirmation leaves the request incomplete. A confirmed transfer is not undone by a later local error
or telemetry failure, and Impact never retries business work. Only the explicit transfer carrier can continue an
owner. A transfer without a Session continues without one, even if the receiver's scope has a Session. Parallel
branches receive contributor context. One real application join retains or receives completion.
The application handles authorization and recovery, including any distributed guarantees for its business effects.

## Add manual spans

`span()` never invokes the application callback twice. Result classification does not invoke `then`, `next`, iterator
accessors, or proxy traps. When those protocol properties cannot be inspected without running application code, the
original value is returned unchanged and terminal/output observation is marked unavailable. A safely identified custom
thenable is likewise returned untouched with its terminal output unobserved. Serialization loss is marked partial or
omitted and never replaces the application result.

Manual `span()` and Interaction input/output capture each contain one JSON document with `application/json` MIME. Decode that captured value once. JSON `null`, `false`, `0` and empty text (`""`) remain distinct, and text that looks like
JSON remains text. An absent value, a closed content state or a missing value/MIME pair is unavailable, not an empty or
null result.

## Propagate context between services

`injectContext()` combines initialized defaults with the current scope and writes W3C `traceparent`/`tracestate`
plus one bounded `impact-context` entry. The latter is canonical UTF-8 JSON encoded as unpadded base64url, containing
version 2, optional `interactionId`, `sessionId` and `domainRun`. User attribution is not automatically propagated.
Identifiers are nonempty well-formed strings of at most 1,024 UTF-8 bytes. The encoded owned entry is at most
8,192 bytes. A malformed or conflicting existing entry rejects atomically: the entire carrier remains unchanged.
Use a fresh carrier per request, including when the current scope has no logical IDs.

`extractContext(carrier)` is pure and returns `{ context, nativeContext, issues }` plus a validated transfer when
present. Apply contributor context with `impact.context({ propagated: impact.extractContext(headers) }, work)`.
Malformed inbound correlation produces content-free diagnosis rather than a fabricated request. Explicit local
identity cannot silently disagree with received identity. Received data never selects tenancy or overrides local
user attribution. An existing application-owned native parent is preserved. For an application using a different
OpenTelemetry API registry, pass its public context owner once as `init({ contextApi: callerContext })`. Helpers use
that owner's `active` and `with` methods without replacing a global manager or provider.

Create the gateway carrier inside each actual request's active span and pass it through the application's existing
per-request header option, for example `fetch(gatewayUrl, { ...requestOptions, headers: impact.injectContext({}) })`.
Keep native credentials and other request options under application control. Plain injection contributes correlation. It does not transfer completion ownership or install an HTTP patcher.

## Add deployment and application context

`context` and `span` add information without being required for automatic provider capture. Set stable deployment
defaults with `init({ context: { environment, versionId, componentId, buildId, deploymentId } })` when those values are known.

`environment` reports the deployment environment name (`deployment.environment.name`), not an authenticated
Environment UUID. `versionId` reports the deployed application version/ref (`impact.product.version.id`), such as the
actual release reference or Git commit used by the build. Its spelling does not make the value a canonical Builder
Version UUID. Supply real configured values or leave them unknown. Do not use a library version or model name to
stand in for a deployment.

`componentId`, `agentId` and `agentVersionId` are reported application keys. `buildId` and `deploymentId` are reported
external build/deployment references, for example actual CI or hosting IDs. These fields do not establish a Builder
Part, Version or Deploy relationship. Native provider model, agent, and session IDs describe separate provider facts.

Route credentials establish Workspace and Product tenancy. Context values are correlation claims. Keep reported environment/version/component/build/deployment metadata,
Session, Interaction, purpose, Product User and
`domainRun: { kind, id }` distinct. A Simulation run ID and a technical invocation ID remain distinct from the Interaction and Session IDs.

Optional typed context fields `channel`, `locale`, `plan`, `userType` and `journeyStep` emit
`impact.correlation.channel`, `.locale`, `.plan`, `.user_type` and `.journey_step`, respectively. They accept
non-empty, well-formed strings of at most 1,024 UTF-8 bytes without NUL. They do not prescribe a vocabulary or infer
values. Stable defaults may be supplied in `init({ context: ... })`. Within one context, a typed field wins over its
exact canonical `custom` key. An inner scope wins over outer/default values, including an inner custom value.
Existing custom-only values keep their validation and omission behavior. `agentVersionId` continues to emit
`impact.agent.version.id` separately from the reported deployed `versionId`.

Supply a known terminal Session fact on the actual terminal operation, before its span or automatic owner starts:

```ts theme={null}
await impact.context(
  {
    sessionId: 'conversation-1',
    journeyStep: 'complete',
    sessionEnding: 'resolved',
  },
  () => impact.span('finish-conversation', { role: 'entry' }, finishConversation),
);
```

`sessionEnding` emits the raw `impact.session.ending` attribute and requires `sessionId` in the same submitted
context. It is rejected in init defaults. Nested work inherits it for the same Session. Changing the Session clears
the inherited ending unless that scope supplies a new pair, and leaving the scope restores the outer pair.
Use application-owned native trace parentage to keep the terminal operation under its intended Session. Changing
context leaves existing trace parentage intact. This field records the supplied fact, does not close
a Session or alter inferred Ending classification, and offers no post-hoc ending API. Verify the terminal span's raw
attribute through authenticated Trace readback under that exact Session. These typed fields and the supplied ending
are not added to propagation headers or baggage.

`runtime.status().runtimeId` identifies this initialized SDK runtime. Impact-created evidence and Impact-routed copies carry
the same `impact.runtime.id` plus `impact.sdk.version`. There is no caller-settable `context.runtimeId`. Customer
records remain unchanged. Source references use `code.file.path`, `code.function.name`, `code.line.number`,
`impact.source.basis.id` and `impact.source.observed.at`. `custom` values use `impact.correlation.*`.
Execution provenance uses `impact.execution.origin`, `impact.execution.input.reference` and distinct
`impact.<evaluation|dataset|case|experiment|replay>.id` attributes, matching Python. These supplied source/business
facts do not grant authority or trigger source inspection.


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