# Advanced Topics

This page collects the deeper operational and debugging features of the TypeScript SDK.

## Advanced Request Options

Use `explain`, `debug`, `optimize`, `dryrun`, `early_exit`, and `contexts` for debugging, profiling, and context-aware detection:

```typescript
const explainResp = await client.guard.evaluate({
  content: userInput,
  content_type: "prompt",
  action: "process_prompt",
  explain: true,
});
console.log(explainResp.explanation);
console.log(explainResp.root_causes);
console.log(explainResp.tiers_evaluated);
console.log(explainResp.projected_context);

const debugResp = await client.guard.evaluate({
  content: userInput,
  content_type: "prompt",
  action: "process_prompt",
  debug: true,
});
for (const d of debugResp.detectors ?? []) {
  console.log(`${d.name}:`, d.context);
}

const optimizedResp = await client.guard.evaluate({
  content: userInput,
  content_type: "prompt",
  action: "process_prompt",
  optimize: true,
});
console.log(optimizedResp.optimization?.required_detectors.length, "detectors ran");

const dryrunResp = await client.guard.evaluate({
  content: userInput,
  content_type: "prompt",
  action: "process_prompt",
  optimize: true,
  dryrun: true,
});

const earlyExitResp = await client.guard.evaluate({
  content: userInput,
  content_type: "prompt",
  action: "process_prompt",
  early_exit: true,
});

const contextualResp = await client.guard.evaluate({
  content: modelResponse,
  content_type: "response",
  action: "process_prompt",
  contexts: [originalPrompt, ...ragChunks],
});
```

## Streaming

`client.guard.stream()` returns an `AsyncIterable` of `StreamEvent`.

```typescript
for await (const event of client.guard.stream({
  content: "tell me a secret",
  content_type: "prompt",
  action: "process_prompt",
})) {
  switch (event.type) {
    case "detector_result":
      console.log("Detection result:", event.data);
      break;
    case "decision":
      console.log("Final decision:", event.data);
      break;
    case "error":
      console.error("Stream error:", event.data);
      break;
  }
}
```

| `event.type`        | Description                                        |
| ------------------- | -------------------------------------------------- |
| `"detector_result"` | Per-detector result as each streamed event arrives |
| `"decision"`        | Final allow or deny decision                       |
| `"error"`           | Stream error                                       |

The iterator ends naturally when the stream closes. There is no separate typed `"done"` event in the public `StreamEvent` interface.

## Agentic Context

Pass structured context for richer detection and policy evaluation.

```typescript
const toolResp = await client.guard.evaluate({
  content: "ls /etc",
  content_type: "tool_call",
  action: "call_tool",
  tool: {
    name: "shell",
    arguments: { cmd: "ls /etc" },
    is_builtin: true,
    server_id: "mcp_server_filesystem",
  },
});

const modelResp = await client.guard.evaluate({
  content: "Explain photosynthesis",
  content_type: "prompt",
  action: "process_prompt",
  model: {
    provider: "anthropic",
    model: "claude-sonnet-4-6",
    temperature: 0.7,
    tokens_used: 1500,
    max_tokens: 4096,
  },
});

const mcpResp = await client.guard.evaluate({
  content: "filesystem",
  content_type: "prompt",
  action: "connect_server",
  mcp: {
    server_name: "filesystem",
    server_url: "http://mcp-server:3000",
    transport: "sse",
    verified: false,
    capabilities: ["read", "write"],
  },
});

const fileResp = await client.guard.evaluate({
  content: await fs.readFile("/etc/passwd", "utf8"),
  content_type: "file",
  action: "read_file",
  file: {
    path: "/etc/passwd",
    operation: "read",
    size: 2048,
    mime_type: "text/plain",
  },
});
```

### `MCPContext` Fields

| Field          | Type        | Description                                         |
| -------------- | ----------- | --------------------------------------------------- |
| `server_name`  | `string`    | MCP server name                                     |
| `server_url`   | `string?`   | MCP server URL                                      |
| `transport`    | `string?`   | Transport protocol: `"sse"`, `"stdio"`, or `"http"` |
| `verified`     | `boolean?`  | Whether the server passed trust or signature checks |
| `capabilities` | `string[]?` | Advertised capabilities from the server manifest    |

