@jini-ai/diagnostics 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # @jini-ai/diagnostics
2
2
 
3
+ ## 0.5.0 — 2026-10-05
4
+
5
+ ### BREAKING (for hosts that implement the observability ports themselves)
6
+
7
+ - `ObservabilityPort` gains `trackDbQuery`, `trackOutboundCall` and `trackAgentRun`; `TraceSpanPort` gains `addEvent`, and `setStatus` takes an optional `description`; `TracerPort.startSpan` takes `kind: 'server' | 'client' | 'internal'` and an optional `{ parent }`. Ports built with `createObservabilityPort`/`createOtelObservabilityPort` or the no-op port need no change. `RequestTracker.run` is optional, so request trackers written before scoping still satisfy the port.
8
+
9
+ ### Added
10
+
11
+ - DB, outbound and agent-run signals: `instrumentStorageKernel` (in place, via a Kysely capture plugin; no SQL text crosses the port), `trackHttpClient`, and `trackFetch` (one outbound span per call of any fetch-shaped function; identity for the no-op port). The OTel adapter redacts: outbound URLs keep scheme/host/port only, inbound targets drop the query and blank secret shapes, errors are exported by type only.
12
+ - `isNoopObservabilityPort` and shared frozen no-op trackers, so decorators skip wrapping when observability is off.
13
+ - New `./observability/node` entry with `createAsyncLocalSpanScope` (`SpanScopePort` on `AsyncLocalStorage`); without a span scope every span is a root.
14
+
15
+ ### Fixed
16
+
17
+ - The OTel adapter's `trackRequest` records the `requestId` option as the `http.request.id` span attribute (it was ignored) and returns it on the tracker.
18
+ - Internal `@jini-ai/core` dependency is a caret range (`workspace:^`) instead of an exact pin.
19
+
3
20
  ## 0.4.0 — 2026-10-02
4
21
 
5
22
  ### BREAKING
@@ -9,6 +26,7 @@
9
26
 
10
27
  ## Unreleased
11
28
 
29
+ - The OTel adapter's `trackRequest` now honors `{ requestId }`: the id is recorded as the `http.request.id` span attribute and returned on the tracker. It was previously dropped.
12
30
  - **BREAKING:** Remove local `ClockPort`/`DiagnosticsClockPort`; all clocks use `Clock.nowMs()` from `@jini-ai/core/primitives`. Add core as a package dependency.
13
31
  - Share the eleven byte-pinned credential patterns with core while retaining all redaction/scanner export names and diagnostics-specific policy. Bundle text and JSON redaction also mask standalone provider credential shapes; ordinary IDs, hashes and paths stay readable.
14
32
  - Off-origin evidence copy now says "the inspected origin".
