> ## 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.

# Activate Protect in JavaScript

> Configure Protect explicitly, understand native enforcement limits, and manage Decision delivery.

Protect evaluates native application work against explicitly enabled policies. Check runtime execution, Decision
delivery, and readable Product evidence separately. Confirm enforcement on your actual host and native
operation within the compatibility boundaries below.

Protect `executionId` identifies a technical operation or actual command. It is independent of logical `interactionId`,
`sessionId` and verified `userId`. Native provider checks snapshot those associations locally alongside actual trace/span
identity. Command tests preserve their real command ID. These local association fields do not change the Protect HTTP Decision format. Product associates records through its receiver contract.

## Install the optional engine

Protect activation is explicit. Ordinary imports and `init()` do not load an encoder, initialize ONNX Runtime,
download weights or change provider decisions. Install the inference peers only for an application using Protect:

```sh theme={null}
ONNXRUNTIME_NODE_INSTALL=skip pnpm add onnxruntime-node@1.32.0-dev.20261105-527971bce @huggingface/tokenizers@0.2.0
# Or with npm:
ONNXRUNTIME_NODE_INSTALL=skip npm install onnxruntime-node@1.32.0-dev.20261105-527971bce @huggingface/tokenizers@0.2.0
ORT_DISABLE_TELEMETRY=1 node dist/main.js
```

`ONNXRUNTIME_NODE_INSTALL=skip` selects the bundled CPU binaries and skips optional CUDA/TensorRT downloads.
The native postinstall still runs. If pnpm requests native build approval, run
`ONNXRUNTIME_NODE_INSTALL=skip pnpm approve-builds` and select `onnxruntime-node` before starting the application.
Keep this setting on later native approval or rebuild commands for CPU-only installations.