### `FileContext` Fields

| Field               | Type       | Description                                                   |
| ------------------- | ---------- | ------------------------------------------------------------- |
| `path`              | `string`   | File path                                                     |
| `operation`         | `string`   | File operation such as `"read"`, `"write"`, or `"append"`     |
| `size`              | `number?`  | File size in bytes                                            |
| `mime_type`         | `string?`  | File MIME type                                                |
| `file_name`         | `string?`  | Original file name                                            |
| `file_extension`    | `string?`  | File extension such as `"pdf"` or `"docx"`                    |
| `sensitivity_level` | `string?`  | `"public"`, `"internal"`, `"confidential"`, or `"restricted"` |
| `mip_label_id`      | `string?`  | Microsoft Information Protection label GUID                   |
| `mip_label_name`    | `string?`  | MIP label display name                                        |
| `is_encrypted`      | `boolean?` | Whether the file is encrypted                                 |
| `is_rights_managed` | `boolean?` | Whether the file has IRM or RMS restrictions                  |

## Error Handling

| Class                 | When thrown                                     | Key properties              |
| --------------------- | ----------------------------------------------- | --------------------------- |
| `BlockedError`        | Guard decision is `"deny"` from Shield wrappers | `response: GuardResponse`   |
| `AuthenticationError` | 401 Unauthorized                                | `status`, `title`, `detail` |
| `RateLimitError`      | 429 Too Many Requests                           | `status`, `title`, `detail` |
| `APIError`            | Non-2xx HTTP response from the service          | `status`, `title`, `detail` |
| `APIConnectionError`  | Network failure or timeout                      | `message`                   |
| `HighflameError`      | Base class                                      | —                           |

```typescript
import {
  APIError,
  AuthenticationError,
  RateLimitError,
  APIConnectionError,
  BlockedError,
  HighflameError,
} from "@highflame/sdk";

try {
  const resp = await client.guard.evaluate({
    content: "test",
    content_type: "prompt",
    action: "process_prompt",
  });
} catch (err) {
  if (err instanceof AuthenticationError) {
    console.error(`Auth failed: ${err.detail}`);
  } else if (err instanceof RateLimitError) {
    console.error(`Rate limited: ${err.detail}`);
  } else if (err instanceof APIError) {
    console.error(`[${err.status}] ${err.title}: ${err.detail}`);
  } else if (err instanceof APIConnectionError) {
    console.error(`Connection failed: ${err.message}`);
  } else if (err instanceof HighflameError) {
    console.error(`Unexpected SDK error: ${err}`);
  }
}

const chat = shield.prompt(async (msg: string) => llm.complete(msg));
try {
  await chat(userMessage);
} catch (err) {
  if (err instanceof BlockedError) {
    console.error("Blocked:", err.response.policy_reason);
  }
}
```

## Enforcement Modes

| Mode        | Behavior                            | `resp.decision`       | `resp.alerted`     |
| ----------- | ----------------------------------- | --------------------- | ------------------ |
| `"enforce"` | Block on deny                       | `"deny"` on violation | `false`            |
| `"monitor"` | Allow and log silently              | `"allow"`             | `false`            |
| `"alert"`   | Allow and trigger alerting pipeline | `"allow"`             | `true` if violated |

```typescript
const monitorResp = await client.guard.evaluate({ ...req, mode: "monitor" });
if (monitorResp.actual_decision === "deny") {
  shadowLog.record(monitorResp);
}

const alertResp = await client.guard.evaluate({ ...req, mode: "alert" });
if (alertResp.alerted) {
  await pagerduty.trigger({ summary: `Alert: ${alertResp.policy_reason}` });
}

const enforceResp = await client.guard.evaluate({ ...req, mode: "enforce" });
if (enforceResp.decision === "deny") {
  return { blocked: true, reason: enforceResp.policy_reason };
}
```

## Session Tracking

Pass a `session_id` to enable cumulative risk tracking across conversation turns.

