/darkhunt-telemetry:darkhunt-telemetry-integrationfrom darkhunt-telemetry
Integrates the @darkhunt-security/telemetry SDK into Node.js/TypeScript services for LLM tracing, span emission, and observability. Covers install, API keys, client setup, trace/generation/span emission, multi-agent topology with handoffs, and Darkhunt guard() integration.
Ships in darkhunt-telemetry. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
This skill walks through wiring @darkhunt-security/telemetry into a TS/Node
service. The full SDK reference (multi-turn chat, RAG retriever
spans, streaming time-to-first-token) lives at
https://docs.darkhunt.ai/darkhunt-ai-security/sdks/typescript — read it when
the user needs something the patterns below don't cover.
A Darkhunt span exporter built on OpenTelemetry primitives (TracerProvider,
BatchSpanProcessor, OTLP/protobuf transport) that ships spans — traces, LLM
generations, tool calls, retrievals, guardrails — to Darkhunt trace-hub.
Routing semantics (tenantId / workspaceId / applicationId) and the
attribute schema are Darkhunt-specific; trace-hub is the intended receiver.
The SDK does not mask data — values are sent verbatim, and masking of PII
happens server-side in the Darkhunt platform on ingest. That masking does not cover
metadata values, tags or routing IDs (sessionId, userId, userEmail) — never put
secrets or unhashed PII there.
Key shapes:
DarkhuntTelemetry — the client. One per process, lifetime-of-the-process.Trace — a single user-facing interaction. Carries routing fields
(tenant / workspace / application).Generation — one LLM round-trip under a trace. Carries model,
inputMessages, outputMessages, usage, cost, metadata.Span — anything else (tool calls, retrievals, guardrails, sub-agents,
generic work). Use observationType to categorize.Preflight check before installing. The SDK is ESM-only and requires
Node ^18.19.0 || >=20.6.0 (the floor set by its OpenTelemetry deps).
Before adding the dependency, verify the target project:
package.json has "type": "module" (or the project is otherwise ESM,
e.g. via .mts files). If the project is CommonJS, stop and tell the
user the SDK won't require() cleanly — they need to migrate to ESM or
use dynamic import() from a CJS wrapper, neither of which the agent
should do silently.package.json engines.node (or the project's CI matrix) satisfies
^18.19.0 || >=20.6.0. If the project pins an older Node (< 18.19), flag
it and ask before bumping.Once both check out:
npm install @darkhunt-security/telemetry
A dh-... API key authenticates the SDK to the public ingest endpoint. Create
one in the Darkhunt dashboard:
Settings → Security → API Keys).production-tracing,
my-service-staging) and pick an Expiration
(30 / 60 / 90 / 180 days, 1 year, or No expiration). Default is 90 days —
prefer a bounded expiry for production and set a rotation reminder.dh-9028f••••••••).The key carries the same privileges as your account, so treat it as a secret: store it in a secrets manager / env file, never commit it.
The env var the key must go in is DARKHUNT_API_KEY — the SDK reads it from
the environment by default:
DARKHUNT_API_KEY=dh-9028f...your-full-secret...
Equivalently, pass it explicitly as the apiKey constructor option (an
explicit apiKey wins over the env var). Either way it's sent as
Authorization: Bearer <apiKey>. If it's missing, the constructor throws:
apiKey is required for the public endpoint (pass via options, set DARKHUNT_API_KEY, or use internal: true).
While you're on the dashboard, also grab your tenantId, workspaceId,
and applicationId from the Get started page
and set them as DARKHUNT_TENANT_ID, DARKHUNT_WORKSPACE_ID,
DARKHUNT_APPLICATION_ID — the SDK reads those automatically too (see
Routing fields).
The key is in
.env? Leave the file closed. Opening,cat-ing or printing.envsends the key to the model and into the session transcript, which is exactly what keeping it out of the prompt avoids. Check that it is set without revealing it (grep -c '^DARKHUNT_API_KEY=' .envprints a count, not the value), and never copy the key into source, committed config, or your report.
When the user hands you the routing IDs (the dashboard's onboarding prompt
includes DARKHUNT_TENANT_ID, DARKHUNT_WORKSPACE_ID and DARKHUNT_APPLICATION_ID),
they are not secrets: add them next to the key, still without printing the file, and
add the variable names (no values) to .env.example if the project keeps one. Don't
create a new application when one is supplied: the dashboard made a dedicated one.
[ -s .env ] && [ -n "$(tail -c1 .env)" ] && echo >> .env # end .env with a newline first
for kv in DARKHUNT_TENANT_ID=<tenant> DARKHUNT_WORKSPACE_ID=<workspace> DARKHUNT_APPLICATION_ID=<app>; do
grep -q "^${kv%%=*}=" .env 2>/dev/null || echo "$kv" >> .env
done
The base URL defaults to https://api.darkhunt.ai/trace-hub; override it via the
DARKHUNT_BASE_URL env var or the baseUrl option when pointing at a
self-hosted / staging / dev trace-hub. Two rules when you override it: use the
ingest API host (api…darkhunt.ai), not the dashboard (app…darkhunt.ai,
which redirects POSTs → 405); and keep the /trace-hub path — the exporter
posts to {baseUrl}/otlp/t/{tenantId}/v1/traces, so dropping /trace-hub yields 404. Example (dev): DARKHUNT_BASE_URL=https://api-seth-dev.darkhunt.ai/trace-hub.
Set serviceName (option, or DARKHUNT_SERVICE_NAME / OTEL_SERVICE_NAME) to the OTel
Resource service.name. The backend records it per span, so in a multi-service / multi-agent
system give each process its own value (e.g. weather.coordinator, weather.geodata) to tell
producers apart — the Resource is per-TracerProvider, so distinct names require distinct
clients/processes, not one shared instance. When several logical agents share ONE process,
don't spin up a client each — set agent per trace instead (see "Multi-agent topology"): it
emits service.name as a span attribute, which outranks the Resource at ingest.
For tool-type observations, set toolName (and optionally toolCallId / toolArguments) on
the span — emitted as gen_ai.tool.name / gen_ai.tool.call.id / gen_ai.tool.call.arguments, the
fields the backend uses to show the actual tool (e.g. "geocode") rather than the generic type.
.envThe SDK reads process.env only, and Node never loads .env by itself. If nothing in
the service does, the variables are missing at runtime and new DarkhuntTelemetry()
throws apiKey is required for the public endpoint as soon as src/telemetry.ts is
imported. Find out how this service gets its configuration before you finish:
ConfigModule, dotenv,
docker compose env_file:): make sure that happens before the module that
constructs the client is imported.--env-file=.env (Node ≥ 20.6), or make
import 'dotenv/config'; the first import of the entrypoint, and say so in your
report.DARKHUNT_* variables must be set there.Don't construct DarkhuntTelemetry per request. The SDK registers a
process.once('beforeExit', ...) handler per construction and spins up a
NodeTracerProvider + BatchSpanProcessor each time, so a per-call client leaks
listeners (Node's 10-listener warning) and prevents BSP from batching across
calls. Put it in a dedicated module the rest of the app imports:
// src/telemetry.ts
import { DarkhuntTelemetry } from '@darkhunt-security/telemetry';
// Reads DARKHUNT_API_KEY, DARKHUNT_TENANT_ID, DARKHUNT_WORKSPACE_ID,
// and DARKHUNT_APPLICATION_ID from the environment.
export const dh = new DarkhuntTelemetry();
export async function shutdownTelemetry(): Promise<void> {
await dh.shutdown();
}
The SDK auto-flushes on process.beforeExit, but not on signal-driven
shutdown. Long-running servers must wire it up so the in-memory span batch
isn't lost on deploy/restart:
const shutdown = async (signal: NodeJS.Signals) => {
console.log(`shutting down (${signal})`);
await shutdownTelemetry();
process.exit(0);
};
process.once('SIGTERM', shutdown);
process.once('SIGINT', shutdown);
For one-shot scripts / CLIs / cron jobs: await dh.flush() before returning is
enough — the beforeExit hook handles teardown.
import { dh } from './telemetry.js';
export async function handleChat(req, res) {
const startTime = Date.now(); // capture BEFORE the awaited LLM call
const trace = dh.trace({
name: 'chat',
sessionId: req.session?.id, // groups turns into one conversation timeline
userId: req.user?.email,
startTime, // backdate the root span
});
const gen = trace.generation('answer', { startTime });
gen.update({
inputMessages: [{ role: 'user', content: req.body.message }],
});
const reply = await yourLlmCall(req.body.message); // your existing client
gen.end({
model: 'claude-opus-4',
outputMessages: [{ role: 'assistant', content: reply.content }],
usage: {
input_tokens: reply.usage.inputTokens,
output_tokens: reply.usage.outputTokens,
},
});
trace.end();
res.json({ reply: reply.content });
}
startTime backdates the span to a timestamp you captured earlier. Pass it
(on both the trace root and the generation) whenever the moment the span should
begin is earlier than the line that constructs it. In the example above the
spans are opened before the await, so they already capture the full LLM
latency — startTime just pins the start to the exact captured instant rather
than the slightly-later construction line. It becomes essential when you instead
open the generation after the call returns (a common pattern): without it the
span starts post-call and records ~0ms of duration.
update() is for fields known at start; end() is for fields known when work
finishes. You can pass everything to end() if there's no streaming
intermediate state to record. Wrap in try/catch and record failures with
gen.end({ level: 'ERROR', statusMessage: String(err) }).
Every span carries three required routing attributes — tenantId,
workspaceId, applicationId. The exporter groups by these and posts to
POST {baseUrl}/otlp/t/{tenantId}/v1/traces with X-Workspace-Id /
X-Application-Id headers.
Set them once at the client level if they're constant for the process (or via
the DARKHUNT_* env vars), pass per-trace if multi-tenant. The constructor
merges constructor arg > env var > default and dh.trace() throws if any
field is still missing.
// Single-tenant: client-level (or via DARKHUNT_TENANT_ID / _WORKSPACE_ID / _APPLICATION_ID)
const dh = new DarkhuntTelemetry({
tenantId: 't1',
workspaceId: 'ws-1',
applicationId: 'app-1',
});
dh.trace({ name: 'chat' }); // tenant/workspace/app inherited
// Multi-tenant: per-trace
const dh = new DarkhuntTelemetry();
dh.trace({
tenantId: req.tenantId,
workspaceId: req.wsId,
applicationId: 'shared',
});
// Multi-tenant AND several logical agents in the process: BOTH per-trace.
// They're independent — routing comes from the request, `agent` from whichever
// agent is running. Only serviceName stays on the client.
const dh = new DarkhuntTelemetry({ serviceName: 'alludium-web' });
dh.trace({
agent: 'research', // the topology node
sessionId: req.sessionId, // MUST be shared across the run's agents
tenantId: req.tenantId,
workspaceId: req.wsId,
applicationId: req.appId,
});
Routing fields are required; sessionId and userId are technically
optional but every integration should set them. They unlock the two
features customers actually buy the platform for:
sessionId into one timeline. A chatbot that doesn't set it shows up as
N disconnected traces instead of one conversation.userId for per-user rate limits, abuse signals, and policy decisions.
Without it, the only available scope is per-application — much coarser.When wiring a service, look for the stable identifiers already in scope and plumb them through:
req.session?.id (or signed cookie) →
sessionId; req.user?.id or req.user?.email → userId.sessionId; the
invoking customer/account ID → userId.If these aren't known at trace open (auth happens mid-flow), open the trace
anyway and call trace.update({ userId, sessionId }) once they're known —
all spans created after the update inherit the values.
| Work | API | observationType |
|---|---|---|
| LLM round-trip | trace.generation(name, opts) | (auto: generation) |
| External tool / function call | trace.span(name, { observationType: 'tool', ... }) | 'tool' |
| Vector search / retrieval | trace.span(name, { observationType: 'retriever', ... }) | 'retriever' |
| Sub-agent step | trace.span(name, { observationType: 'agent', ... }) | 'agent' |
| Input/output guardrail | trace.span(name, { observationType: 'guardrail', ... }) | 'guardrail' |
| Generic work | trace.span(name, opts) | 'span' (default) |
| Fire-and-forget marker | trace.event(name, opts) | 'event' |
Spans nest naturally — parent.span(...) makes the child a child in the
trace tree.
The metadata bag is a flat Record<string, string> on each span. It shows
up in the trace-hub dashboard and is filterable. Be strict:
score, route, outcome).input/output) where it doesn't
pollute the metadata view.The canonical list of what the SDK emits and what trace-hub reads.
Set on client.trace({...}) or as constructor defaults on new DarkhuntTelemetry({...}).
| SDK option | Required | trace-hub field |
|---|---|---|
tenantId | yes | tenant scope |
workspaceId | yes | workspace scope |
applicationId | yes | application scope |
name | no | trace.name |
sessionId | no | trace.sessionId |
userId | no | trace.userId |
userEmail | no | trace.userEmail |
tags | no | trace.tags |
release | no | trace.version + serviceVersion |
environment | no | environment.deployment |
agent | no | environment.serviceName — the topology node. Emits service.name as a span attr on the root AND every child, overriding the Resource for this trace group. Also makes the trace a new root: handoffFrom[0] becomes a link, not a parent. |
Set on trace.span(name, opts) / trace.generation(name, opts) / via
.update(opts) / .end(opts).
| SDK option | trace-hub field | Notes |
|---|---|---|
observationType | span.type | span / tool / agent / generation / event / chain / retriever / evaluator / embedding / guardrail |
input | content.input | sent verbatim; objects JSON-encoded |
output | content.output | sent verbatim |
level | span.level | 'DEFAULT' / 'DEBUG' / 'WARNING' / 'ERROR' |
statusMessage | error.message | sets ERROR status when paired with level: 'ERROR' |
version | span.version | |
metadata | span.metadata.<key> | one attribute per key — never a single JSON blob |
Set on trace.generation(name, opts) / via .update(opts) / .end(opts).
These add to the span fields above.
| SDK option | trace-hub field |
|---|---|
model | model.name |
modelParameters | model.parameters |
inputMessages | content.input |
outputMessages | content.output |
systemInstructions | content.system |
usage.input_tokens | tokens.input |
usage.output_tokens | tokens.output |
usage.cache_read_tokens | tokens.cacheRead |
usage.cache_creation_tokens | tokens.cacheCreation |
cost | cost.json + cost.total |
completionStartTime | timing.completionStartTime |
promptName | prompt.name |
promptVersion | prompt.version |
When the service is one agent in a multi-agent system, the platform reconstructs the agent topology — who handed off to whom — from span links (standard OTel, not a proprietary format). Wire it with the handoff helper; without links you only get a star under the orchestrator, not the real DAG.
Identity: one serviceName per agent (e.g. finance.quant) — that is the topology node.
Several logical agents in ONE process?
serviceNameis the OTel Resource, fixed perTracerProvider(i.e. per client), so a shared client renders ONE node named after the process. Don't reach for a client-per-agent registry — passagentper trace instead:dh.trace({ agent: 'research', ... }). It emitsservice.nameas a span attribute on the root and every child (span attrs outrank the Resource at ingest), so each agent gets its own node from one client. Two rules come with it: (1) an agent-scoped trace is deliberately a new root — it ignoreshandoffFrom[0]and any ambient span when parenting, because node identity resolves once per trace id and two agents in one trace would silently collapse; upstreams stayagent_handofflinks, so the edge survives but the cross-agentparentSpanIdchain does not. (2) Since edges then come from links alone, and links resolve within a session, every agent in one run MUST share asessionIdor no edge is drawn. Use a small stable set of agent names — each distinct value is a permanent topology node.
Emit a handoff — two calls:
// Upstream agent: expose its entry-span token.
const trace = dh.trace({ name: 'research-agent', sessionId, userId });
// ...work...
const handoff = trace.handoffToken(); // opaque, serialisable string (a W3C traceparent)
return { ...result, handoff };
// Downstream agent: declare its upstream(s). Fan-in = pass several.
const trace = dh.trace({
name: 'analyst-agent',
handoffFrom: [research.handoff, quant.handoff],
sessionId,
userId,
});
handoffFrom accepts HandoffToken strings or OTel Contexts; each becomes an
agent_handoff span link on the trace's root span. The orchestrator threads each
upstream's handoffToken into the downstream's handoffFrom — wherever it already passes
that agent's output as the next agent's input. Cross-process (Temporal / queue / HTTP): the
token is a string, so carry it in the workflow arg / message / header like any other value.
Emit the right spans so the graph reads correctly:
generation span renders as an Agent (model, cost,
and the AI-risk surface); a tools-only node renders as a Worker (no cost, can't be
jailbroken/injected). Emit trace.generation(...) for every real LLM call.model + usage on each generation.↻ ×N — automatic. N = the agent's cross-service entry spans (how many times it
was invoked). A retry loop or N debate rounds ⇒ N entry spans ⇒ ↻ ×N.↺ between two agents — needs a back-edge. On a retry / re-review, add the
prior agent to the next agent's handoffFrom (e.g. the retried remediation links to the
failed verify; each debate rebuttal links to the opposing thesis). A one-directional flow
won't draw a cycle — the back-link does.Gotchas (each was a real bug):
handoffToken() targets the always-exported root span. A
helper span created and .end()-ed immediately gets dropped on fast (sub-second, tool-only)
agents → the downstream link dangles → no edge. Use handoffToken() / handoffFrom only.handoffFrom: [a, b, c] — a span has one parent but can link to many upstreams.handoffFrom.darkhunt.link.kind marker — the SDK tags handoff links for you. Don't
route non-handoff OTel links through handoffFrom.guard() (enforcement, not just tracing)Tracing records what a tool did. guard() lets the rules in the Darkhunt
dashboard stop it. It calls the guardrail manager's /verify twice per call:
TOOL_CALL, before the function runs: a block means it never runs;TOOL_RESULT, before the caller sees the output: a block means it is withheld.Only add it when the user asks to guard, block or enforce. Plain observability doesn't need it.
import { configureGuard, guard } from '@darkhunt-security/telemetry';
configureGuard({ mode: 'shadow' }); // start in shadow; see "Rollout"
// Wrap the FUNCTION you hand to the framework's tool helper:
const sendReferral = tool({
description: '…',
inputSchema: z.object({ to: z.string(), message: z.string() }),
execute: guard(async function send_referral(input) {
/* … */
}),
});
guard(fn) returns an async
function with the same parameters. Put it where the framework takes your
implementation (execute, func, a handler).args: (...a) => ({ … }) for positional tools.name defaults to the
function's name: give anonymous functions a name, or pass { name: 'send_referral' }.trace.activate(() => runAgent()), or
call tools under startActiveSpan, so each check carries the run's
sessionId, userId and routing. The current run comes from the active OTel
context; the client registers the context manager by default. Outside a run
the checks still go out, but with no session.tool span
for this tool with startActiveSpan, the guard puts its guardrail spans
under it.onDeny per tool, by who reads the result| Who consumes the result | onDeny | Why |
|---|---|---|
| A model (the LLM picked the tool) | 'return' (default): a refusal string | the model reads "Blocked by Darkhunt: …" and can explain it |
| Code that can do without the data | a function, e.g. () => [] | the pipeline continues; the block is still recorded |
| Code that can't continue | 'throw': DarkhuntBlockedError | fail loudly rather than run on a refusal string |
shadow (DARKHUNT_GUARD_MODE=shadow, the default). Checks run
and are recorded as "Would block (shadow)", but nothing is stopped.enforce with an explicit fail mode. enforce requires
DARKHUNT_GUARD_FAIL=open|closed. Use closed for tools that send or write
sensitive data, and open where availability matters more.configureGuard({ onVerdict }) to add blocked or denied verdicts to the
run's output.toolName==<tool>,
ENFORCE, TOOL_CALL) and run the agent. The tool must not run, the result
must show the block, and the dashboard's enforcement log must list it under
the run's session.Keep AGT, and make Darkhunt its policy. Give the AGT manifest a
type: custom, adapter: darkhunt policy on pre_tool_call / post_tool_call,
and build the control with
AgentControl.fromPath(path, undefined, new DarkhuntPolicy())
(@darkhunt-security/telemetry/agt). Then:
agtTool(control, fn) for a tool function;runGoverned(control, name, args, execute) for a loop that dispatches by name;checkToolPoint(control, 'pre_tool_call' | 'post_tool_call', name, args, { result })
for allow/deny hooks only.[email protected], the version in
AGT's latest official release (v4.1.0). It's an optional peer dependency with
prebuilt binaries. Manifests must declare
agent_control_specification_version: 0.3.1-beta.{ host: trace } when calling them outside the run's context.After wiring, run:
npx tsc --noEmit # ensure types resolve
npm test # if the integration has unit-test coverage
Then probe auth and routing on the server. A clean flush() is not proof of ingestion
(the BatchSpanProcessor swallows export errors); this is. 400 on the empty body
means auth and routing are OK, 401 a wrong or missing key, 404 a baseUrl
without /trace-hub:
( set -a; . ./.env; set +a # load .env into this subshell only; never print it
curl -s -o /dev/null -w '%{http_code}\n' -X POST \
-H "Authorization: Bearer $DARKHUNT_API_KEY" \
-H 'Content-Type: application/x-protobuf' \
-H "X-Workspace-Id: $DARKHUNT_WORKSPACE_ID" \
-H "X-Application-Id: $DARKHUNT_APPLICATION_ID" \
--data-binary '' \
"${DARKHUNT_BASE_URL:-https://api.darkhunt.ai/trace-hub}/otlp/t/$DARKHUNT_TENANT_ID/v1/traces" )
Drop the first line if the variables are already exported. . ./.env runs the file as
shell; if it isn't shell-compatible, export the variables another way, never by
printing the file.
Then exercise a real path that emits a span and check trace-hub for the
incoming trace. The dashboard should show one trace per sessionId, each
generation rendering inputMessages / outputMessages as chat bubbles, the
routing attributes on the span detail panel, and token usage / model / cost on
generation spans.
If spans don't appear, check: (1) routing fields are populated, (2) baseUrl
points at the right environment, (3) the apiKey is valid, (4) the process
exits gracefully so flush() runs (a kill -9 loses the in-memory batch).
When you finish, report: the files you changed and why; where each DARKHUNT_*
variable is set (never the key's value); the probe's status code; and what the user
still has to do (restart the service, set the variables in deployment, send one real
request).
startTime. If you construct the
generation after the awaited call returns, its duration shows ~0ms. Capture
Date.now() before the call and pass it as startTime to backdate the span.beforeExit, so
the in-memory span batch is lost. Wire SIGTERM/SIGINT to dh.shutdown().metadata shows up on every dashboard
row for that span. Promote only summary fields.trace.end(). Spans that never end stay open in BSP and
never get exported. Always pair dh.trace(...) with trace.end().guard wrapped around a framework tool object. It needs the implementation function (execute / func), not the tool the framework built from it.enforce without DARKHUNT_GUARD_FAIL. configureGuard throws. Choose open or closed deliberately.trace.activate(...)..env to check the key. The key lands in the model's context and the transcript. Check with grep -c, and load it into a subshell only for the probe..env. The constructor throws at import. See §2b.The full SDK guide — multi-turn chat sessions, RAG retriever spans, streaming
completionStartTime for time-to-first-token, recording errors with
level: 'ERROR' + statusMessage, and the full configuration + env-var
precedence table — is at:
https://docs.darkhunt.ai/darkhunt-ai-security/sdks/typescript
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Other plugins' skills for the same job
npx claudepluginhub darkhunt-security/darkhunt-telemetry-ts --plugin darkhunt-telemetry