On non-Windows systems, set `ORT_DISABLE_TELEMETRY=1` before any ONNX Runtime initialization. The lazy native loader
refuses initialization without it and does not change customer process settings or OpenTelemetry. Setting it after
another dependency initialized ONNX Runtime does not establish that the original initialization was protected.
The pinned build is available from npm, and the package also admits compatible application-owned `1.29.x` engines.
The documented CPU profile covers macOS ARM64. Windows ETW and native Windows behavior are unassessed.
[ONNX Runtime privacy](https://github.com/microsoft/onnxruntime/blob/main/docs/Privacy.md).

## Activate Protect

Enable the Product key's Protect grant, initialize the ordinary SDK, and activate Protect. Supply your existing
Builder Version UUID and a runtime label.

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

const runtime = await impact.init();
const protect = await runtime.activateProtect({
  versionId: 'd2719d8f-2332-4b53-9f42-2f88cf166362',
  runtimeLabel: 'support-worker',
});
console.log(protect.status());
```

Connection-v2 discovery supplies an HTTP(S) Protect origin and the authenticated Product/Environment. The SDK
connects to that origin's `/ws/sentinel` using Bearer authority and `X-Impact-Purpose: protect`. JavaScript also
permits explicit loopback HTTP/WS. Registration, exact configuration delivery, application acknowledgement,
health and useful protected work are distinct observations. A socket or model alone does not qualify enforcement.
The controller automatically reconnects and re-registers the same runtime identity, Version and label. Unchanged
configuration is acknowledged again without reloading its models. Public `close()` fences reconnects and joins the
owned control socket, native work and Decision outbox. The control socket gets one second for graceful closure,
then one second to confirm termination. Pending or failed transport/native cleanup retains the registration and
reports an error. Concurrent closes join one cleanup attempt. Retries continue only incomplete cleanup.

Select a customer-runner Environment with its actual UUID.

```ts theme={null}
const protect = await runtime.activateProtect({
  environmentId: '5b8e0c3a-7d41-4f2e-9c6a-1e2f3a4b5c6d',
  versionId: 'd2719d8f-2332-4b53-9f42-2f88cf166362',
  runtimeLabel: 'support-worker',
  reportScores: true,
});
```

Select an existing canonical Builder Version UUID with Protect’s explicit `versionId`. The server resolves its digest. Caller-supplied `versionDigest` values
are unsupported and refuse before discovery or activation. Protect's Version option is separate from the reported
context `versionId`/`IMPACT_VERSION_ID`: release labels and commits are not substituted for this formal UUID. Omitted Version input
cannot qualify a Version-specific runtime. Presence and Trace export retain their base discovery Environment.
Labels are trimmed, valid text of 1–120 UTF-16 units without controls. Equivalent activation options reuse one
registration and conflicting options are rejected.

## Configure models and scores

`reportScores` defaults to false. Opt-in HTTP Decisions include a finite 0–1 score, including zero.
Unavailable checks omit the score. Native raw threshold/PCA and the pinned Arctic XS/S/M/L pipeline-2 catalogue remain the
inference basis. The controller downloads immutable classifier references from its same origin, verifies declared
size/hash and supported media type, and uses bounded model acquisition only when an applied Policy needs a model.
Set `modelDirectory` or `IMPACT_PROTECT_MODEL_DIRECTORY` to choose the cache. Optional `modelIds` restrict the delivered
model. Otherwise the native catalogue can serve the delivered model. Use `encoderInstalls` to reuse existing verified files.

```ts theme={null}
const protect = await runtime.activateProtect({
  versionId: 'd2719d8f-2332-4b53-9f42-2f88cf166362',
  encoderInstalls: [
    {
      modelId: 'arctic-xs',
      modelPath: '/srv/protection/arctic-xs/model.onnx',
      tokenizerPath: '/srv/protection/arctic-xs/tokenizer.json',
    },
  ],
});
```

## Apply and renew a policy

Each runtime applies only its own exact `configSequence`/`configRevision` and Policy/artifact tuple. A selected
runtime may adopt newer material while another retains its original material until its own adoption. Off removes
its applied on Policies without acquiring a new model. An expiry renewal keeps the same sequence and revision. A higher
sequence may carry the same revision when its configuration body matches. Stale sequences and changed material
under a retained revision are refused. Failure, expiry and partial state remain visible. Expiry follows the captured unavailable
posture: Enforce blocks unless explicit `allow_and_record`. Monitor preserves native work and records unavailable
checks. An occurrence or stream reports against its own captured configuration even when it settles after a later
adoption.

## Protect native OpenAI calls

Use the documented native OpenAI Chat Completions path. Input enforcement
precedes its one checked native send. Output enforcement does not repeat it. Applied Off and Monitor preserve
the client's configured retries, native results, metadata, errors, lazy streams, backpressure and caller cancellation. Original requests/readers/iterator returns
stay retained until their actual cleanup joins. After interruption, only proven caller cancellation retains its native
error and exact caller reason. A later caller abort does not change an SDK interruption into caller cancellation.
Configured unavailable blocking fences withdrawn protected release. Pending or failed cleanup is an error and does
not prove resource completion. Customer transport clients remain
caller-owned. Pending unary Monitor and explicit `allow_and_record` calls finish normally during shutdown, with
captured `runtime_closed` unavailable Decisions. Shutdown retains their real join. Required Enforce/block still fences
release. Check other adapters separately for their available operation boundaries.
For OpenAI output Enforce, an unread raw response cannot be claimed as checked: `asResponse()` follows the captured
unavailable posture. Combined and derived helpers retain response metadata alongside checked output without
exposing an unchecked duplicate body. Off and Monitor keep the native raw path.

## Handle capacity and Decision delivery

Protect retains at most 32 active native requests. At that limit, Monitor and explicit `allow_and_record` preserve the
next application-owned call without adding request hooks or read custody. The completed input Decision keeps its
original occurrence and body. The future output check is reported unavailable before that native send, against its
captured Policy configuration. No later native body check or SDK join is claimed. Required Enforce/block refuses
unavailable send admission before the provider effect. Shutdown joins the retained cohort within its deadline while
unretained application work may continue.

The Decision format requires a digest even when that future output is unknown. These reports use the exact
`unavailableBasis` value `provider_retention_unavailable:output_body_unavailable:proposed_digest_placeholder` with
unavailable check/effect, no score and the required SHA-256 of an internal empty placeholder. Treat the body as unknown whenever the marker is present.

Native Decisions use the original authenticated HTTP `/v1/protect/decisions` endpoint and bounded outbox. Retry keeps
the same occurrence and body and never repeats a provider call or rescoring. `flush()` and shutdown make bounded
attempts. Status retains pending, failed-attempt and lost counts. Native Decision reports contain digests, lengths,
exact provenance and effects, not released/proposed plaintext. `protect_test` commands and
`protect_test_result` replies remain on the control socket. A missing genuine enforcement callback is unavailable,
not a successful provider Test. Process exit can lose in-memory unacknowledged Decisions. Use Product readback to confirm the same occurrence.

## Use the OpenAI x509 transport

For a Node application that explicitly owns its static certificate transport, use the advanced entry point:

```ts theme={null}
import { createProtectedOpenAIX509Transport } from 'impact-ai/openai-x509';

const transport = await createProtectedOpenAIX509Transport({ certificateChain, privateKey, ca });
```

Call its `createClient()` with native OpenAI options including
`workloadIdentity: { type: 'x509', identityProviderId, serviceAccountId }`. This method returns the actual native OpenAI client and privately binds its
original transport. Passing only `x509Transport` into a separately constructed
client does not issue this proof. Its protected calls remain unavailable. The
application calls the returned `close()` to drain or `destroy()` to interrupt and
join that transport. Protection runtime shutdown never closes an application
transport shared by ordinary calls. Certificate/key matching and target TLS
verification are mandatory. HTTP/HTTPS CONNECT can be selected through `proxy`,
with separately trusted proxy `ca`. Optional native `lookup` or `socketPath`
routing retains verification of the original target authority. No arbitrary
agent, factory, connector or TLS-verification bypass is accepted.

Install `undici@7.30.2` alongside the application's OpenAI client for this optional transport.
[Undici security release](https://github.com/nodejs/undici/releases/tag/v7.30.1)

This explicit OpenAI 7.10.0 / Undici 7.30.2 constructor route compares complete final
Chat/Responses JSON before model dispatch, retains one original model send, and
aborts/joins its complete response on interruption. Its absolute model deadline
is `requestTimeoutMs` (default ten minutes, maximum ten minutes), with a 16 MiB
request/response limit. Native token exchange remains separate, with a five
second complete-response deadline and a 64 KiB unencoded credential response
limit. Token, certificate and private-key bytes are not reported or fingerprinted.
For other native clients, a detached data-only request destination at the reserved
mTLS authority is refused before authentication, even if mutable auth metadata
has been erased. This uses the pinned native pre-auth destination rule, not an
inferred private authentication state. Dynamic request destinations are unavailable.
The owned `workloadIdentity.fromX509` retrofit remains unavailable. Hosted identity enrollment and whole-route support are unassessed.


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