@@ -8,7 +8,8 @@ export interface RequestHookOptions {
8
8
  /** Adds request correlation and completed-request hooks using explicit ID and clock ports.
9
9
  * @param required Clock and request ID generator, scoped by the host.
10
10
  * @param options Optional logging, metrics and tracing adapters.
11
- * @returns Request tracking with exactly one completion event per request.
11
+ * @returns Request tracking with exactly one completion event per request; DB, outbound and
12
+ * agent-run signals go straight to the tracing adapter (the no-op without one).
12
13
  * @throws Hook errors propagate to the caller; adapters choose their own error policy.
13
14
  */
14
15
  export declare function createHookObservabilityPort({ clock, requestIdGenerator }: {
@@ -1,16 +1,20 @@
1
+ import { createNoopObservabilityPort } from './noop.js';
1
2
  /** Adds request correlation and completed-request hooks using explicit ID and clock ports.
2
3
  * @param required Clock and request ID generator, scoped by the host.
3
4
  * @param options Optional logging, metrics and tracing adapters.
4
- * @returns Request tracking with exactly one completion event per request.
5
+ * @returns Request tracking with exactly one completion event per request; DB, outbound and
6
+ * agent-run signals go straight to the tracing adapter (the no-op without one).
5
7
  * @throws Hook errors propagate to the caller; adapters choose their own error policy.
6
8
  */
7
9
  export function createHookObservabilityPort({ clock, requestIdGenerator }, { logger, metrics, tracing } = {}) {
8
- return { trackRequest(input, options = {}) {
10
+ const signals = tracing ?? createNoopObservabilityPort({});
11
+ return {
12
+ trackRequest(input, options = {}) {
9
13
  const requestId = options.requestId ?? requestIdGenerator.generate({});
10
14
  const startedAt = clock.nowMs();
11
15
  const tracker = tracing?.trackRequest(input, { requestId });
12
16
  let ended = false;
13
- return { requestId, end(outcome) {
17
+ return { requestId, run: (fn) => (tracker?.run ? tracker.run(fn) : fn()), end(outcome) {
14
18
  if (ended)
15
19
  return;
16
20
  ended = true;
@@ -19,6 +23,10 @@ export function createHookObservabilityPort({ clock, requestIdGenerator }, { log
19
23
  logger?.log(event);
20
24
  metrics?.recordRequest(event);
21
25
  } };
22
- } };
26
+ },
27
+ trackDbQuery: (input) => signals.trackDbQuery(input),
28
+ trackOutboundCall: (input) => signals.trackOutboundCall(input),
29
+ trackAgentRun: (input, options) => signals.trackAgentRun(input, options),
30
+ };
23
31
  }
24
32
  //# sourceMappingURL=hooks.js.map
@@ -1,14 +1,17 @@
1
1
  import type { ObservabilityConfig } from './config.js';
2
2
  import type { ExporterFactory, TracerProviderFactory, ObservabilityPort } from './ports.js';
3
+ import { type OtelAdapterOptions } from './otel.js';
3
4
  export * from './config.js';
4
5
  export * from './ports.js';
5
6
  export * from './noop.js';
6
7
  export * from './otel.js';
7
8
  export * from './hooks.js';
8
- /** Selects an adapter from explicit config; disabled telemetry never invokes either factory. */
9
+ export * from './instrumentation.js';
10
+ /** Selects an adapter from explicit config; disabled telemetry never invokes either factory.
11
+ * @param options Adapter options (host span scope); ignored when telemetry is disabled. */
9
12
  export declare function createObservabilityPort({ config, exporterFactory, tracerProviderFactory }: {
10
13
  config: ObservabilityConfig;
11
14
  exporterFactory: ExporterFactory;
12
15
  tracerProviderFactory: TracerProviderFactory;
13
- }): ObservabilityPort;
16
+ }, options?: OtelAdapterOptions): ObservabilityPort;
14
17
  //# sourceMappingURL=index.d.ts.map
@@ -5,10 +5,12 @@ export * from './ports.js';
5
5
  export * from './noop.js';
6
6
  export * from './otel.js';
7
7
  export * from './hooks.js';
8
- /** Selects an adapter from explicit config; disabled telemetry never invokes either factory. */
9
- export function createObservabilityPort({ config, exporterFactory, tracerProviderFactory }) {
8
+ export * from './instrumentation.js';
9
+ /** Selects an adapter from explicit config; disabled telemetry never invokes either factory.
10
+ * @param options Adapter options (host span scope); ignored when telemetry is disabled. */
11
+ export function createObservabilityPort({ config, exporterFactory, tracerProviderFactory }, options = {}) {
10
12
  if (!config.enabled)
11
13
  return createNoopObservabilityPort({});
12
- return createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory });
14
+ return createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory }, options);
13
15
  }
14
16
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,61 @@
1
+ import type { HttpClientPort } from "@jini-ai/core/primitives";
2
+ import type { ObservabilityPort } from './ports.js';
3
+ /**
4
+ * @file Decorators that put a host's existing chokepoints on the observability port: the storage
5
+ * kernel (every repo query, on every dialect) and the guarded HTTP client (every vetted egress call).
6
+ * Both return their input untouched for the no-op port, so a disabled install keeps the exact
7
+ * objects and call paths it had — no wrapper frame, no per-query plugin, no allocation.
8
+ */
9
+ export interface QueryDescription {
10
+ operation: string;
11
+ table?: string;
12
+ }
13
+ /** Operation and table of one Kysely operation node. Reads node kinds and identifiers only — never
14
+ * parameter values or statement text, so the description is safe to export whatever the query binds.
15
+ * A raw statement contributes its leading keyword alone (`pragma`, `select`), or `raw`. */
16
+ export declare function describeQueryNode({ node }: {
17
+ node: unknown;
18
+ }): QueryDescription;
19
+ /** The kernel surface the decorator replaces; `StorageKernel<DB>` from `@jini-ai/db/kernel` fits it. */
20
+ export interface InstrumentableKernel {
21
+ readonly dialect: string;
22
+ run(fn: (db: any) => unknown): Promise<unknown>;
23
+ transaction(fn: () => Promise<unknown>): Promise<unknown>;
24
+ query(statement: any): Promise<unknown>;
25
+ execute(statement: any): Promise<unknown>;
26
+ }
27
+ /**
28
+ * Tracks every kernel `run`/`transaction`/`query`/`execute` as one DB span, decorating the kernel
29
+ * IN PLACE. A replacement object would break identity-keyed lookups hosts already rely on (the
30
+ * SQLite driver's connection reverse cache, kernels cached per connection), and in-place keeps every
31
+ * holder of the same kernel covered. `run` bodies get the builder with a capture plugin, so the span
32
+ * is named from the first query the body builds (operation + table), never its SQL text.
33
+ * @param required The kernel and the port. A no-op port, or a kernel already decorated, is left alone.
34
+ * @returns The same kernel object.
35
+ * @complexity O(1) per call beyond one plugin pass per built query.
36
+ */
37
+ export declare function instrumentStorageKernel<K extends InstrumentableKernel>({ kernel, observability }: {
38
+ kernel: K;
39
+ observability: ObservabilityPort;
40
+ }): K;
41
+ /** Any `fetch`-shaped function: the global, a timeout wrapper, a SigV4 client's `fetch`. Structural,
42
+ * so this universal entry needs no DOM or undici types. */
43
+ export type FetchLike = (input: any, init?: any) => Promise<{
44
+ status: number;
45
+ }>;
46
+ /** One outbound span per call of a raw `fetch` — the egress paths that do not go through a guarded
47
+ * client (deploy hosts, git hosts, object stores, loopback). Input, init and the response pass through
48
+ * untouched; the span gets scheme/host/port and status only, like {@link trackHttpClient}.
49
+ * @returns `fetch` itself for the no-op port.
50
+ * @complexity O(1) per call. */
51
+ export declare function trackFetch<F extends FetchLike>({ fetch, observability }: {
52
+ fetch: F;
53
+ observability: ObservabilityPort;
54
+ }): F;
55
+ /** One outbound span per `send`, with the response status or the transport failure; the call itself
56
+ * is unchanged. Returns `client` itself for the no-op port. */
57
+ export declare function trackHttpClient({ client, observability }: {
58
+ client: HttpClientPort;
59
+ observability: ObservabilityPort;
60
+ }): HttpClientPort;
61
+ //# sourceMappingURL=instrumentation.d.ts.map
@@ -0,0 +1,139 @@
1
+ import { isNoopObservabilityPort } from './noop.js';
2
+ function tableName(node) {
3
+ const n = node;
4
+ if (n?.kind === 'AliasNode')
5
+ return tableName(n.node);
6
+ const name = n?.kind === 'TableNode' ? n.table?.identifier?.name : undefined;
7
+ return typeof name === 'string' ? name : undefined;
8
+ }
9
+ function withTable(operation, node) {
10
+ const table = tableName(node);
11
+ return table ? { operation, table } : { operation };
12
+ }
13
+ /** Operation and table of one Kysely operation node. Reads node kinds and identifiers only — never
14
+ * parameter values or statement text, so the description is safe to export whatever the query binds.
15
+ * A raw statement contributes its leading keyword alone (`pragma`, `select`), or `raw`. */
16
+ export function describeQueryNode({ node }) {
17
+ const n = node;
18
+ switch (n?.kind) {
19
+ case 'SelectQueryNode': return withTable('select', n.from?.froms?.[0]);
20
+ case 'InsertQueryNode': return withTable('insert', n.into);
21
+ case 'UpdateQueryNode': return withTable('update', n.table);
22
+ case 'DeleteQueryNode': return withTable('delete', n.from?.froms?.[0]);
23
+ case 'RawNode': {
24
+ // The keyword must end at a boundary: a fragment that opens with a quoted literal is not one.
25
+ const keyword = /^\s*([A-Za-z]+)(?![A-Za-z0-9_'"])/.exec(n.sqlFragments?.[0] ?? '')?.[1];
26
+ return { operation: keyword ? keyword.toLowerCase() : 'raw' };
27
+ }
28
+ default:
29
+ if (typeof n?.kind !== 'string')
30
+ return { operation: 'query' };
31
+ return { operation: n.kind.replace(/(Query)?Node$/, '').replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase() };
32
+ }
33
+ }
34
+ const INSTRUMENTED = new WeakSet();
35
+ async function settle({ tracker, describe }, work) {
36
+ let result;
37
+ try {
38
+ result = await tracker.run(work);
39
+ }
40
+ catch (error) {
41
+ tracker.end({ ...describe(), error });
42
+ throw error;
43
+ }
44
+ tracker.end(describe());
45
+ return result;
46
+ }
47
+ function rawDescription(statement) {
48
+ const toNode = statement?.toOperationNode;
49
+ return describeQueryNode({ node: typeof toNode === 'function' ? toNode.call(statement) : null });
50
+ }
51
+ /**
52
+ * Tracks every kernel `run`/`transaction`/`query`/`execute` as one DB span, decorating the kernel
53
+ * IN PLACE. A replacement object would break identity-keyed lookups hosts already rely on (the
54
+ * SQLite driver's connection reverse cache, kernels cached per connection), and in-place keeps every
55
+ * holder of the same kernel covered. `run` bodies get the builder with a capture plugin, so the span
56
+ * is named from the first query the body builds (operation + table), never its SQL text.
57
+ * @param required The kernel and the port. A no-op port, or a kernel already decorated, is left alone.
58
+ * @returns The same kernel object.
59
+ * @complexity O(1) per call beyond one plugin pass per built query.
60
+ */
61
+ export function instrumentStorageKernel({ kernel, observability }) {
62
+ if (isNoopObservabilityPort(observability) || INSTRUMENTED.has(kernel))
63
+ return kernel;
64
+ INSTRUMENTED.add(kernel);
65
+ const target = kernel;
66
+ const system = target.dialect === 'postgres' ? 'postgresql' : target.dialect;
67
+ const run = target.run.bind(target), transaction = target.transaction.bind(target);
68
+ const query = target.query.bind(target), execute = target.execute.bind(target);
69
+ target.run = (fn) => {
70
+ let seen;
71
+ const capture = {
72
+ transformQuery: ({ node }) => { seen ??= describeQueryNode({ node }); return node; },
73
+ transformResult: async ({ result }) => result,
74
+ };
75
+ const withCapture = (db) => {
76
+ const builder = db;
77
+ return typeof builder?.withPlugin === 'function' ? builder.withPlugin(capture) : db;
78
+ };
79
+ return settle({ tracker: observability.trackDbQuery({ system }), describe: () => seen ?? { operation: 'run' } }, () => run((db) => fn(withCapture(db))));
80
+ };
81
+ // Inner run() spans start inside the transaction's scope, so they nest under it.
82
+ target.transaction = (fn) => settle({ tracker: observability.trackDbQuery({ system }), describe: () => ({ operation: 'transaction' }) }, () => transaction(fn));
83
+ target.query = (statement) => settle({ tracker: observability.trackDbQuery({ system }), describe: () => rawDescription(statement) }, () => query(statement));
84
+ target.execute = (statement) => settle({ tracker: observability.trackDbQuery({ system }), describe: () => rawDescription(statement) }, () => execute(statement));
85
+ return kernel;
86
+ }
87
+ /** URL and method of one fetch call: `init.method` wins over a Request's own, as in `fetch` itself.
88
+ * Anything that is not a string, URL or Request-shaped object becomes '' (the adapter's `invalid-url`). */
89
+ function fetchTarget(input, init) {
90
+ const shaped = (typeof input === 'object' && input !== null ? input : {});
91
+ const raw = typeof input === 'string' ? input : shaped.href ?? shaped.url;
92
+ const method = init?.method ?? shaped.method;
93
+ return { url: typeof raw === 'string' ? raw : '', method: typeof method === 'string' ? method.toUpperCase() : 'GET' };
94
+ }
95
+ /** One outbound span per call of a raw `fetch` — the egress paths that do not go through a guarded
96
+ * client (deploy hosts, git hosts, object stores, loopback). Input, init and the response pass through
97
+ * untouched; the span gets scheme/host/port and status only, like {@link trackHttpClient}.
98
+ * @returns `fetch` itself for the no-op port.
99
+ * @complexity O(1) per call. */
100
+ export function trackFetch({ fetch, observability }) {
101
+ if (isNoopObservabilityPort(observability))
102
+ return fetch;
103
+ const tracked = async (input, init) => {
104
+ const tracker = observability.trackOutboundCall(fetchTarget(input, init));
105
+ let response;
106
+ try {
107
+ response = await tracker.run(() => fetch(input, init));
108
+ }
109
+ catch (error) {
110
+ tracker.end({ error });
111
+ throw error;
112
+ }
113
+ tracker.end({ statusCode: response.status });
114
+ return response;
115
+ };
116
+ return tracked;
117
+ }
118
+ /** One outbound span per `send`, with the response status or the transport failure; the call itself
119
+ * is unchanged. Returns `client` itself for the no-op port. */
120
+ export function trackHttpClient({ client, observability }) {
121
+ if (isNoopObservabilityPort(observability))
122
+ return client;
123
+ return {
124
+ async send(required, optional) {
125
+ const tracker = observability.trackOutboundCall({ method: required.request.method, url: required.request.url });
126
+ let response;
127
+ try {
128
+ response = await tracker.run(() => client.send(required, optional));
129
+ }
130
+ catch (error) {
131
+ tracker.end({ error });
132
+ throw error;
133
+ }
134
+ tracker.end({ statusCode: response.status });
135
+ return response;
136
+ },
137
+ };
138
+ }
139
+ //# sourceMappingURL=instrumentation.js.map
@@ -0,0 +1,12 @@
1
+ import type { SpanScopePort } from './ports.js';
2
+ /**
3
+ * The active span per async context, for Node hosts: pass it as the adapter's `scope` so a DB query
4
+ * or outbound call made while serving a request becomes that request span's child. Kept out of the
5
+ * universal `./observability` entry because AsyncLocalStorage is Node-only. A continuation resumed
6
+ * from a callback registered outside the scope (some stream/body-parser paths) sees no active span
7
+ * and starts a root span: it is never attributed to the wrong request.
8
+ * @param _required Empty; each call owns a fresh store.
9
+ * @returns A scope port over one AsyncLocalStorage instance.
10
+ */
11
+ export declare function createAsyncLocalSpanScope(_required: Record<string, never>): SpanScopePort;
12
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1,15 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ /**
3
+ * The active span per async context, for Node hosts: pass it as the adapter's `scope` so a DB query
4
+ * or outbound call made while serving a request becomes that request span's child. Kept out of the
5
+ * universal `./observability` entry because AsyncLocalStorage is Node-only. A continuation resumed
6
+ * from a callback registered outside the scope (some stream/body-parser paths) sees no active span
7
+ * and starts a root span: it is never attributed to the wrong request.
8
+ * @param _required Empty; each call owns a fresh store.
9
+ * @returns A scope port over one AsyncLocalStorage instance.
10
+ */
11
+ export function createAsyncLocalSpanScope(_required) {
12
+ const storage = new AsyncLocalStorage();
13
+ return { active: () => storage.getStore(), run: ({ span, fn }) => storage.run(span, fn) };
14
+ }
15
+ //# sourceMappingURL=node.js.map
@@ -1,4 +1,7 @@
1
1
  import type { ObservabilityPort } from './ports.js';
2
2
  /** Creates disabled telemetry; every request shares one frozen tracker without allocation. */
3
3
  export declare function createNoopObservabilityPort(_required: Record<string, never>): ObservabilityPort;
4
+ /** True for a port this module built. Decorators use it to skip wrapping entirely when telemetry is
5
+ * off, so a disabled install pays no per-query or per-call indirection, not merely no export. */
6
+ export declare function isNoopObservabilityPort(port: ObservabilityPort): boolean;
4
7
  //# sourceMappingURL=noop.d.ts.map
@@ -1,6 +1,22 @@
1
- const NOOP_TRACKER = Object.freeze({ end() { } });
1
+ const run = (fn) => fn();
2
+ const NOOP_TRACKER = Object.freeze({ end() { }, run });
3
+ // One frozen tracker serves every non-request signal too: their end() outcomes differ only in type.
4
+ const NOOP_SIGNAL_TRACKER = Object.freeze({ end() { }, run });
5
+ const NOOP_PORTS = new WeakSet();
2
6
  /** Creates disabled telemetry; every request shares one frozen tracker without allocation. */
3
7
  export function createNoopObservabilityPort(_required) {
4
- return { trackRequest: () => NOOP_TRACKER };
8
+ const port = {
9
+ trackRequest: () => NOOP_TRACKER,
10
+ trackDbQuery: () => NOOP_SIGNAL_TRACKER,
11
+ trackOutboundCall: () => NOOP_SIGNAL_TRACKER,
12
+ trackAgentRun: () => NOOP_SIGNAL_TRACKER,
13
+ };
14
+ NOOP_PORTS.add(port);
15
+ return port;
16
+ }
17
+ /** True for a port this module built. Decorators use it to skip wrapping entirely when telemetry is
18
+ * off, so a disabled install pays no per-query or per-call indirection, not merely no export. */
19
+ export function isNoopObservabilityPort(port) {
20
+ return NOOP_PORTS.has(port);
5
21
  }
6
22
  //# sourceMappingURL=noop.js.map
@@ -1,14 +1,28 @@
1
1
  import type { ObservabilityConfigEnabled } from './config.js';
2
- import type { ExporterFactory, TracerProviderFactory, ObservabilityPort } from './ports.js';
2
+ import type { ExporterFactory, TracerProviderFactory, ObservabilityPort, SpanScopePort } from './ports.js';
3
3
  export interface OtelAdapterDependencies {
4
4
  config: ObservabilityConfigEnabled;
5
5
  exporterFactory: ExporterFactory;
6
6
  tracerProviderFactory: TracerProviderFactory;
7
7
  }
8
- /** Builds request spans through injected provider/exporter factories. Hosts wrap their SDK here.
9
- * @param required Explicit config and structural factories.
10
- * @returns One adapter whose request spans end once, with the final route name and status.
8
+ export interface OtelAdapterOptions {
9
+ scope?: SpanScopePort;
10
+ }
11
+ type Attributes = Record<string, string | number>;
12
+ /** A low-cardinality error label: a SCREAMING_CASE code (ECONNREFUSED, SQLITE_BUSY), else the class
13
+ * name. Messages are never exported: they carry SQL fragments, hostnames, emails, even credentials. */
14
+ export declare function errorType(error: unknown): string;
15
+ /** Query and fragment are dropped (tokens ride there most often); secret-shaped path values are
16
+ * blanked. Ids stay: an operator searches by them, and a route pattern alone cannot name a record. */
17
+ export declare function redactRequestTarget(path: string): string;
18
+ /** Scheme, host and explicit port only. Paths carry bot tokens and signed-URL keys; userinfo carries passwords. */
19
+ export declare function outboundTargetAttributes(url: string): Attributes;
20
+ /** Builds request, DB, outbound and agent-run spans through injected provider/exporter factories.
21
+ * @param required Explicit config and structural factories. Hosts wrap their SDK here.
22
+ * @param options Optional host scope storage; with it, spans started inside a tracker's run() are its children.
23
+ * @returns One adapter whose spans end once, with final names, redacted attributes and error status.
11
24
  * @throws Provider/exporter errors propagate during setup. No globals or SDK imports are used.
12
25
  */
13
- export declare function createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory }: OtelAdapterDependencies): ObservabilityPort;
26
+ export declare function createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory }: OtelAdapterDependencies, { scope }?: OtelAdapterOptions): ObservabilityPort;
27
+ export {};
14
28
  //# sourceMappingURL=otel.d.ts.map
