# @sentisec/sdk

TypeScript SDK for Sentisec — cognitive integrity monitoring for autonomous
agents. Wraps OpenAI and Anthropic clients so every agent request flows
through Sentisec's staged monitoring pipeline, with streaming support via
SSE passthrough.

[![npm version](https://img.shields.io/npm/v/@sentisec/sdk)](https://www.npmjs.com/package/@sentisec/sdk)
[![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

---

## Install

```bash
npm install @sentisec/sdk
# or
pnpm add @sentisec/sdk
```

Requires Node 20+.

---

## Choose your control plane first

> **Warning — an unset endpoint means production.**
> `new Monitor({ ... })` with no `endpoint` sends every wrapped request
> to the hosted plane at `https://api.sentisec.ch`. If you are running
> Sentisec locally or self-hosted and you skip this, your prompts leave
> your machine. Set it explicitly; the SDK cannot infer your intent.

Resolution order, highest first:

1. `wrap(client, { baseUrl })` — a literal, fully-formed URL for one
   wrap call. Nothing is appended to it.
2. `new Monitor({ endpoint })` — a control-plane **host**; the SDK
   appends `/ws/<workspace>/v1` (OpenAI) or `/ws/<workspace>` (Anthropic,
   whose client adds `/v1/messages` itself).
3. `SENTISEC_ENDPOINT` — same host semantics, from the environment.
4. the hosted default, `https://api.sentisec.ch`.

```bash
# Local or self-hosted: set this once and both SDKs obey it.
export SENTISEC_ENDPOINT=http://localhost:8080
```

The Python SDK also supports `SENTISEC_ENDPOINT`, but resolves saved
credentials and uses different proxy paths; see the feature table below.

**`wrap()` replaces your client's `baseURL`.** That is what the wrapper
is for — traffic has to go through Sentisec to be gated. But if your
client already pointed at Azure, a local vLLM, or another gateway, that
destination is discarded, and the SDK prints a one-line warning naming
the remedy. Route the upstream through Sentisec rather than setting it
on the client.

---

## Quick start — OpenAI (non-streaming)

```ts
import OpenAI from "openai";
import { Monitor, SentisecHijackError } from "@sentisec/sdk";

const monitor = new Monitor({
  apiKey: process.env.SENTISEC_API_KEY!,
  model: "gpt-4o",
  task: "summarise today's security advisories",
  policy: "research_agent",
  responsePolicy: "gated",
  customerId: "ws_acme",
  // Explicit on purpose — omit it and this snippet targets the hosted
  // plane. Point it at your own control plane when self-hosting.
  endpoint: process.env.SENTISEC_ENDPOINT ?? "https://api.sentisec.ch",
});

// Wraps the OpenAI client in place — type is preserved.
const openai = monitor.wrap(new OpenAI({ apiKey: process.env.OPENAI_API_KEY }));

try {
  const completion = await openai.chat.completions.create({
    model: "gpt-4o",
    messages: [{ role: "user", content: "Summarise CVE-2024-12345." }],
  });
  console.log(completion.choices[0]?.message.content);
} catch (err) {
  if (err instanceof SentisecHijackError) {
    // Proxy issued a HALT verdict — the agent was attempting something
    // outside its declared task scope.
    console.error("HALT", err.sessionId, err.detail);
  } else {
    throw err;
  }
}
```

---

## Quick start — Anthropic (non-streaming)

```ts
import Anthropic from "@anthropic-ai/sdk";
import { Monitor, SentisecAnthropicBlockError } from "@sentisec/sdk";

const monitor = new Monitor({
  apiKey: process.env.SENTISEC_API_KEY!,
  model: "claude-3-5-sonnet-20241022",
  task: "answer customer support tickets",
  policy: "customer_support",
  customerId: "ws_support",
  endpoint: process.env.SENTISEC_ENDPOINT ?? "https://api.sentisec.ch",
});

const anthropic = monitor.wrap(new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }));

const message = await anthropic.messages.create({
  model: "claude-3-5-sonnet-20241022",
  max_tokens: 1024,
  messages: [{ role: "user", content: "How do I reset my password?" }],
});

// Default (gated-return): on HALT the response contains a synthetic
// tool_use block with sentisec_blocked: true.
const lastBlock = message.content[message.content.length - 1];
if (lastBlock?.type === "tool_use" && lastBlock.name === "sentisec_block") {
  console.warn("Sentisec blocked this response:", lastBlock.input);
} else {
  console.log(message.content);
}

// Opt-in exception surface:
const anthropicThrow = monitor.wrap(
  new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }),
  { onBlock: "throw" },
);
try {
  await anthropicThrow.messages.create({ ... });
} catch (err) {
  if (err instanceof SentisecAnthropicBlockError) {
    console.error("HALT", err.sessionId, err.row, err.detail);
  }
}
```

---

## Streaming — OpenAI

```ts
import OpenAI from "openai";
import { Monitor, wrapOpenAIStream } from "@sentisec/sdk";

const monitor = new Monitor({
  apiKey: process.env.SENTISEC_API_KEY!,
  model: "gpt-4o",
  task: "code review",
  policy: "coding_agent",
  customerId: "ws_eng",
});

const openai = monitor.wrap(new OpenAI({ apiKey: process.env.OPENAI_API_KEY }));

// Apply the streaming wrapper (separate from the non-streaming wrap).
const sessionId = "ses_0000000000000001"; // use your session id
const streamingClient = wrapOpenAIStream(openai, sessionId);

const stream = await streamingClient.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Review this diff..." }],
  stream: true,
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta.content ?? "";
  process.stdout.write(content);

  if (chunk.sentisec) {
    // Final chunk: what Sentisec said about the turn.
    console.log("\nVerdict:", chunk.sentisec.verdict, chunk.sentisec.session_id);
  }
}
```

The request carries what the client itself would send: its `apiKey`
(`Authorization: Bearer`; for Anthropic `x-api-key`, or `authToken` as a
Bearer), its `defaultHeaders` when it keeps a plain object of them, and the
call's own `options.headers`. A non-2xx answer throws `SentisecStreamError`
(`status`, `body`). `sentisec.verdict` on the last event is Sentisec's own
label for the turn (`NOMINAL`, `ELEVATED`, `SUSPICIOUS`, `HIJACK`), read
from its trailing SSE comment — `UNKNOWN` when it sent none, `ABORT` when
you aborted. `sentisec.approval`, when a call was held, lists the calls
still waiting (`pending`, with the handle `Approvals.resume` needs) and
those settled while the stream waited (`completed`).

AbortSignal support:

```ts
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000); // 5 s timeout

const streamingClient = wrapOpenAIStream(openai, sessionId, {
  signal: controller.signal,
});

for await (const chunk of await streamingClient.chat.completions.create({ ... })) {
  // On abort, last chunk has finish_reason: "session_closed"
  // and chunk.sentisec.verdict === "ABORT".
}
```

---

## Streaming — Anthropic

```ts
import Anthropic from "@anthropic-ai/sdk";
import { Monitor, wrapAnthropicStream } from "@sentisec/sdk";

const monitor = new Monitor({ ... });
const anthropic = monitor.wrap(new Anthropic({ ... }));
const streamingClient = wrapAnthropicStream(anthropic, sessionId);

const stream = await streamingClient.messages.create({
  model: "claude-3-5-sonnet-20241022",
  max_tokens: 1024,
  messages: [{ role: "user", content: "..." }],
  stream: true,
});

for await (const event of stream) {
  if (event.type === "content_block_delta") {
    const delta = event.delta as { type: string; text?: string };
    if (delta.type === "text_delta") process.stdout.write(delta.text ?? "");
    if (delta.type === "sentisec_halted") {
      console.warn("Mid-stream HALT:", delta);
    }
  }
  if (event.type === "message_stop" && event.sentisec) {
    console.log("Verdict:", event.sentisec.verdict);
  }
}
```

---

## When a tool call waits for approval

A workspace can hold a consequential tool call until a person approves it.
Three things can happen to the reply, and the first two need no code:

- **The reply waits for the decision.** The reply is held open for the
  workspace's window (45 seconds by default): a JSON reply sends `200` and
  its headers at once, a space about every 10 seconds, then the JSON; a
  stream sends its earlier frames, then an SSE comment about every 10
  seconds (every SSE client skips it). Approved inside the window, the
  call comes back in that same reply under the id `<call_id>_ib`; run it
  and answer it under that id. openai-node's own
  `timeout` stops counting once the headers arrive, so a plain client
  waits through it; a total deadline of your own (`AbortSignal.timeout`,
  a framework timeout) must be at least `HOLD_TIMEOUT_MS` (60 s).
- **The model is told the step is waiting.** Nobody decided in time (or a
  person declined): the call comes back renamed `sentisec_tool_call_blocked`
  with a plain-words `reason`. Nothing runs it: answer it with
  `blockedResults(response)` (a short fixed result Sentisec replaces with
  its ruling before the model reads it). The AI SDK and Mastra answer an
  unknown tool with their own tool error, which Sentisec replaces the same way.
- **The app finishes it later**, around one call:

```ts
import OpenAI from "openai";
import { Approvals, blockedResults, isBlocked } from "@sentisec/sdk";

const client = new OpenAI({ apiKey: KEY, baseURL: `https://api.sentisec.ch/ws/${WS}/v1` });
const approvals = Approvals.fromClient(client, { application: "refund-desk" }); // label optional

const result = await approvals.complete(
  (body, options) => client.chat.completions.create(body, options),
  { model, messages, tools },
  { sessionId: ticketId },                                   // optional
);
const message = result.response.choices[0].message;  // once approved, the call comes back released
messages.push(message);
for (const call of message.tool_calls ?? []) {
  if (!isBlocked(call)) messages.push(await runMyTool(call));   // your own tools
}
messages.push(...blockedResults(result.response));           // renamed calls, answered, never run
```

or inside `fetch`, for any fetch-based stack (openai-node, the AI SDK,
Mastra, LangChain.js) — the tool loop itself does not change:

```ts
const approvals = new Approvals({ apiKey: KEY, endpoint: "https://api.sentisec.ch" });
const client = new OpenAI({ apiKey: KEY, baseURL: `https://api.sentisec.ch/ws/${WS}/v1`,
                            fetch: approvals.fetch({ sessionId: ticketId, onPending: store }) });
```

`complete` reads a held reply to its end; when the answer still holds a
call, the helper reads its status with your key until a person decides
(15 minutes by default, `waitMs`), and once approved re-sends the same
request once with the `X-Sentisec-Continuation` header, so the call runs
exactly once. `result.outcome` says how it ended: `released` / `declined`
with `rung: "in_band"` (decided while the reply waited; `result.completed`
lists the calls), `approved_not_run` with `rung: "handle"` (re-sent),
`declined`, `lapsed`, `expired`, `revoked`, `released` (decided later,
nothing re-sent), or `waiting` (`waitMs` passed first). A re-send refused
with `409 continuation_refused` sets `refused` and returns the first answer.
Inside `fetch` the whole wait runs within one request, so the client's
deadline bounds it (openai-node's `timeout`, 10 minutes by default): when it
fires, the wait stops and the loop receives the held answer, nothing is
retried, and `onPending` has the offer. A ticket that ends first stores
`result.pending` (plain JSON) and later calls `approvals.resume(create,
pending, body)`. A held reply carries no `X-Sentisec-Approval` or
`X-Sentisec-Continuation` header; the helper reads `sentisec.approval` from
the body. The continuation travels only in a request header — never in a
message the model or your user sees; store a `PendingApproval` like a
credential for that one call.

Streams: the offer and the in-band completion ride SSE comments
(`: sentisec-verdict {...}`), which openai-node and @anthropic-ai/sdk skip.
Through `approvals.fetch()` a stream passes through unchanged and live; its
comments are read on the way, and a call still waiting when the stream ends
goes to `onPending` (finish it later with `approvals.resume(create, pending,
body)`). A call settled while the stream waited needs nothing: it is in the
stream under `<call_id>_ib`. `complete` reads JSON answers only (a stream
body throws a `TypeError` before anything is sent); `pendingFromSse`,
`completedFromSse` and `SseVerdicts` read the comments from raw text.

---

## Policies

Three built-in policy bundles ship with Phase 1:

| ID | Use case |
|---|---|
| `research_agent` | Web-access agents doing research and summarisation |
| `customer_support` | Support-ticket agents with constrained tool access |
| `coding_agent` | Code-review and generation agents |

Custom policies:

```ts
const monitor = new Monitor({
  // ...
  policy: "./policies/my-custom-policy.yaml",
});
```

---

## Features and Python SDK differences

The TypeScript SDK and the Python package `sentisec-sdk` expose different
APIs. Choose the integration for your language; they are not drop-in
replacements for each other.

| Feature | TypeScript (`@sentisec/sdk`) | Python (`sentisec-sdk`) |
|---|---|---|
| Provider wrappers | `monitor.wrap(client)` dispatches to OpenAI or Anthropic and returns the same client. | `monitor.wrap_openai(client)` and `monitor.wrap_anthropic(client)` return the same client. |
| Proxy destination | Appends `/ws/<customerId>/v1` (OpenAI) or `/ws/<customerId>` (Anthropic) to the endpoint host; `wrap(client, { baseUrl })` overrides the complete URL. | Appends `/v1/proxy/openai` or `/v1/proxy/anthropic` to the endpoint host. |
| Configuration | `apiKey`, `model` and `task` are required constructor fields; `customerId` defaults to `cust_local`. Endpoint precedence is wrap override, constructor, environment, hosted default. | Resolves credentials from explicit arguments, environment and saved profiles; the endpoint falls back to the hosted default. |
| Response handling | OpenAI HALT responses raise `SentisecHijackError`. Anthropic returns a synthetic block tool-use response by default, or raises `SentisecAnthropicBlockError` with `onBlock: "throw"`. | Thin wrappers rewrite the destination and API key; response handling remains with the provider client. |
| Streaming | Separate `wrapOpenAIStream` and `wrapAnthropicStream` helpers expose Sentisec's verdict label and held calls on the last event, and AbortSignal support. | Thin wrappers leave the provider client's streaming interface in place; no matching Sentisec streaming helpers are exported. |
| Calls held for approval | `Approvals`: `complete` / `resume` around a call, or `approvals.fetch()` for fetch-based stacks. | `Approvals`: `complete` / `resume`, sync and async. |
| Session lifecycle and forensic export | `Monitor.session()`, `Session.wrap()` and `Session.exportForensicBundle()` are reserved methods that currently throw. Use `Monitor.wrap()` for provider calls. | Exports a frozen `Session` record; `Monitor` has no session lifecycle or forensic export methods. |

Matching type names do not imply feature parity between the distributions.

---

## Develop

```bash
pnpm install                         # from repo root
pnpm --filter @sentisec/sdk build    # tsup → dist/
pnpm --filter @sentisec/sdk typecheck
```

Node 20+ and pnpm 9+ required.

---

## License

Apache-2.0. See [LICENSE](./LICENSE).
