@agentskit/observability β Functions
API functions for @agentskit/observability.
#Function: appendPiiAuditEvents()
appendPiiAuditEvents(
log,input):Promise<AuditEntry<PiiAuditPayload>[]>
Defined in: packages/observability/src/audit-log.ts:167
Append one audit record for each PII hit, storing offsets but no matched text.
#Parameters
#log
Signed audit log that receives the records.
#input
Actor, action, subject, hits, and optional reason to record.
#Returns
Promise<AuditEntry<PiiAuditPayload>[]>
The appended records in hit order.
#Function: axiomSink()
axiomSink(
config):LifecycleObserver
Defined in: packages/observability/src/axiom.ts:54
Create a batched HTTP sink that exports span start and end events to an Axiom dataset; failures are isolated.
#Parameters
#config
Axiom credentials, dataset, and optional endpoint and batch settings.
#Returns
A lifecycle observer with flush and shutdown methods.
#Function: buildTimeline()
buildTimeline(
steps):Timeline
Defined in: packages/observability/src/replay-timeline.ts:55
Build cumulative cost, token, and latency totals from recorded steps.
#Parameters
#steps
readonly ReplayStep[]
Checkpoints in chronological order.
#Returns
Timeline rows and totals, with a zero-length span for no steps.
#Function: buildTraceReport()
buildTraceReport(
traceId,spans):TraceReport
Defined in: packages/observability/src/trace-viewer.ts:21
Summarize a flat span list into a TraceReport β totals,
error count, wall-clock duration. The report JSON is the
on-disk format written by createFileTraceSink and the
input consumed by renderTraceViewerHtml.
#Parameters
#traceId
string
#spans
#Returns
#Function: chargebackReport()
chargebackReport(
samples,options?):ChargebackReport
Defined in: packages/observability/src/cost-chargeback.ts:144
Group call samples and calculate token and dollar totals.
#Parameters
#samples
Per-call usage records to aggregate.
#options?
ChargebackReportOptions = \{\}
Grouping, price overrides, and time-window filters.
#Returns
Rows sorted by descending spend, plus report totals.
#Throws
When a sample has invalid identity, token, or cost fields.
#Function: chargebackReportToCsv()
chargebackReportToCsv(
report):string
Defined in: packages/observability/src/cost-chargeback.ts:223
Serialize a chargeback report as CSV, including a final totals row.
#Parameters
#report
Aggregated report to serialize.
#Returns
string
CSV text with a trailing newline.
#Function: computeCost()
computeCost(
usage,price):number
Defined in: packages/observability/src/cost-guard.ts:179
Compute dollar cost from a usage record plus a price record. Hostile token counts are normalized to zero so NaN never poisons totals.
#Parameters
#usage
#completionTokens
number
#promptTokens
number
#price
#Returns
number
#Function: consoleAlertSink()
consoleAlertSink():
CostAlertSink
Defined in: packages/observability/src/cost-guard-alert-sinks.ts:13
Create an alert sink that writes cost alert details to stderr.
#Returns
A sink that formats one concise line for each alert.
#Function: consoleLogger()
consoleLogger(
config?):Observer
Defined in: packages/observability/src/console-logger.ts:85
Create an observer that writes agent events to stdout in human or JSON form.
#Parameters
#config?
ConsoleLoggerConfig = \{\}
Optional output format; defaults to the human-readable format.
#Returns
Observer
An observer that writes one formatted line per event.
#Function: costGuard()
costGuard(
options):Observer&object
Defined in: packages/observability/src/cost-guard.ts:301
A cost-guarded observer. Tracks token usage from llm:end events,
computes running cost incrementally per active model, aborts the run
when the budget is exceeded.
#Parameters
#options
#Returns
Observer & object
#Function: countTokens()
countTokens(
messages,options?):Promise<number>
Defined in: packages/observability/src/token-counter.ts:88
Count (or estimate) tokens for a list of messages.
When no custom counter is provided, falls back to the built-in
approximateCounter (zero deps, chars/4 heuristic).
#Parameters
#messages
readonly Pick<Message, "role" | "content">[]
#options?
TokenCounterOptions & object
#Returns
Promise<number>
#Example
import { countTokens } from '@agentskit/observability'
// Quick approximate count
const total = await countTokens(messages)
// With a custom provider-specific counter
const exact = await countTokens(messages, { counter: tiktokenCounter, model: 'gpt-4o' })#Function: countTokensDetailed()
countTokensDetailed(
messages,options?):Promise<TokenCountResult>
Defined in: packages/observability/src/token-counter.ts:99
Same as countTokens but returns per-message breakdown.
#Parameters
#messages
readonly Pick<Message, "role" | "content">[]
#options?
TokenCounterOptions & object
#Returns
Promise<TokenCountResult>
#Function: createAdvancedCostGuard()
createAdvancedCostGuard(
options):AdvancedCostGuard
Defined in: packages/observability/src/cost-guard-advanced.ts:75
Create a per-tenant cost guard with rolling caps and configurable enforcement.
#Parameters
#options
Budgets, caps, pricing, enforcement mode, and alert sinks.
#Returns
An observer with tenant state and control methods.
#Throws
When options are invalid or kill mode has no disableRuntime callback.
#Example
const guard = createAdvancedCostGuard({ budgets: { acme: 10 }, mode: 'reject' })#Function: createControlSurface()
createControlSurface(
options?):ControlSurface
Defined in: packages/observability/src/prod-control.ts:199
Create a transport-agnostic control surface for pausing, stepping, and inspecting runs.
#Parameters
#options?
ControlSurfaceOptions = \{\}
Event retention, run-id resolution, audit, and optional bearer-token settings.
#Returns
Observer and control methods for runtime hooks or an HTTP handler.
#Throws
When configured limits are not positive integers or a run id is invalid.
#Example
const control = createControlSurface({ defaultRunId: 'run-1' })
await control.awaitResume('run-1')#Function: createDevtoolsServer()
createDevtoolsServer(
options?):DevtoolsServer
Defined in: packages/observability/src/devtools.ts:50
Create a transport-agnostic event hub; new clients receive hello, buffered replay, and the live feed.
#Parameters
#options?
DevtoolsServerOptions = \{\}
Optional buffer size and server id.
#Returns
A runtime observer and transport-agnostic client management methods.
#Throws
When bufferSize is not a positive integer.
#Example
const devtools = createDevtoolsServer()
const detach = devtools.attach({ id: 'panel', send: envelope => socket.send(toSseFrame(envelope)) })#Function: createFileTraceSink()
createFileTraceSink(
dir):FileTraceSink
Defined in: packages/observability/src/trace-viewer.ts:118
Collect spans in memory and write a JSON report and optional offline HTML viewer to a directory.
#Parameters
#dir
string
Destination directory created on the first flush.
#Returns
Span callbacks, a copy of collected spans, and an async flush method.
#Example
const sink = createFileTraceSink('./traces')
const paths = await sink.flush({ traceId: 'run-42' })#Function: createInMemoryAuditStore()
createInMemoryAuditStore():
AuditLogStore
Defined in: packages/observability/src/audit-log.ts:197
Create a transient in-memory audit store for tests, demos, or short-lived deployments.
#Returns
An empty store implementing the audit log storage contract.
#Function: createInMemoryCostStore()
createInMemoryCostStore(
options?):InMemoryCostStore
Defined in: packages/observability/src/cost-store.ts:245
Process-local CostStore for development and tests. State is lost on restart
and is not shared between instances or isolates; use a durable store in production.
#Parameters
#options?
CostStoreOptions = \{\}
#Returns
#Function: createProviderCounter()
createProviderCounter(
options):TokenCounter
Defined in: packages/observability/src/token-counter.ts:168
Create a token counter backed by a real tokenizer.
This factory lets you plug in any tokenizer library (tiktoken, Anthropic's
tokenizer, etc.) while conforming to the TokenCounter contract.
#Parameters
#options
#Returns
TokenCounter
#Example
import { createProviderCounter } from '@agentskit/observability'
import { encoding_for_model } from 'tiktoken'
const enc = encoding_for_model('gpt-4o')
const tiktokenCounter = createProviderCounter({
name: 'tiktoken',
tokenize: (text) => [...enc.encode(text)],
})
const tokens = await countTokens(messages, { counter: tiktokenCounter })#Function: createSignedAuditLog()
createSignedAuditLog(
options):SignedAuditLog
Defined in: packages/observability/src/audit-log.ts:109
Hash-chained + HMAC-signed audit log. Every entry references the previous entry's hash, and every entry's body is signed with a caller-supplied secret. Together: tamper-evident (chain detects splicing) + authenticated (HMAC detects content edits by anyone who doesn't hold the secret).
Designed for SOC 2 / HIPAA friendly evidence. The store contract
is three methods so you can back the log with SQLite, S3 + GCS,
Postgres, or a read-only log service β anything append-only.
#Parameters
#options
#Returns
#Function: createTopologyGraph()
createTopologyGraph(
options?):TopologyGraph
Defined in: packages/observability/src/topology-graph.ts:108
Create an in-memory graph for topology dispatch and agent activity events.
#Parameters
#options?
TopologyGraphOptions = \{\}
Optional snippet length and clock override.
#Returns
A mutable graph with JSON, Mermaid, ASCII, and subscription APIs.
#Example
const graph = createTopologyGraph()
graph.ingest({ topology: 'swarm', phase: 'agent:start', agent: 'writer' })#Function: createTraceTracker()
createTraceTracker(
callbacks):object
Defined in: packages/observability/src/trace-tracker.ts:87
Build nested spans from a sequential AgentsKit event stream; same-kind events are assumed non-interleaved.
#Parameters
#callbacks
Receivers for span start and completion events.
#Returns
object
An event handler and flush method for closing open spans; correlation fields are copied to attributes.
#flush()
flush():
void
#Returns
void
#handle()
handle(
event):void
#Parameters
event
CorrelatedAgentEvent
#Returns
void
#Example
const tracker = createTraceTracker({ onSpanStart: save, onSpanEnd: save })
tracker.handle(event)#Function: datadogSink()
datadogSink(
config):LifecycleObserver
Defined in: packages/observability/src/datadog.ts:57
Create a batched HTTP sink that exports span events as JSON logs to Datadog; failures are isolated.
#Parameters
#config
API key, Datadog site, service tags, and batch settings.
#Returns
A lifecycle observer with flush and shutdown methods.
#Function: diffState()
diffState(
previous,next): readonlyStateDiffEntry[]
Defined in: packages/observability/src/replay-timeline.ts:99
Compare two shallow state records and return changed property entries.
#Parameters
#previous
Readonly<Record<string, unknown>>
State before the checkpoint.
#next
Readonly<Record<string, unknown>>
State at the checkpoint.
#Returns
readonly StateDiffEntry[]
Added, removed, or changed top-level properties in key order.
#Function: langsmith()
langsmith(
config):LangSmithObserver
Defined in: packages/observability/src/langsmith.ts:56
Create a lazy-loading observer that exports tracked spans to LangSmith without construction-time I/O.
#Parameters
#config
LangSmith credentials and optional project, endpoint, and error handler.
#Returns
An observer with flush and idempotent shutdown methods.
#Example
const observer = langsmith({ apiKey: process.env.LANGSMITH_API_KEY! })#Function: monthlyWindowKey()
monthlyWindowKey(
now):string
Defined in: packages/observability/src/cost-store.ts:127
UTC calendar month of now, formatted YYYY-MM.
#Parameters
#now
Date
#Returns
string
#Function: multiTenantCostGuard()
multiTenantCostGuard(
options):Observer&object
Defined in: packages/observability/src/cost-guard-multi-tenant.ts:96
Per-tenant cost-guard. Same incremental accounting as costGuard,
partitioned by tenant id, with separate budgets per tenant and a
no-abort default (the SaaS gateway typically enforces).
#Parameters
#options
#Returns
Observer & object
#Function: newRelicSink()
newRelicSink(
config):LifecycleObserver
Defined in: packages/observability/src/new-relic.ts:54
Create a batched HTTP sink that exports span events to New Relic Logs; failures are isolated.
#Parameters
#config
API key, region, service name, and batch settings.
#Returns
A lifecycle observer with flush and shutdown methods.
#Function: opentelemetry()
opentelemetry(
config?):OpenTelemetryObserver
Defined in: packages/observability/src/opentelemetry.ts:80
Create a lazy-loading observer that exports tracked spans through OpenTelemetry using the v2 spanProcessors config.
#Parameters
#config?
OpenTelemetryConfig = \{\}
Optional OTLP endpoint, service name, and error callback.
#Returns
An observer with flush and idempotent shutdown methods.
#Example
const observer = opentelemetry({ endpoint: 'http://localhost:4318/v1/traces' })#Function: positionAt()
positionAt(
steps,timeline,index):ReplayPosition
Defined in: packages/observability/src/replay-timeline.ts:134
Select a replay step and calculate its difference from the prior state.
#Parameters
#steps
readonly ReplayStep[]
Recorded steps used to read adjacent state snapshots.
#timeline
Timeline built from the same step sequence.
#index
number
Zero-based row index to select.
#Returns
The selected cumulative row and state difference.
#Throws
When the index is outside the timeline rows.
#Function: priceFor()
priceFor(
model,prices?):TokenPrice
Defined in: packages/observability/src/cost-guard.ts:104
Look up the best price match for a model id. Prefix match β 'gpt-4o-mini'
matches its own entry before 'gpt-4o'. Returns { input: 0, output: 0 }
(free) for unknown models. Use hasPriceFor or resolvePrice when
unknown-model handling must be explicit.
#Parameters
#model
string | undefined
#prices?
Record<string, TokenPrice> = DEFAULT_PRICES
#Returns
#Function: recordCostSpend()
recordCostSpend(
store,record):Promise<CostWindow>
Defined in: packages/observability/src/cost-store.ts:356
Record spend that already happened: reserve it without a ceiling, then commit it, and return the resulting window. Cost guards use this after each priced call. When the commit fails, the hold is released before the error is rethrown, so a failed write does not leave the amount reserved.
#Parameters
#store
#record
#Returns
Promise<CostWindow>
#Function: renderTraceViewerHtml()
renderTraceViewerHtml(
report):string
Defined in: packages/observability/src/trace-viewer.ts:52
Render a self-contained HTML page visualizing a TraceReport as
a gantt-style waterfall β no JS dependency, no network. Open
the output file in a browser for offline Jaeger-style debugging.
#Parameters
#report
#Returns
string
#Function: replayBisect()
replayBisect(
history,oracle,opts?):Promise<BisectVerdict>
Defined in: packages/observability/src/replay-bisect.ts:31
Locate the earliest change that flips the run from pass to fail.
Convention: index 0 is the oldest known-good change; higher indices are
newer. The oracle returns 'fail' for any index β₯ the culprit and 'pass'
before. Returns the first failing index, or all_clean / all_broken
when no transition exists.
#Parameters
#history
readonly object[]
#oracle
#opts?
BisectOpts = \{\}
#Returns
Promise<BisectVerdict>
#Function: replayEvents()
replayEvents<
E>(events,handlers):Promise<void>
Defined in: packages/observability/src/replay.ts:18
Replay events sequentially through each handler in registration order.
#Type Parameters
#E
E
#Parameters
#events
readonly E[]
Ordered event history to replay.
#handlers
readonly ReplayHandler<E>[]
Consumers invoked for each event.
#Returns
Promise<void>
A promise that resolves after every handler completes.
#Function: sloObserver()
sloObserver(
options?):SloObserver
Defined in: packages/observability/src/slo.ts:172
Create an observer that records SLO metrics and periodically emits burn-rate alerts.
#Parameters
#options?
SloOptions = \{\}
Optional targets, windows, alert sink, and clock.
#Returns
An observer with snapshot, Prometheus, OTEL, and stop methods.
#Throws
When a target or window has an invalid value.
#Example
const slo = sloObserver({ targets: { successRate: 0.995 } })#Function: throttle()
throttle(
sink,windowMs,now?):CostAlertSink
Defined in: packages/observability/src/cost-guard-alert-sinks.ts:62
Throttle alerts by tenant, window, type, and threshold for the given interval.
#Parameters
#sink
Sink to wrap.
#windowMs
number
Minimum interval between matching alerts.
#now?
() => number
Clock used to compare alert times; defaults to Date.now.
#Returns
A sink that forwards at most one matching alert per interval.
#Throws
When windowMs is not finite and positive.
#Function: toSseFrame()
toSseFrame(
envelope):string
Defined in: packages/observability/src/devtools.ts:135
Serialize one devtools envelope as an SSE data frame for Express, Hono, or Node HTTP.
#Parameters
#envelope
Message to serialize.
#Returns
string
A complete data: frame terminated by a blank line.
#Function: webhookAlertSink()
webhookAlertSink(
options):CostAlertSink
Defined in: packages/observability/src/cost-guard-alert-sinks.ts:38
Create a sink that posts cost alerts as JSON to a webhook endpoint.
#Parameters
#options
Endpoint and optional fetch implementation and headers.
#Returns
An async sink that rejects when the HTTP response is not successful.
#Function: wrapObserverWithRedaction()
wrapObserverWithRedaction(
inner,options):Observer
Defined in: packages/observability/src/redaction.ts:148
Wrap an observer so supported event content is redacted or tokenized before delivery.
#Parameters
#inner
Observer
Observer that receives the sanitized event copy.
#options
PII rules and optional tokenization or audit settings.
#Returns
Observer
An observer that forwards sanitized events to inner.
#Throws
In tokenize mode when vault or allowed roles are missing.