npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@noetaris/harness-otel

v0.10.0

Published

OpenTelemetry observer bridge for @noetaris/harness

Readme

@noetaris/harness-otel

OpenTelemetry observer bridge for @noetaris/harness.

Overview

@noetaris/harness-otel turns the harness Observer hooks into OpenTelemetry spans and a metric. It knows only what the harness knows: runs, fork branches, steps and plain events. Its spans and attributes use harness.* names, and it writes no gen_ai.* key.

LLM calls and tool calls get their own spans from an extension. The GenAI semantic conventions come as one: @noetaris/harness-otel-genai. You can also write your own (see Extensions).

Takes @opentelemetry/api as a peer dependency — works with any OTel SDK implementation (Node SDK, collector exporters, etc.).

Installation

pnpm add @noetaris/harness-otel

Peer dependencies:

pnpm add @noetaris/harness @opentelemetry/api

For chat and execute_tool spans and the GenAI metrics, add the extension:

pnpm add @noetaris/harness-otel-genai

Requires @noetaris/harness 0.9.0 or later (its onRunEnd carries the run's error, and its carry hook and RunContext.resumedFrom / branchedFrom drive links between runs), @opentelemetry/api 1.1.0 or later, and Node.js ≥ 22.

Usage

createOtelObserver returns a plain Observer. Pass it to a run through the reserved observer resource key — the second argument to agent.run(). There is no separate registration step.

import { createOtelObserver } from '@noetaris/harness-otel'
import { genai } from '@noetaris/harness-otel-genai'
import { trace, metrics } from '@opentelemetry/api'

const observer = createOtelObserver(trace.getTracer('my-agent'), {
  meterProvider: metrics.getMeterProvider(), // omit to record spans only
  extensions: [genai()],                     // omit for lifecycle spans only
})

// the LLM adapter is provided when the agent is created (createAgent)
await agent.run({ input: 'Hello' }, { observer })

resume() accepts the same observer key, so a resumed run is traced too.

To send events to more than one Observer (e.g. OTel plus a custom logger), merge them with composeObservers([...]) from @noetaris/harness and pass the result as the single observer resource. composeObservers takes an array of observers plus an optional onObserverError sink, and isolates each observer so one that throws never starves the others or crashes the run.

Spans

| Span | Kind | Attributes | |------|------|------------| | harness.run {agentId} | INTERNAL, root | harness.agent.id, harness.session.id, harness.run.id; harness.parent_run.id and harness.instance.id when the run has them; harness.request.id when the run belongs to a request (requestId); one of harness.resumed_from.run_id, harness.branched_from.session_id + harness.branched_from.run_id, or harness.continued_from.run_id when the run continues another (see Links between runs); at the end harness.run.signal | | harness.branch {name} | INTERNAL, under the fork's step span | harness.branch.name, harness.branch.path; at the end harness.run.signal | | harness.step {stepName} | INTERNAL, under its run or branch span | harness.step.name; at the end harness.step.outcome (ok | error | interrupt | stopped), harness.step.next.kind (step | end | pause | throw), harness.step.next.name when the next kind is step, and harness.step.signal when route() ran (see Step routing) |

An extension can rename the root and add attributes to it (genai() names it invoke_agent {agentId}).

Step routing

When a step settles, its span records where the run went next:

| Attribute | Present | Value | |---|---|---| | harness.step.signal | when the step's route() ran and returned | the signal route() returned | | harness.step.next.kind | always | step — a route target, .next(), the implicit next step, the onError fallback, or the join after a fork; end — .end() (in a fork branch: the branch ended); pause — the run paused (interrupt, stop, unhandled error); throw — a graph error (e.g. a signal with no transition) rejects the run | | harness.step.next.name | when the next kind is step | the next step's name |

A step without route() (implicit or .next()), a fork node, and a step that paused or failed before routing have no harness.step.signal; no stand-in value is set. The step's update and state are never recorded on a span.

Errors. A step that settles with an error, and a run or branch that ends with one, get ERROR status (the message is String(error)) and error.type: the error's class name, or _OTHER when the thrown value is not an Error. A run ends with an error when a step or route throws and no onError step handles it, when a fork fails, or when the run rejects. $interrupt, $stopped and your own signals are not errors — not even a route that returns the string '$error' itself.

Events. An event that no extension claims — a ctx.emit() of your own, or llm.* / tool.* when no extension handles them — becomes a span event (its name only, no payload) on the step span, or on the run span when no step is open.

Ending. Each step span ends on onStepSettled, which core fires once per step on every path — including a fork node that pauses on an interrupt, is stopped, or fails — so a fork's step span is always exported and its branch spans always have an exported parent. As a safety net, the end of a run also ends a step span that is still open. A run that rejects still ends its spans: onRunEnd fires before the rejection. If the same run starts again without ending (a restart), its old spans are ended first with harness.run.signal = '$abandoned'.

Links between runs

A session that pauses and continues is several runs, and each run is its own trace. The root span of a run that continues another one gets a span link back to that run's root span:

session S1
  trace T1                    trace T2                        trace T3                  trace T5
  harness.run (#1)  <--link--  harness.run (#2)  <--link--  harness.run (#3)  <--link--  harness.run (#4)
  paused: $interrupt            paused: $interrupt            done                      next turn
  (resumed_from)                (resumed_from)                                          (continued_from)
        ^
        |  store.branch(S1, run #1)
session S2
  trace T4
  harness.run (#1')  --link-->  #1   (branched_from)

| The run is | Link type (harness.link.type) | Root span attributes | |---|---|---| | the next run on a session that paused — on an interrupt, a stop, or an error no onError step handled (via agent.resume(), run.resume(), or agent.run() on that session) | resumed_from | harness.resumed_from.run_id | | the first run of a session made by store.branch() | branched_from | harness.branched_from.session_id, harness.branched_from.run_id | | a new turn (agent.run()) on a session whose last run completed | continued_from | harness.continued_from.run_id |

The link points at the previous root span only — a third run links to the second, not the first. Fork branch spans never get a link. The linked context is marked remote.

How it works. Right after a run starts, core asks the observer's carry hook for a string map to keep. This observer returns the root span's context as W3C traceparent (and tracestate when there is one). Core saves it on the run's record (StoredRun.carrier) and hands it back as RunContext.resumedFrom.carrier (or branchedFrom.carrier, continuedFrom.carrier) to the run that continues it. The format is written and read only by this package, so it does not depend on the propagator your app configures.

When there is no link. The attributes are still set, so the runs stay correlated, but there is no link when:

  • the earlier run was not observed by this package (no observer, or only observers without carry);
  • its record has no carrier, or a malformed one (it is ignored; nothing is thrown or reported).

A branched session created by a store version that did not record its source gets neither a link nor the harness.branched_from.* attributes.

A run without a carrier is not skipped over: the next run gets no link rather than a link to an older run.

All segments of one request. When agent.run() is given a requestId, every root span of that turn — the first run and each resume — has harness.request.id. Query it to find every trace of one request. It is not added to fork branch spans or to the harness.run.duration metric.

One trace across a pause (recipe)

Links are the default because one trace across a pause is usually wrong: the root span of the first run has already ended, and a pause can last for days. If you still want the resumed run to be a child of the paused one, load the record, turn its carrier into a context, and give an observer built with that parentContext to this resume only:

import { ROOT_CONTEXT, propagation } from '@opentelemetry/api'

const paused = await store.load(agent.id, sessionId)
const parentContext = propagation.extract(ROOT_CONTEXT, paused?.carrier ?? {})

await agent.resume(answer, sessionId, interruptId, {
  observer: createOtelObserver(tracer, { parentContext }),
})

propagation.extract needs the W3C propagator, which NodeSDK and provider.register() install by default. The resumed root span then shares the paused run's trace, is a child of its root span, and still has its resumed_from link. Don't pass this observer to other runs: parentContext applies to every top-level run the observer sees.

Metric

Requires options.meterProvider.

| Metric | Instrument | Unit | Recorded | Attributes | |--------|-----------|------|----------|------------| | harness.run.duration | histogram | s | at the end of each top-level run (not branches, not abandoned runs) | harness.agent.id, harness.run.signal |

The meter is @noetaris/harness-otel with the package's version.

Active context

While your code runs inside a harness span, that span is the active OpenTelemetry context, so anything that reads context.active() sees it:

| Code running | Active span | |---|---| | a step's run function | harness.step {stepName} | | inside runTool(...) or ctx.within('tool.call', { toolCallId }, ...) | execute_tool {toolName} (with genai()) | | the request an LLM adapter sends to its provider | chat {modelId} (with genai()) |

So auto-instrumented libraries (an HTTP client, a database driver) nest under those spans, trace.getActiveSpan() returns them, and a logger that stamps trace_id and span_id from the active span correlates with the trace. The bridge only activates spans that are already open; it never starts or ends one on this path.

When you need a context manager

Making a span active needs a registered context manager — for example the AsyncLocalStorageContextManager that NodeTracerProvider.register() (or the Node SDK) installs.

| | With a context manager | Without one | |---|---|---| | step, branch and run spans | nested | nested | | chat / execute_tool spans (extensions) | under the active span: the step, or execute_tool for an LLM call made inside a tool | under the step span | | a sub agent started from a step or a tool | under that step or tool span | its own root (no parent) | | auto-instrumented calls | under the active harness span | not linked |

Without one the tree still nests under steps; only the ambient links are lost.

Sub agents

An agent started from a step or a tool nests under the span that is active there. Pass it the same observer:

// a step of the calling agent
run: async () => {
  await Promise.all([
    researcher.run({}, { observer }),
    reviewer.run({}, { observer }),
  ])
  return { done: true }
},
invoke_agent main                 (harness.run main without genai())
└─ harness.step work
   ├─ invoke_agent researcher
   │  └─ harness.step run
   └─ invoke_agent reviewer
      └─ harness.step run
  • Pass the observer to the sub agent's run(), and do not set parentContext on it. parentContext fixes the parent of every top-level run the observer sees, sub agents included, so they would stop nesting under the caller.
  • One observer instance serves the caller and its sub agents at once, including sub agents running in parallel: span state is kept per run, so each run keeps its own tree and starting a sub agent never ends the caller's spans.
  • After a resume, a sub agent started from the replayed step nests under the resumed run's step span.

Tools

Report a tool call with runTool from @noetaris/harness-types. It emits "tool.call", runs the tool inside the "tool.call" scope, then emits "tool.result". With genai() that gives an execute_tool span, active while the tool runs:

import { runTool } from '@noetaris/harness-types'

run: async (_state, ctx) => {
  const outputs = await Promise.all(
    toolCalls.map(call => runTool(ctx, call, () => toolImpls[call.name](call.input))),
  )
  return { outputs }
},
invoke_agent main
└─ harness.step act
   └─ execute_tool delegate
      └─ invoke_agent researcher      ← a sub agent called by the `delegate` tool
         └─ harness.step run

API

createOtelObserver(tracer, options?)

Returns an Observer for the spans and metric above. The tracer is yours; the bridge does not choose its instrumentation scope.

| Option | Type | Description | |--------|------|-------------| | extensions | OtelExtension[] | Extensions, driven in this order. See Extensions. | | meterProvider | MeterProvider | Enables metrics, for the bridge and its extensions. Omit to skip metric recording. | | parentContext | Context | OTel context for the root span. Defaults to context.active(). Applies to every top-level run this observer sees, including sub agents that share it. See One trace across a pause. | | attributes | Attributes | Extra attributes merged onto the root span (built-in attributes win on conflict). |

Extensions

An extension adds domain spans, attributes and metrics on top of the lifecycle spans. It is a factory: createOtelObserver calls it once with { tracer, meterProvider } and gets back its hooks, so one extension value can be passed to several observers without sharing instruments or state.

import type { OtelExtension } from '@noetaris/harness-otel'

/** Counts `cache.hit` events per run and puts the total on the root span. */
const cacheHits: OtelExtension = () => ({
  name: 'cache-hits',
  claims: ['cache.hit'],
  createState: () => ({ hits: 0 }),
  onEvent: ({ state }) => { state.hits++ },
  onRunEnd: ({ span, state, parent }) => {
    if (parent !== undefined) parent.hits += state.hits   // a branch: roll up into its run
    else span?.setAttribute('app.cache.hits', state.hits)
  },
})

const observer = createOtelObserver(tracer, { extensions: [cacheHits] })

| Hook | Called | |---|---| | name, claims | claims lists the event types the extension handles; the bridge does not add them as span events | | decorateRun(ctx) | top-level run only, before its root span starts: return a name and/or attributes for it | | createState(lineage) | once per lineage (a run, or a fork branch inside it), with its LineageInfo (agentId, sessionId, runId, branchPath?) | | onEvent({ ctx, type, payload, state, parent }) | every claimed event; start new spans under parent | | scopeSpan(scope, state) | for ctx.within(type, payload, fn): return the span to make active while fn runs | | onRunEnd({ lineage, signal, durationMs, error?, span, state, parent }) | at the end of every lineage, before the bridge ends the lineage's own spans |

Rules the bridge follows:

| Rule | Detail | |---|---| | Order | Opening a run: decorateRun of each extension, then the root span, then createState of each. Ending: each extension's onRunEnd, then the bridge ends the step and the run or branch span. Extensions run in array order. | | Root name and attributes | options.attributes < built-in attributes < each extension's attributes, in order. The last extension that returns a name names the root. | | parent | The active context when it holds a span; else a context with the lineage's step span (or run span). So without a context manager, new spans still nest under the step. | | state and parent in onRunEnd | parent is the containing run's state for the same extension, for a branch (use it to roll counts up); undefined for a top-level run. | | scopeSpan | The first extension that returns a span wins. Step scopes always use the step span. | | error in onRunEnd | Present exactly when the run ended with an error. Test for error, not for the signal. | | Your spans | End the spans you opened for a lineage in onRunEnd, whatever the signal — including '$abandoned', sent when a run restarts without ending. | | A hook that throws | The bridge still finishes its own work for that hook (the root span still ends), calls the other extensions, then rethrows the first error. If createState throws, the extension is skipped for that lineage. If scopeSpan throws, wrap throws before calling fn. If the factory throws, createOtelObserver throws. | | Inside agent.run() | Core isolates every observer call: the step's work still runs exactly once, and the error goes to the run's onObserverError resource (agent.run(input, { observer, onObserverError })) with the hook's name — 'wrap' for a scopeSpan failure, otherwise the failing hook ('onEvent', 'onRunEnd', …). | | A step whose run start was never seen | It still gets a lineage: createState runs and onRunEnd is called at its end, but the lineage has no span — span is undefined in onRunEnd. |

Migration from 0.6

0.7 moved everything GenAI-shaped into @noetaris/harness-otel-genai. Add extensions: [genai()] to keep LLM and tool spans.

| 0.6 | 0.7 without genai() | 0.7 with genai() | |---|---|---| | root invoke_agent {agentId} | harness.run {agentId} | invoke_agent {agentId} | | branch {name} | harness.branch {name} | same | | gen_ai.agent.id (root) | harness.agent.id | + gen_ai.agent.name | | gen_ai.conversation.id (root) | harness.session.id | + gen_ai.conversation.id | | gen_ai.operation.name (root) | — | invoke_agent | | gen_ai.step.name, gen_ai.step.outcome | harness.step.name, harness.step.outcome | same | | gen_ai.branch.name, gen_ai.branch.path | harness.branch.name, harness.branch.path | same | | chat {modelId} span, kind INTERNAL | span event llm.request / llm.response on the step | chat {modelId}, kind CLIENT | | execute_tool {toolName} span | span events tool.call / tool.result on the step | execute_tool {toolName} | | captureInputs, captureOutputs, captureToolIO, maxContentLength options | — | genai({ … }) options | | content span events gen_ai.content.prompt / .completion, gen_ai.tool.input / .output | — | JSON attributes gen_ai.input.messages, gen_ai.output.messages, gen_ai.tool.call.arguments / .result (+ gen_ai.tool.definitions) | | metric gen_ai.client.token.usage (gen_ai.token.type) | — | gen_ai.client.inference.usage.* counters and gen_ai.client.inference.operation.* histograms | | metric gen_ai.client.operation.duration = run duration | harness.run.duration | harness.run.duration and gen_ai.invoke_agent.duration | | responses paired with requests in LIFO order when no callId | callId is required (@noetaris/harness-types 0.8) | pairing by callId only |

Warning: with genai(), the name gen_ai.client.operation.duration still exists but now measures each chat call (gen_ai.operation.name = chat). A dashboard or alert on that name silently shows chat latencies, and a filter on gen_ai.operation.name = invoke_agent matches nothing. Move run-duration queries to harness.run.duration or gen_ai.invoke_agent.duration.

Limitations

A paused/resumed session produces one trace per run. OTel context is in-memory and does not survive an interrupt, a process boundary, or the pause gap, so each run starts a fresh root span (a new trace_id). This is by design — one continuous trace across an arbitrary pause would be an anti-pattern. The runs are tied together by span links and by the harness.session.id attribute on every root span (and gen_ai.conversation.id with genai()). A link is missing when the earlier run left no usable carrier, or when a branch seed predates branchedFrom; for one trace instead, see the recipe.

One observer instance can serve concurrent runs and the sub agents they start: span state is kept per run. Use a separate observer for a run only when it needs its own options, such as a different parentContext. The tracer and meterProvider are safe to share.

Related Packages

License

MIT