@@ -1,19 +1,77 @@
1
- /** Builds request spans through injected provider/exporter factories. Hosts wrap their SDK here.
2
- * @param required Explicit config and structural factories.
3
- * @returns One adapter whose request spans end once, with the final route name and status.
1
+ import { redactSecretShapes } from '../redaction/secrets-only.js';
2
+ /** A low-cardinality error label: a SCREAMING_CASE code (ECONNREFUSED, SQLITE_BUSY), else the class
3
+ * name. Messages are never exported: they carry SQL fragments, hostnames, emails, even credentials. */
4
+ export function errorType(error) {
5
+ const code = error?.code;
6
+ if (typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,63}$/.test(code))
7
+ return code;
8
+ if (error instanceof Error)
9
+ return error.name;
10
+ return typeof error;
11
+ }
12
+ /** Query and fragment are dropped (tokens ride there most often); secret-shaped path values are
13
+ * blanked. Ids stay: an operator searches by them, and a route pattern alone cannot name a record. */
14
+ export function redactRequestTarget(path) {
15
+ return redactSecretShapes({ text: path.replace(/[?#][\s\S]*$/, ''), policy: {} }).text;
16
+ }
17
+ /** Scheme, host and explicit port only. Paths carry bot tokens and signed-URL keys; userinfo carries passwords. */
18
+ export function outboundTargetAttributes(url) {
19
+ let parsed;
20
+ try {
21
+ parsed = new URL(url);
22
+ }
23
+ catch {
24
+ return { 'server.address': 'invalid-url' };
25
+ }
26
+ return {
27
+ 'url.scheme': parsed.protocol.replace(/:$/, ''), 'server.address': parsed.hostname,
28
+ ...(parsed.port ? { 'server.port': Number(parsed.port) } : {}),
29
+ };
30
+ }
31
+ // Interrupted means the run died with its process; canceled and abandoned are not proven failures.
32
+ const FAILED_RUN_STATUSES = new Set(['failed', 'interrupted']);
33
+ /** Wraps an end handler so a second end() is ignored. */
34
+ function once(handler) {
35
+ let ended = false;
36
+ return (outcome) => { if (ended)
37
+ return; ended = true; handler(outcome); };
38
+ }
39
+ /** Sets attributes, then the error label, status and exception event (type only), then ends. */
40
+ function finish({ span, attributes }, { failure, error } = {}) {
41
+ for (const [name, value] of Object.entries(attributes))
42
+ span.setAttribute({ name, value });
43
+ if (failure !== undefined) {
44
+ span.setAttribute({ name: 'error.type', value: failure });
45
+ span.setStatus({ code: 'error', description: failure });
46
+ if (error !== undefined)
47
+ span.addEvent({ name: 'exception', attributes: { 'exception.type': failure } });
48
+ }
49
+ span.end({});
50
+ }
51
+ /** Builds request, DB, outbound and agent-run spans through injected provider/exporter factories.
52
+ * @param required Explicit config and structural factories. Hosts wrap their SDK here.
53
+ * @param options Optional host scope storage; with it, spans started inside a tracker's run() are its children.
54
+ * @returns One adapter whose spans end once, with final names, redacted attributes and error status.
4
55
  * @throws Provider/exporter errors propagate during setup. No globals or SDK imports are used.
5
56
  */
6
- export function createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory }) {
57
+ export function createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory }, { scope } = {}) {
7
58
  const exporter = exporterFactory.create({ endpoint: config.endpoint });
8
59
  const provider = tracerProviderFactory.create({ serviceName: config.serviceName, exporter });
9
60
  const tracer = provider.getTracer({ name: config.tracerName });
10
- return { trackRequest(input) {
11
- const span = tracer.startSpan({ name: input.method, kind: 'server', attributes: { 'http.method': input.method, 'http.target': input.path } });
12
- let ended = false;
13
- return { end(outcome) {
14
- if (ended)
15
- return;
16
- ended = true;
61
+ function start({ name, kind, attributes }, { root = false } = {}) {
62
+ const parent = root ? undefined : scope?.active();
63
+ return tracer.startSpan({ name, kind, attributes }, parent ? { parent } : {});
64
+ }
65
+ function runIn(span) {
66
+ return (fn) => (scope ? scope.run({ span, fn }) : fn());
67
+ }
68
+ return {
69
+ trackRequest(input, { requestId } = {}) {
70
+ // The id the response echoes is recorded on the span, so a reported id finds its trace.
71
+ const span = start({ name: input.method, kind: 'server', attributes: {
72
+ 'http.method': input.method, 'http.target': redactRequestTarget(input.path), ...(requestId ? { 'http.request.id': requestId } : {}),
73
+ } });
74
+ return { ...(requestId ? { requestId } : {}), run: runIn(span), end: once((outcome) => {
17
75
  // Routing finishes after startSpan, so open with a provisional name and assign the final
18
76
  // pattern at end. The consumer port needs no separate rename operation to express that timing.
19
77
  span.updateName({ name: `${input.method} ${outcome.routePattern}` });
@@ -22,7 +80,41 @@ export function createOtelObservabilityPort({ config, exporterFactory, tracerPro
22
80
  if (outcome.statusCode >= 500)
23
81
  span.setStatus({ code: 'error' });
24
82
  span.end({});
25
- } };
26
- } };
83
+ }) };
84
+ },
85
+ trackDbQuery({ system }) {
86
+ const span = start({ name: 'db', kind: 'client', attributes: { 'db.system.name': system } });
87
+ return { run: runIn(span), end: once(({ operation, table, error }) => {
88
+ // Same provisional-name timing as requests: the query is built inside the tracked body.
89
+ const op = operation.toUpperCase();
90
+ span.updateName({ name: table ? `${op} ${table}` : op });
91
+ finish({ span, attributes: { 'db.operation.name': op, ...(table ? { 'db.collection.name': table } : {}) } }, error !== undefined ? { failure: errorType(error), error } : {});
92
+ }) };
93
+ },
94
+ trackOutboundCall({ method, url }) {
95
+ const target = outboundTargetAttributes(url);
96
+ const span = start({ name: `${method} ${target['server.address']}`, kind: 'client', attributes: { 'http.request.method': method, ...target } });
97
+ return { run: runIn(span), end: once(({ statusCode, error }) => {
98
+ const attributes = statusCode !== undefined ? { 'http.response.status_code': statusCode } : {};
99
+ if (error !== undefined)
100
+ return finish({ span, attributes }, { failure: errorType(error), error });
101
+ // Client-span semantics: a 4xx is this caller's failure, unlike a server span's 4xx.
102
+ finish({ span, attributes }, statusCode !== undefined && statusCode >= 400 ? { failure: String(statusCode) } : {});
103
+ }) };
104
+ },
105
+ trackAgentRun({ runId }, { conversationId, agentName } = {}) {
106
+ // A run outlives the request that started it, so it is its own trace rather than a long child.
107
+ const span = start({ name: agentName ? `invoke_agent ${agentName}` : 'invoke_agent', kind: 'internal', attributes: {
108
+ 'gen_ai.operation.name': 'invoke_agent', ...(agentName ? { 'gen_ai.agent.name': agentName } : {}),
109
+ ...(conversationId ? { 'gen_ai.conversation.id': conversationId } : {}), 'agent.run.id': runId,
110
+ } }, { root: true });
111
+ return { run: runIn(span), end: once(({ status, error }) => {
112
+ const attributes = { 'agent.run.status': status };
113
+ if (error !== undefined)
114
+ return finish({ span, attributes }, { failure: errorType(error), error });
115
+ finish({ span, attributes }, FAILED_RUN_STATUSES.has(status) ? { failure: status } : {});
116
+ }) };
117
+ },
118
+ };
27
119
  }
28
120
  //# sourceMappingURL=otel.js.map
@@ -4,6 +4,9 @@
4
4
  * replacing the instrumentation system itself, not merely its exporter backend. Add signals
5
5
  * only against real instrumentation call sites; guessed DB/outbound/agent shapes would couple
6
6
  * consumers to contracts whose lifecycle has not yet been established.
7
+ * The DB/outbound/agent signals below were each shaped after their first real call site: the
8
+ * storage kernel's run/transaction body, the guarded HTTP client's send, and a host's agent-run
9
+ * watcher. Inputs carry ids and fixed labels only; adapters own redaction of anything raw.
7
10
  */
8
11
  export interface RequestTrackingInput {
9
12
  method: string;
@@ -18,12 +21,63 @@ export interface RequestTrackingOutcome {
18
21
  statusCode: number;
19
22
  routePattern: string;
20
23
  }
24
+ /** Runs work inside a tracker's scope, so signals that work starts are attributed to it. */
25
+ export interface TrackerScope {
26
+ run<T>(fn: () => T): T;
27
+ }
21
28
  export interface RequestTracker {
22
29
  readonly requestId?: string;
23
30
  end(outcome: RequestTrackingOutcome): void;
31
+ /** Optional so adapters written before scoping still satisfy the port; callers fall back to fn(). */
32
+ run?<T>(fn: () => T): T;
33
+ }
34
+ /** `system` is the engine family (`sqlite`, `postgresql`); statement text never crosses the port. */
35
+ export interface DbQueryTrackingInput {
36
+ system: string;
37
+ }
38
+ /** Like a route pattern, the operation and table are known only once the query has been built. */
39
+ export interface DbQueryTrackingOutcome {
40
+ operation: string;
41
+ table?: string;
42
+ error?: unknown;
43
+ }
44
+ export interface DbQueryTracker extends TrackerScope {
45
+ end(outcome: DbQueryTrackingOutcome): void;
46
+ }
47
+ /** The raw URL is handed over whole; adapters keep scheme/host/port and drop path, query and userinfo. */
48
+ export interface OutboundCallTrackingInput {
49
+ method: string;
50
+ url: string;
51
+ }
52
+ /** `statusCode` when a response arrived, `error` when the call failed before one did. */
53
+ export interface OutboundCallTrackingOutcome {
54
+ statusCode?: number;
55
+ error?: unknown;
56
+ }
57
+ export interface OutboundCallTracker extends TrackerScope {
58
+ end(outcome: OutboundCallTrackingOutcome): void;
59
+ }
60
+ export interface AgentRunTrackingInput {
61
+ runId: string;
62
+ }
63
+ export interface AgentRunTrackingOptions {
64
+ conversationId?: string;
65
+ agentName?: string;
66
+ }
67
+ /** `interrupted`: the run vanished (its process restarted). `abandoned`: the watcher gave up unproven. */
68
+ export type AgentRunStatus = 'succeeded' | 'failed' | 'canceled' | 'interrupted' | 'abandoned';
69
+ export interface AgentRunTrackingOutcome {
70
+ status: AgentRunStatus;
71
+ error?: unknown;
72
+ }
73
+ export interface AgentRunTracker extends TrackerScope {
74
+ end(outcome: AgentRunTrackingOutcome): void;
24
75
  }
25
76
  export interface ObservabilityPort {
26
77
  trackRequest(input: RequestTrackingInput, options?: RequestTrackingOptions): RequestTracker;
78
+ trackDbQuery(input: DbQueryTrackingInput): DbQueryTracker;
79
+ trackOutboundCall(input: OutboundCallTrackingInput): OutboundCallTracker;
80
+ trackAgentRun(input: AgentRunTrackingInput, options?: AgentRunTrackingOptions): AgentRunTracker;
27
81
  }
28
82
  export interface RequestObservation extends RequestTrackingOutcome {
29
83
  requestId: string;
@@ -50,16 +104,33 @@ export interface TraceSpanPort {
50
104
  }): void;
51
105
  setStatus(required: {
52
106
  code: 'error';
107
+ description?: string;
108
+ }): void;
109
+ addEvent(required: {
110
+ name: string;
111
+ attributes: Record<string, string | number>;
53
112
  }): void;
54
113
  end(required: Record<string, never>): void;
55
114
  }
115
+ export type TraceSpanKind = 'server' | 'client' | 'internal';
56
116
  export interface TracerPort {
117
+ /** `parent` is a span this tracer returned earlier; absent means a root span. */
57
118
  startSpan(required: {
58
119
  name: string;
59
- kind: 'server';
120
+ kind: TraceSpanKind;
60
121
  attributes: Record<string, string | number>;
122
+ }, optional?: {
123
+ parent?: TraceSpanPort;
61
124
  }): TraceSpanPort;
62
125
  }
126
+ /** Host-owned active-span storage (Node: AsyncLocalStorage). Without one, every span is a root. */
127
+ export interface SpanScopePort {
128
+ active(): TraceSpanPort | undefined;
129
+ run<T>(required: {
130
+ span: TraceSpanPort;
131
+ fn: () => T;
132
+ }): T;
133
+ }
63
134
  export interface TracerProviderPort {
64
135
  getTracer(required: {
65
136
  name: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/diagnostics",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Diagnostics-bundle tooling: JSON/text secret redaction, log-source collection, manifest building, and zip packaging for support exports.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -15,6 +15,7 @@
15
15
  ".": "node",
16
16
  "./redaction/secrets-only": "universal",
17
17
  "./observability": "universal",
18
+ "./observability/node": "node",
18
19
  "./web-evidence": "universal",
19
20
  "./web-evidence/playwright": "node",
20
21
  "./domain-dns": "node"
@@ -41,6 +42,11 @@
41
42
  "import": "./dist/observability/index.js",
42
43
  "default": "./dist/observability/index.js"
43
44
  },
45
+ "./observability/node": {
46
+ "types": "./dist/observability/node.d.ts",
47
+ "import": "./dist/observability/node.js",
48
+ "default": "./dist/observability/node.js"
49
+ },
44
50
  "./web-evidence": {
45
51
  "types": "./dist/web-evidence/index.d.ts",
46
52
  "import": "./dist/web-evidence/index.js",
@@ -75,7 +81,7 @@
75
81
  },
76
82
  "dependencies": {
77
83
  "jszip": "^3.10.1",
78
- "@jini-ai/core": "0.4.0"
84
+ "@jini-ai/core": "^0.4.1"
79
85
  },
80
86
  "devDependencies": {
81
87
  "@vitest/coverage-v8": "^2.1.9"
@@ -1,8 +0,0 @@
1
- /** Credential-shape vocabulary for secret-only redaction; no I/O or host dependencies. */
2
- export interface SecretPattern {
3
- readonly name: string;
4
- readonly pattern: RegExp;
5
- }
6
- export declare const PEM_PATTERN_NAME = "PEM private key block";
7
- export declare const SECRET_PATTERNS: readonly SecretPattern[];
8
- //# sourceMappingURL=secret-patterns.d.ts.map
@@ -1,18 +0,0 @@
1
- /** Credential-shape vocabulary for secret-only redaction; no I/O or host dependencies. */
2
- // Named once and reused (by SECRET_PATTERNS here and by the guard's ALLOWLIST) rather than repeated
3
- // as a literal in multiple places.
4
- export const PEM_PATTERN_NAME = "PEM private key block";
5
- export const SECRET_PATTERNS = [
6
- { name: "Google API key (AIza)", pattern: /(?<![A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}(?![A-Za-z0-9_-])/ },
7
- { name: "Anthropic API key (sk-ant-)", pattern: /(?<![A-Za-z0-9_-])sk-ant-[A-Za-z0-9_-]{90,}/ },
8
- { name: "generic sk- secret key (OpenAI-shaped)", pattern: /(?<![A-Za-z0-9_-])sk-[A-Za-z0-9]{40,}/ },
9
- { name: "GitHub personal access token (classic, ghp_)", pattern: /(?<!\w)ghp_\w{36}(?!\w)/ },
10
- { name: "GitHub OAuth token (gho_)", pattern: /(?<!\w)gho_\w{36}(?!\w)/ },
11
- { name: "GitHub fine-grained PAT", pattern: /(?<!\w)github_pat_\w{80,}/ },
12
- { name: "npm access token", pattern: /(?<!\w)npm_\w{36}(?!\w)/ },
13
- { name: "Slack token", pattern: /(?<![A-Za-z0-9-])xox[baprs]-[A-Za-z0-9-]{12,}/ },
14
- { name: "AWS access key ID", pattern: /(?<![0-9A-Z])AKIA[0-9A-Z]{16}(?![0-9A-Z])/ },
15
- { name: "Fastmail app password (fm2_)", pattern: /(?<![A-Za-z0-9+/=])fm2_[A-Za-z0-9+/=]{20,}/ },
16
- { name: PEM_PATTERN_NAME, pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
17
- ];
18
- //# sourceMappingURL=secret-patterns.js.map