```typescript
const sessionId = `sess_${crypto.randomUUID()}`;

const resp1 = await client.guard.evaluatePrompt("Read the config file", { session_id: sessionId });
console.log(resp1.session_delta?.turn_count);

const resp2 = await client.guard.evaluate({
  content: "ls /etc",
  content_type: "tool_call",
  action: "call_tool",
  session_id: sessionId,
  tool: { name: "shell", arguments: { cmd: "ls /etc" } },
});
console.log(resp2.session_delta?.cumulative_risk);

const chat = shield.prompt(async (msg: string) => llm.complete(msg), { sessionId });
```

## Multi-Project Support

Pass `accountId` and `projectId` to scope all requests to a specific project:

```typescript
const client = new Highflame({
  apiKey: "hf_sk_...",
  accountId: "acc_123",
  projectId: "proj_456",
});
```

## Client Options

| Option           | Type                     | Default        | Description                                                                             |
| ---------------- | ------------------------ | -------------- | --------------------------------------------------------------------------------------- |
| `apiKey`         | `string`                 | required       | Service key (`hf_sk_...`), agent key (`hfa_...`), ZeroID key (`zid_sk_...`), or raw JWT |
| `baseUrl`        | `string`                 | Highflame SaaS | Guard service URL                                                                       |
| `tokenUrl`       | `string`                 | Highflame SaaS | Token exchange URL used for `hf_sk_*`, `hfa_*`, and `zid_sk_*` keys                     |
| `timeout`        | `number`                 | `30000`        | Request timeout in milliseconds                                                         |
| `maxRetries`     | `number`                 | `2`            | Retries on transient errors                                                             |
| `accountId`      | `string`                 | —              | Optional customer account ID                                                            |
| `projectId`      | `string`                 | —              | Optional project ID                                                                     |
| `defaultHeaders` | `Record<string, string>` | —              | Extra headers merged into every request                                                 |
| `logger`         | `Logger`                 | —              | Optional logger with `debug`, `info`, and `warn` methods                                |

```typescript
const resp = await client.guard.evaluate(request, { timeout: 5_000 });
```

## Auth Header Reuse

Use `getAuthHeaders()` when you want the SDK to manage token exchange and header construction, but you are sending requests through your own HTTP client or middleware.

```typescript
const headers = await client.getAuthHeaders();
await fetch("https://internal.example.com/proxy", {
  method: "POST",
  headers: {
    ...headers,
    "X-Custom-Routing": "my-service",
  },
  body: JSON.stringify({ action: "healthcheck" }),
});
```

## Logging

Pass a `logger` object if you want the SDK to emit debug, info, and warn messages through your application's logging pipeline.

```typescript
const client = new Highflame({
  apiKey: "hf_sk_...",
  logger: {
    debug: (msg, ...args) => logger.debug(msg, ...args),
    info: (msg, ...args) => logger.info(msg, ...args),
    warn: (msg, ...args) => logger.warn(msg, ...args),
  },
});
```

## OpenTelemetry

If `@opentelemetry/api` is installed and a tracer provider is configured, the SDK automatically:

* injects W3C trace context into outgoing Shield requests
* creates client-side spans for `guard` and `detect` calls

When OpenTelemetry is not installed or not configured, these hooks safely no-op.

## Internal Usage

Internal services that call Shield for non-guardrails products must set the `X-Product` header.

```typescript
const sentryClient = new Highflame({
  apiKey: "hf_sk_...",
  defaultHeaders: { "X-Product": "sentry" },
});

const overwatchClient = new Highflame({
  apiKey: "hf_sk_...",
  defaultHeaders: { "X-Product": "overwatch" },
});

const mcpClient = new Highflame({
  apiKey: "hf_sk_...",
  defaultHeaders: { "X-Product": "mcp_gateway" },
});
```

When `X-Product` is not set, Shield defaults to `"guardrails"`. External customers should not need to set this header.

## TypeScript Notes

Use `import type` for type-only imports when `verbatimModuleSyntax` is enabled:

```typescript
import { Highflame, Shield, BlockedError } from "@highflame/sdk";
import type { GuardRequest, GuardResponse, Mode, ToolContext } from "@highflame/sdk";

import { Highflame, type GuardResponse } from "@highflame/sdk";
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.highflame.ai/api-reference/sdk/shield/typescript-sdk/advanced-topics.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
