@jini-ai/diagnostics 0.6.12 → 0.6.15-rc.1
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 +30 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/memory-growth.d.ts +57 -0
- package/dist/memory-growth.js +105 -0
- package/dist/observability/delivery.d.ts +44 -0
- package/dist/observability/delivery.js +65 -0
- package/dist/observability/errors.d.ts +15 -0
- package/dist/observability/errors.js +25 -0
- package/dist/observability/fanout.d.ts +18 -0
- package/dist/observability/fanout.js +165 -0
- package/dist/observability/hooks.d.ts +2 -2
- package/dist/observability/hooks.js +7 -2
- package/dist/observability/index.d.ts +6 -0
- package/dist/observability/index.js +4 -0
- package/dist/observability/node.d.ts +3 -0
- package/dist/observability/node.js +3 -0
- package/dist/observability/noop.js +5 -0
- package/dist/observability/otel.d.ts +22 -5
- package/dist/observability/otel.js +108 -25
- package/dist/observability/ports.d.ts +78 -0
- package/dist/observability/report-error.d.ts +59 -0
- package/dist/observability/report-error.js +81 -0
- package/dist/observability/telemetry-test.d.ts +28 -0
- package/dist/observability/telemetry-test.js +46 -0
- package/dist/observability/tracker-noop.d.ts +6 -0
- package/dist/observability/tracker-noop.js +10 -0
- package/dist/observability/tracker-types.d.ts +61 -0
- package/dist/observability/tracker-types.js +2 -0
- package/dist/observability/tracker.d.ts +13 -0
- package/dist/observability/tracker.js +114 -0
- package/dist/redaction.d.ts +11 -0
- package/dist/redaction.js +65 -0
- package/package.json +8 -3
|
@@ -9,4 +9,7 @@ import type { SpanScopePort } from './ports.js';
|
|
|
9
9
|
* @returns A scope port over one AsyncLocalStorage instance.
|
|
10
10
|
*/
|
|
11
11
|
export declare function createAsyncLocalSpanScope(_required: Record<string, never>): SpanScopePort;
|
|
12
|
+
export { reportErrorOnce, redactedError, runWithErrorReportScope, type ErrorReportScope } from './report-error.js';
|
|
13
|
+
export { createTracker, createTrackerWarning } from "./tracker.js";
|
|
14
|
+
export { createTelemetryTestProbe } from "./telemetry-test.js";
|
|
12
15
|
//# sourceMappingURL=node.d.ts.map
|
|
@@ -12,4 +12,7 @@ export function createAsyncLocalSpanScope(_required) {
|
|
|
12
12
|
const storage = new AsyncLocalStorage();
|
|
13
13
|
return { active: () => storage.getStore(), run: ({ span, fn }) => storage.run(span, fn) };
|
|
14
14
|
}
|
|
15
|
+
export { reportErrorOnce, redactedError, runWithErrorReportScope } from './report-error.js';
|
|
16
|
+
export { createTracker, createTrackerWarning } from "./tracker.js";
|
|
17
|
+
export { createTelemetryTestProbe } from "./telemetry-test.js";
|
|
15
18
|
//# sourceMappingURL=node.js.map
|
|
@@ -6,10 +6,15 @@ const NOOP_PORTS = new WeakSet();
|
|
|
6
6
|
/** Creates disabled telemetry; every request shares one frozen tracker without allocation. */
|
|
7
7
|
export function createNoopObservabilityPort(_required) {
|
|
8
8
|
const port = {
|
|
9
|
+
supportsMetric: false,
|
|
10
|
+
activeTraceIds: () => undefined,
|
|
9
11
|
trackRequest: () => NOOP_TRACKER,
|
|
10
12
|
trackDbQuery: () => NOOP_SIGNAL_TRACKER,
|
|
11
13
|
trackOutboundCall: () => NOOP_SIGNAL_TRACKER,
|
|
12
14
|
trackAgentRun: () => NOOP_SIGNAL_TRACKER,
|
|
15
|
+
trackOperation: () => NOOP_SIGNAL_TRACKER,
|
|
16
|
+
reportError: () => false,
|
|
17
|
+
metric: () => { },
|
|
13
18
|
};
|
|
14
19
|
NOOP_PORTS.add(port);
|
|
15
20
|
return port;
|
|
@@ -10,14 +10,31 @@ export interface OtelAdapterOptions {
|
|
|
10
10
|
}
|
|
11
11
|
type Attributes = Record<string, string | number>;
|
|
12
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.
|
|
13
|
+
* name. Messages are never exported: they carry SQL fragments, hostnames, emails, even credentials.
|
|
14
|
+
* Both `error.code` and `Error.name` are writable secret channels (review 2026-10-25 #2):
|
|
15
|
+
* select the label, then redact and cap it
|
|
16
|
+
* to {@link MAX_ERROR_TYPE} (redact first: a cut could leave a secret prefix too short to match). */
|
|
14
17
|
export declare function errorType(error: unknown): string;
|
|
15
|
-
/**
|
|
16
|
-
*
|
|
17
|
-
|
|
18
|
+
/** Feature attributes are documented as ids and fixed labels, but a caller can still hand over a
|
|
19
|
+
* secret-shaped value (an unknown tool id straight from a request, review #1). Every string is
|
|
20
|
+
* redacted and capped before any SDK sees it; numbers pass. Every adapter applies this, so one careless
|
|
21
|
+
* call site cannot leak through one vendor.
|
|
22
|
+
* @param required The caller's attributes. @returns A fresh, redacted copy. @complexity O(total text). */
|
|
23
|
+
export declare function redactOperationAttributes({ attributes }: {
|
|
24
|
+
attributes: Readonly<Record<string, string | number>>;
|
|
25
|
+
}): Attributes;
|
|
26
|
+
/** Prefer a router-owned template. Otherwise drop query/fragment and replace sensitive-looking
|
|
27
|
+
* segments; raw ids no longer cross the export boundary (correlation belongs on explicit ids).
|
|
28
|
+
* @returns A bounded request target. @complexity O(p) path text.
|
|
29
|
+
*/
|
|
30
|
+
export declare function redactRequestTarget({ path }: {
|
|
31
|
+
path: string;
|
|
32
|
+
}, { routePattern }?: {
|
|
33
|
+
routePattern?: string;
|
|
34
|
+
}): string;
|
|
18
35
|
/** Scheme, host and explicit port only. Paths carry bot tokens and signed-URL keys; userinfo carries passwords. */
|
|
19
36
|
export declare function outboundTargetAttributes(url: string): Attributes;
|
|
20
|
-
/** Builds request, DB, outbound
|
|
37
|
+
/** Builds request, DB, outbound, agent-run and operation spans, and exception events for reported errors, through injected provider/exporter factories.
|
|
21
38
|
* @param required Explicit config and structural factories. Hosts wrap their SDK here.
|
|
22
39
|
* @param options Optional host scope storage; with it, spans started inside a tracker's run() are its children.
|
|
23
40
|
* @returns One adapter whose spans end once, with final names, redacted attributes and error status.
|
|
@@ -1,18 +1,68 @@
|
|
|
1
1
|
import { redactSecretShapes } from '../core/secrets-only.js';
|
|
2
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.
|
|
3
|
+
* name. Messages are never exported: they carry SQL fragments, hostnames, emails, even credentials.
|
|
4
|
+
* Both `error.code` and `Error.name` are writable secret channels (review 2026-10-25 #2):
|
|
5
|
+
* select the label, then redact and cap it
|
|
6
|
+
* to {@link MAX_ERROR_TYPE} (redact first: a cut could leave a secret prefix too short to match). */
|
|
4
7
|
export function errorType(error) {
|
|
5
8
|
const code = error?.code;
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
return error.name;
|
|
10
|
-
return typeof error;
|
|
9
|
+
const label = typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,63}$/.test(code)
|
|
10
|
+
? code : error instanceof Error ? String(error.name) : typeof error;
|
|
11
|
+
return redactLabel(label).slice(0, MAX_ERROR_TYPE) || 'Error';
|
|
11
12
|
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
const MAX_ERROR_TYPE = 64;
|
|
14
|
+
const MAX_ATTRIBUTE_TEXT = 256;
|
|
15
|
+
const MAX_ATTRIBUTES = 64;
|
|
16
|
+
const ATTRIBUTE_KEY = /^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/;
|
|
17
|
+
function redactLabel(text) {
|
|
18
|
+
return redactSecretShapes({ text, policy: {} }).text;
|
|
19
|
+
}
|
|
20
|
+
/** Feature attributes are documented as ids and fixed labels, but a caller can still hand over a
|
|
21
|
+
* secret-shaped value (an unknown tool id straight from a request, review #1). Every string is
|
|
22
|
+
* redacted and capped before any SDK sees it; numbers pass. Every adapter applies this, so one careless
|
|
23
|
+
* call site cannot leak through one vendor.
|
|
24
|
+
* @param required The caller's attributes. @returns A fresh, redacted copy. @complexity O(total text). */
|
|
25
|
+
export function redactOperationAttributes({ attributes }) {
|
|
26
|
+
const safe = {};
|
|
27
|
+
for (const name of Object.keys(attributes)) {
|
|
28
|
+
if (Object.keys(safe).length >= MAX_ATTRIBUTES)
|
|
29
|
+
break;
|
|
30
|
+
// Keys are a bounded label allow-list too: never export emails, URLs or credential-shaped keys.
|
|
31
|
+
if (!ATTRIBUTE_KEY.test(name) || redactLabel(name) !== name)
|
|
32
|
+
continue;
|
|
33
|
+
const value = attributes[name];
|
|
34
|
+
safe[name] = typeof value === 'string' ? redactLabel(value).slice(0, MAX_ATTRIBUTE_TEXT) : value;
|
|
35
|
+
}
|
|
36
|
+
return safe;
|
|
37
|
+
}
|
|
38
|
+
/** Decode before classifying; malformed encodings and non-label segments fail closed.
|
|
39
|
+
* Only short alphabetic route words survive; ids, emails and opaque tokens become placeholders.
|
|
40
|
+
* @returns A safe path segment. @complexity O(s) segment text.
|
|
41
|
+
*/
|
|
42
|
+
function safePathSegment({ segment }, _options = {}) {
|
|
43
|
+
let decoded;
|
|
44
|
+
try {
|
|
45
|
+
decoded = decodeURIComponent(segment);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return ':param';
|
|
49
|
+
}
|
|
50
|
+
if (decoded === '')
|
|
51
|
+
return '';
|
|
52
|
+
if (!/^[a-zA-Z-]{1,24}$/.test(decoded))
|
|
53
|
+
return ':param';
|
|
54
|
+
if (/^[a-fA-F]{8,}$/.test(decoded) || decoded.length >= 16)
|
|
55
|
+
return ':param';
|
|
56
|
+
return decoded;
|
|
57
|
+
}
|
|
58
|
+
/** Prefer a router-owned template. Otherwise drop query/fragment and replace sensitive-looking
|
|
59
|
+
* segments; raw ids no longer cross the export boundary (correlation belongs on explicit ids).
|
|
60
|
+
* @returns A bounded request target. @complexity O(p) path text.
|
|
61
|
+
*/
|
|
62
|
+
export function redactRequestTarget({ path }, { routePattern } = {}) {
|
|
63
|
+
if (routePattern && routePattern !== 'unmatched')
|
|
64
|
+
return routePattern.replace(/[?#][\s\S]*$/, '').slice(0, 1024);
|
|
65
|
+
return path.replace(/[?#][\s\S]*$/, '').split('/').map(segment => safePathSegment({ segment })).join('/').slice(0, 1024);
|
|
16
66
|
}
|
|
17
67
|
/** Scheme, host and explicit port only. Paths carry bot tokens and signed-URL keys; userinfo carries passwords. */
|
|
18
68
|
export function outboundTargetAttributes(url) {
|
|
@@ -36,19 +86,7 @@ function once(handler) {
|
|
|
36
86
|
return (outcome) => { if (ended)
|
|
37
87
|
return; ended = true; handler(outcome); };
|
|
38
88
|
}
|
|
39
|
-
/**
|
|
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.
|
|
89
|
+
/** Builds request, DB, outbound, agent-run and operation spans, and exception events for reported errors, through injected provider/exporter factories.
|
|
52
90
|
* @param required Explicit config and structural factories. Hosts wrap their SDK here.
|
|
53
91
|
* @param options Optional host scope storage; with it, spans started inside a tracker's run() are its children.
|
|
54
92
|
* @returns One adapter whose spans end once, with final names, redacted attributes and error status.
|
|
@@ -58,6 +96,20 @@ export function createOtelObservabilityPort({ config, exporterFactory, tracerPro
|
|
|
58
96
|
const exporter = exporterFactory.create({ endpoint: config.endpoint });
|
|
59
97
|
const provider = tracerProviderFactory.create({ serviceName: config.serviceName, exporter });
|
|
60
98
|
const tracer = provider.getTracer({ name: config.tracerName });
|
|
99
|
+
const reportedSpans = new WeakSet();
|
|
100
|
+
/** Sets final attributes and ends, preserving an exception already recorded by reportError.
|
|
101
|
+
* Sink errors propagate to the caller. @complexity O(a) time/space for a attributes. */
|
|
102
|
+
function finish({ span, attributes }, { failure, error } = {}) {
|
|
103
|
+
for (const [name, value] of Object.entries(attributes))
|
|
104
|
+
span.setAttribute({ name, value });
|
|
105
|
+
if (failure !== undefined && !reportedSpans.has(span)) {
|
|
106
|
+
span.setAttribute({ name: 'error.type', value: failure });
|
|
107
|
+
span.setStatus({ code: 'error', description: failure });
|
|
108
|
+
if (error !== undefined)
|
|
109
|
+
span.addEvent({ name: 'exception', attributes: { 'exception.type': failure } });
|
|
110
|
+
}
|
|
111
|
+
span.end({});
|
|
112
|
+
}
|
|
61
113
|
function start({ name, kind, attributes }, { root = false } = {}) {
|
|
62
114
|
const parent = root ? undefined : scope?.active();
|
|
63
115
|
return tracer.startSpan({ name, kind, attributes }, parent ? { parent } : {});
|
|
@@ -66,18 +118,23 @@ export function createOtelObservabilityPort({ config, exporterFactory, tracerPro
|
|
|
66
118
|
return (fn) => (scope ? scope.run({ span, fn }) : fn());
|
|
67
119
|
}
|
|
68
120
|
return {
|
|
121
|
+
supportsMetric: false,
|
|
122
|
+
activeTraceIds: (_required = {}, _optional = {}) => scope?.active()?.ids?.(),
|
|
123
|
+
// This structural tracing adapter has no metrics exporter; the provider plugin supplies it.
|
|
124
|
+
metric() { },
|
|
69
125
|
trackRequest(input, { requestId } = {}) {
|
|
70
126
|
// The id the response echoes is recorded on the span, so a reported id finds its trace.
|
|
71
127
|
const span = start({ name: input.method, kind: 'server', attributes: {
|
|
72
|
-
'http.method': input.method, 'http.target': redactRequestTarget(input.path), ...(requestId ? { 'http.request.id': requestId } : {}),
|
|
128
|
+
'http.method': input.method, 'http.target': redactRequestTarget({ path: input.path }), ...(requestId ? { 'http.request.id': requestId } : {}),
|
|
73
129
|
} });
|
|
74
130
|
return { ...(requestId ? { requestId } : {}), run: runIn(span), end: once((outcome) => {
|
|
75
131
|
// Routing finishes after startSpan, so open with a provisional name and assign the final
|
|
76
132
|
// pattern at end. The consumer port needs no separate rename operation to express that timing.
|
|
77
133
|
span.updateName({ name: `${input.method} ${outcome.routePattern}` });
|
|
78
134
|
span.setAttribute({ name: 'http.route', value: outcome.routePattern });
|
|
135
|
+
span.setAttribute({ name: 'http.target', value: redactRequestTarget({ path: input.path }, { routePattern: outcome.routePattern }) });
|
|
79
136
|
span.setAttribute({ name: 'http.status_code', value: outcome.statusCode });
|
|
80
|
-
if (outcome.statusCode >= 500)
|
|
137
|
+
if (outcome.statusCode >= 500 && !reportedSpans.has(span))
|
|
81
138
|
span.setStatus({ code: 'error' });
|
|
82
139
|
span.end({});
|
|
83
140
|
}) };
|
|
@@ -102,6 +159,32 @@ export function createOtelObservabilityPort({ config, exporterFactory, tracerPro
|
|
|
102
159
|
finish({ span, attributes }, statusCode !== undefined && statusCode >= 400 ? { failure: String(statusCode) } : {});
|
|
103
160
|
}) };
|
|
104
161
|
},
|
|
162
|
+
trackOperation({ name, attributes = {} }) {
|
|
163
|
+
const span = start({ name, kind: 'internal', attributes: redactOperationAttributes({ attributes }) });
|
|
164
|
+
return { run: runIn(span), end: once(({ outcome, failed, attributes: settled = {} }) => {
|
|
165
|
+
// The feature decides what counts as failure; its outcome label doubles as the error type.
|
|
166
|
+
finish({ span, attributes: redactOperationAttributes({ attributes: { ...settled, 'operation.outcome': outcome } }) }, failed ? { failure: redactLabel(outcome) } : {});
|
|
167
|
+
}) };
|
|
168
|
+
},
|
|
169
|
+
reportError({ error, context }) {
|
|
170
|
+
try {
|
|
171
|
+
// Inside a tracker's run() the exception lands on that tracker's span; elsewhere it is its own
|
|
172
|
+
// short root span. Type only, never the message: the same export rule errorType documents.
|
|
173
|
+
const active = scope?.active();
|
|
174
|
+
const span = active ?? start({ name: `error ${context.operation}`, kind: 'internal', attributes: redactOperationAttributes({ attributes: context.attributes ?? {} }) }, { root: true });
|
|
175
|
+
const type = errorType(error);
|
|
176
|
+
span.addEvent({ name: 'exception', attributes: { 'exception.type': type, 'operation.name': context.operation } });
|
|
177
|
+
span.setAttribute({ name: 'error.type', value: type });
|
|
178
|
+
span.setStatus({ code: 'error', description: type });
|
|
179
|
+
reportedSpans.add(span);
|
|
180
|
+
if (!active)
|
|
181
|
+
span.end({});
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
// Reporting is best-effort: a broken exporter must not turn an already-handled failure into a crash.
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
},
|
|
105
188
|
trackAgentRun({ runId }, { conversationId, agentName } = {}) {
|
|
106
189
|
// A run outlives the request that started it, so it is its own trace rather than a long child.
|
|
107
190
|
const span = start({ name: agentName ? `invoke_agent ${agentName}` : 'invoke_agent', kind: 'internal', attributes: {
|
|
@@ -73,11 +73,80 @@ export interface AgentRunTrackingOutcome {
|
|
|
73
73
|
export interface AgentRunTracker extends TrackerScope {
|
|
74
74
|
end(outcome: AgentRunTrackingOutcome): void;
|
|
75
75
|
}
|
|
76
|
+
/** Fixed labels and ids only (a tool id, a run id): never user text, paths, or values a caller sent. */
|
|
77
|
+
export type OperationAttributes = Readonly<Record<string, string | number>>;
|
|
78
|
+
/**
|
|
79
|
+
* A feature-level unit of work (one tool call, one publish, one backup) that no transport signal
|
|
80
|
+
* names: the HTTP request, DB queries and outbound calls it makes nest under it. `name` is a fixed
|
|
81
|
+
* dotted label (`tool.call`), never per-call text, so grouping stays bounded.
|
|
82
|
+
*/
|
|
83
|
+
export interface OperationTrackingInput {
|
|
84
|
+
name: string;
|
|
85
|
+
attributes?: OperationAttributes;
|
|
86
|
+
}
|
|
87
|
+
/** `outcome` is the feature's own fixed label (`completed`, `denied`, `timed-out`); `failed` says
|
|
88
|
+
* whether that outcome is a failure, which only the feature can judge (a denial is not one). */
|
|
89
|
+
export interface OperationTrackingOutcome {
|
|
90
|
+
outcome: string;
|
|
91
|
+
failed: boolean;
|
|
92
|
+
attributes?: OperationAttributes;
|
|
93
|
+
}
|
|
94
|
+
export interface OperationTracker extends TrackerScope {
|
|
95
|
+
end(outcome: OperationTrackingOutcome): void;
|
|
96
|
+
}
|
|
97
|
+
/** Correlation assigned by an active tracing implementation; readers never generate IDs. */
|
|
98
|
+
export interface TraceIds {
|
|
99
|
+
readonly traceId: string;
|
|
100
|
+
readonly spanId: string;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* An error worth an incident report (an error tracker's issue; a trace's exception event), as
|
|
104
|
+
* opposed to an expected failure a tracker's outcome already records. `error` is handed over raw:
|
|
105
|
+
* adapters own redaction (see `describeReportedError`), exactly as they do for request targets.
|
|
106
|
+
*/
|
|
107
|
+
export interface ErrorReport {
|
|
108
|
+
error: unknown;
|
|
109
|
+
context: {
|
|
110
|
+
operation: string;
|
|
111
|
+
attributes?: OperationAttributes;
|
|
112
|
+
level?: 'warning' | 'error';
|
|
113
|
+
trace?: TraceIds;
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/** Native crash upload configuration. Provider-specific field names stay opaque to hosts. */
|
|
117
|
+
export interface CrashUpload {
|
|
118
|
+
submitURL: string;
|
|
119
|
+
globalExtra: Readonly<Record<string, string>>;
|
|
120
|
+
}
|
|
121
|
+
/** Vendor-neutral numeric measurement; names and units are fixed labels, never user text. */
|
|
122
|
+
export interface MetricInput {
|
|
123
|
+
name: string;
|
|
124
|
+
value: number;
|
|
125
|
+
}
|
|
126
|
+
export interface MetricOptions {
|
|
127
|
+
kind?: 'counter' | 'gauge' | 'histogram';
|
|
128
|
+
unit?: string;
|
|
129
|
+
attributes?: OperationAttributes;
|
|
130
|
+
}
|
|
76
131
|
export interface ObservabilityPort {
|
|
132
|
+
/** Current structural tracing scope, absent outside a trace. Never generates an ID. */
|
|
133
|
+
activeTraceIds?(required?: Record<string, never>, optional?: Record<string, never>): TraceIds | undefined;
|
|
134
|
+
/** Explicit capability: a callable noop metric does not imply local metric admission. */
|
|
135
|
+
readonly supportsMetric?: boolean;
|
|
136
|
+
/** Records one measurement; adapters without a metrics backend use a no-op. */
|
|
137
|
+
metric(input: MetricInput, options?: MetricOptions): void | Promise<void>;
|
|
77
138
|
trackRequest(input: RequestTrackingInput, options?: RequestTrackingOptions): RequestTracker;
|
|
78
139
|
trackDbQuery(input: DbQueryTrackingInput): DbQueryTracker;
|
|
79
140
|
trackOutboundCall(input: OutboundCallTrackingInput): OutboundCallTracker;
|
|
80
141
|
trackAgentRun(input: AgentRunTrackingInput, options?: AgentRunTrackingOptions): AgentRunTracker;
|
|
142
|
+
trackOperation(input: OperationTrackingInput): OperationTracker;
|
|
143
|
+
/** Called inside a tracker's run() it is attributed to that tracker's work. False refuses local admission; void accepts it. */
|
|
144
|
+
reportError(report: ErrorReport): boolean | void | Promise<boolean | void>;
|
|
145
|
+
/** Configuration only; the host owns crash collection, consent and upload lifecycle. */
|
|
146
|
+
crashUpload?(required: {
|
|
147
|
+
release: string;
|
|
148
|
+
environment: string;
|
|
149
|
+
}, optional?: Record<string, never>): CrashUpload;
|
|
81
150
|
}
|
|
82
151
|
export interface RequestObservation extends RequestTrackingOutcome {
|
|
83
152
|
requestId: string;
|
|
@@ -95,6 +164,8 @@ export interface RequestIdGenerator {
|
|
|
95
164
|
}
|
|
96
165
|
/** Structural SDK adapters are host-owned; no provider registration or ambient config is used. */
|
|
97
166
|
export interface TraceSpanPort {
|
|
167
|
+
/** IDs assigned by the tracing implementation, absent on legacy adapters. */
|
|
168
|
+
ids?(required?: Record<string, never>, optional?: Record<string, never>): TraceIds | undefined;
|
|
98
169
|
updateName(required: {
|
|
99
170
|
name: string;
|
|
100
171
|
}): void;
|
|
@@ -147,4 +218,11 @@ export interface TracerProviderFactory {
|
|
|
147
218
|
exporter: unknown;
|
|
148
219
|
}): TracerProviderPort;
|
|
149
220
|
}
|
|
221
|
+
/** What a vendor provider subpath returns: the port plus the host-owned lifecycle hook. The host
|
|
222
|
+
* registers `dispose` with its teardown (a closed site, a stopped process) so SDK clients, timers
|
|
223
|
+
* and exit listeners are released (review 2026-10-25 #6). `dispose` never throws. */
|
|
224
|
+
export interface ObservabilityAdapter {
|
|
225
|
+
port: ObservabilityPort;
|
|
226
|
+
dispose(): Promise<void>;
|
|
227
|
+
}
|
|
150
228
|
//# sourceMappingURL=ports.d.ts.map
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { ObservabilityPort } from "./ports.js";
|
|
2
|
+
/**
|
|
3
|
+
* @file The shared way a host hands an error to `ObservabilityPort.reportError` (provider wave 2,
|
|
4
|
+
* 2026-10-25): request 5xx, process guards, assistant failures and `trackAsyncOperation` all come
|
|
5
|
+
* through here, so each failure reaches the error tracker ONCE and already redacted.
|
|
6
|
+
*
|
|
7
|
+
* Once: an error object is reported at most once per port in an occurrence (a publish failure reported by its
|
|
8
|
+
* operation and then surfacing as the request's 500 is one incident, not two), and a request whose
|
|
9
|
+
* work already reported something is not reported again as a bare 5xx (`runWithErrorReportScope`).
|
|
10
|
+
* Redacted: message and stack go through Jini's `redactSecrets` before the port sees them; the port's
|
|
11
|
+
* adapters redact again, which is idempotent. Attributes are fixed labels and ids only — callers
|
|
12
|
+
* never pass request bodies, headers, cookies, query strings or user text.
|
|
13
|
+
*/
|
|
14
|
+
type Attributes = Readonly<Record<string, string | number>>;
|
|
15
|
+
/** Per-request state: did anything inside this request report an error yet? */
|
|
16
|
+
export interface ErrorReportScope {
|
|
17
|
+
reported: boolean;
|
|
18
|
+
errors?: WeakMap<ObservabilityPort, WeakSet<object>>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Runs `work` (normally Express's `next`) with `scope` as the current request's report scope, so a
|
|
22
|
+
* report from anywhere inside it marks the request as reported.
|
|
23
|
+
* @complexity O(1) around `work`.
|
|
24
|
+
*/
|
|
25
|
+
export declare function runWithErrorReportScope<T>({ scope, work }: {
|
|
26
|
+
scope: ErrorReportScope;
|
|
27
|
+
work: () => T;
|
|
28
|
+
}, { reuseCurrent }?: {
|
|
29
|
+
reuseCurrent?: boolean;
|
|
30
|
+
}): T;
|
|
31
|
+
type ExactSecrets = readonly string[] | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* A copy of `error` with its message and stack redacted, or the original when nothing needed
|
|
34
|
+
* redacting (so identity survives for callers that compare). Non-Error throws become an Error.
|
|
35
|
+
* `exactSecrets` (e.g. the credential a failing call used) are blanked even without a known shape.
|
|
36
|
+
* @complexity O(n) in message + stack length.
|
|
37
|
+
*/
|
|
38
|
+
export declare function redactedError({ error }: {
|
|
39
|
+
error: unknown;
|
|
40
|
+
}, { exactSecrets }?: {
|
|
41
|
+
exactSecrets?: ExactSecrets;
|
|
42
|
+
}): Error;
|
|
43
|
+
/**
|
|
44
|
+
* Reports once per port and occurrence, after redaction. Without a request/trace scope each call
|
|
45
|
+
* is an independent occurrence. Failed/noop delivery leaves both dedup and bare-5xx fallback open.
|
|
46
|
+
* @returns Synchronous local admission; pending async admission returns false and marks on success.
|
|
47
|
+
* @complexity O(n) in the error's message + stack length; scope state is weakly held.
|
|
48
|
+
*/
|
|
49
|
+
export declare function reportErrorOnce(required: {
|
|
50
|
+
observability: ObservabilityPort | undefined;
|
|
51
|
+
error: unknown;
|
|
52
|
+
operation: string;
|
|
53
|
+
}, optional?: {
|
|
54
|
+
attributes?: Attributes;
|
|
55
|
+
exactSecrets?: ExactSecrets;
|
|
56
|
+
level?: 'warning' | 'error';
|
|
57
|
+
}): boolean;
|
|
58
|
+
export {};
|
|
59
|
+
//# sourceMappingURL=report-error.d.ts.map
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { redactSecrets } from "@jini-ai/core";
|
|
3
|
+
const requestScope = new AsyncLocalStorage();
|
|
4
|
+
/**
|
|
5
|
+
* Runs `work` (normally Express's `next`) with `scope` as the current request's report scope, so a
|
|
6
|
+
* report from anywhere inside it marks the request as reported.
|
|
7
|
+
* @complexity O(1) around `work`.
|
|
8
|
+
*/
|
|
9
|
+
export function runWithErrorReportScope({ scope, work }, { reuseCurrent = false } = {}) {
|
|
10
|
+
return requestScope.run(reuseCurrent ? requestScope.getStore() ?? scope : scope, work);
|
|
11
|
+
}
|
|
12
|
+
const redact = (text, exactSecrets) => redactSecrets({ input: text }, exactSecrets ? { exactSecrets } : {});
|
|
13
|
+
/**
|
|
14
|
+
* A copy of `error` with its message and stack redacted, or the original when nothing needed
|
|
15
|
+
* redacting (so identity survives for callers that compare). Non-Error throws become an Error.
|
|
16
|
+
* `exactSecrets` (e.g. the credential a failing call used) are blanked even without a known shape.
|
|
17
|
+
* @complexity O(n) in message + stack length.
|
|
18
|
+
*/
|
|
19
|
+
export function redactedError({ error }, { exactSecrets } = {}) {
|
|
20
|
+
if (!(error instanceof Error))
|
|
21
|
+
return new Error(redact(typeof error === "string" ? error : `non-Error thrown: ${typeof error}`, exactSecrets));
|
|
22
|
+
const message = redact(error.message, exactSecrets);
|
|
23
|
+
const stack = error.stack === undefined ? undefined : redact(error.stack, exactSecrets);
|
|
24
|
+
if (message === error.message && stack === error.stack)
|
|
25
|
+
return error;
|
|
26
|
+
const copy = new Error(message);
|
|
27
|
+
copy.name = error.name;
|
|
28
|
+
if (stack === undefined)
|
|
29
|
+
delete copy.stack;
|
|
30
|
+
else
|
|
31
|
+
copy.stack = stack;
|
|
32
|
+
return copy;
|
|
33
|
+
}
|
|
34
|
+
/** Mark only successful hand-offs; scope owns the weak per-port incident inventory.
|
|
35
|
+
* @returns Local acceptance. @complexity O(1) time/space per error.
|
|
36
|
+
*/
|
|
37
|
+
function recordAdmission({ result, scope, observability, error }, _options = {}) {
|
|
38
|
+
if (result === false)
|
|
39
|
+
return false;
|
|
40
|
+
if (!scope)
|
|
41
|
+
return true;
|
|
42
|
+
scope.reported = true;
|
|
43
|
+
if (typeof error === "object" && error !== null) {
|
|
44
|
+
scope.errors ??= new WeakMap();
|
|
45
|
+
const errors = scope.errors.get(observability) ?? new WeakSet();
|
|
46
|
+
errors.add(error);
|
|
47
|
+
scope.errors.set(observability, errors);
|
|
48
|
+
}
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
/** Only an object successfully admitted to this port in this scope is a duplicate. @complexity O(1). */
|
|
52
|
+
function alreadyReported({ scope, observability, error }, _options = {}) {
|
|
53
|
+
return typeof error === "object" && error !== null && scope?.errors?.get(observability)?.has(error) === true;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Reports once per port and occurrence, after redaction. Without a request/trace scope each call
|
|
57
|
+
* is an independent occurrence. Failed/noop delivery leaves both dedup and bare-5xx fallback open.
|
|
58
|
+
* @returns Synchronous local admission; pending async admission returns false and marks on success.
|
|
59
|
+
* @complexity O(n) in the error's message + stack length; scope state is weakly held.
|
|
60
|
+
*/
|
|
61
|
+
export function reportErrorOnce(required, optional = {}) {
|
|
62
|
+
const { observability, error, operation } = required;
|
|
63
|
+
const scope = requestScope.getStore();
|
|
64
|
+
if (!observability)
|
|
65
|
+
return false;
|
|
66
|
+
if (alreadyReported({ scope, observability, error }))
|
|
67
|
+
return false;
|
|
68
|
+
try {
|
|
69
|
+
const result = observability.reportError({ error: redactedError({ error }, { exactSecrets: optional.exactSecrets }), context: { operation, ...(optional.attributes ? { attributes: optional.attributes } : {}), ...(optional.level ? { level: optional.level } : {}) } });
|
|
70
|
+
const accepted = (result) => recordAdmission({ result, scope, observability, error });
|
|
71
|
+
if (result instanceof Promise) {
|
|
72
|
+
void result.then(accepted).catch(() => { });
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
return accepted(result);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return false; /* never let reporting fail the caller */
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=report-error.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Tracker } from "./tracker-types.js";
|
|
2
|
+
export type TelemetryTestSignal = "error" | "span" | "analytics" | "metric";
|
|
3
|
+
export interface TelemetryTestResult {
|
|
4
|
+
/** Local provider acceptance, not confirmation of remote delivery. Consent can refuse analytics. */
|
|
5
|
+
providers: {
|
|
6
|
+
providerId: string;
|
|
7
|
+
signals: TelemetryTestSignal[];
|
|
8
|
+
}[];
|
|
9
|
+
}
|
|
10
|
+
export interface TelemetryTestProbe {
|
|
11
|
+
accepted(required: {
|
|
12
|
+
providerId: string;
|
|
13
|
+
method: string;
|
|
14
|
+
input: unknown;
|
|
15
|
+
supportsMetric?: boolean | undefined;
|
|
16
|
+
}, optional?: Record<string, never>): void;
|
|
17
|
+
send(required: {
|
|
18
|
+
tracker: Tracker;
|
|
19
|
+
error: Error;
|
|
20
|
+
userId: string;
|
|
21
|
+
}, optional?: Record<string, never>): Promise<TelemetryTestResult>;
|
|
22
|
+
}
|
|
23
|
+
/** Tests the same facade applications use; an async scope isolates simultaneous admin actions.
|
|
24
|
+
* @returns A diagnostic sender and a hook for the host's existing provider dispatch boundary.
|
|
25
|
+
* @complexity O(p) receipts per test for p providers; no retained receipts after its scope ends.
|
|
26
|
+
*/
|
|
27
|
+
export declare function createTelemetryTestProbe(_required: Record<string, never>, _options?: {}): TelemetryTestProbe;
|
|
28
|
+
//# sourceMappingURL=telemetry-test.d.ts.map
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
/** Recognize only the fixed diagnostic signals; incidental work in the same scope is ignored. */
|
|
3
|
+
function testSignal({ method, input }) {
|
|
4
|
+
if (method === "reportError" && input.context?.operation === "telemetry.test")
|
|
5
|
+
return "error";
|
|
6
|
+
if (method === "trackOperation" && input.name === "telemetry.test")
|
|
7
|
+
return "span";
|
|
8
|
+
if (method === "metric" && input.name === "telemetry.test")
|
|
9
|
+
return "metric";
|
|
10
|
+
if (method === "capture" && input.name === "telemetry_test")
|
|
11
|
+
return "analytics";
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
/** Tests the same facade applications use; an async scope isolates simultaneous admin actions.
|
|
15
|
+
* @returns A diagnostic sender and a hook for the host's existing provider dispatch boundary.
|
|
16
|
+
* @complexity O(p) receipts per test for p providers; no retained receipts after its scope ends.
|
|
17
|
+
*/
|
|
18
|
+
export function createTelemetryTestProbe(_required, _options = {}) {
|
|
19
|
+
const active = new AsyncLocalStorage();
|
|
20
|
+
return {
|
|
21
|
+
accepted({ providerId, method, input, supportsMetric }, _optional = {}) {
|
|
22
|
+
const receipts = active.getStore();
|
|
23
|
+
if (!receipts || !input || typeof input !== "object")
|
|
24
|
+
return;
|
|
25
|
+
const signal = testSignal({ method, input: input });
|
|
26
|
+
if (!signal)
|
|
27
|
+
return;
|
|
28
|
+
if (signal === "metric" && supportsMetric !== true)
|
|
29
|
+
return;
|
|
30
|
+
const signals = receipts.get(providerId) ?? new Set();
|
|
31
|
+
signals.add(signal);
|
|
32
|
+
receipts.set(providerId, signals);
|
|
33
|
+
},
|
|
34
|
+
async send({ tracker, error, userId }, _optional = {}) {
|
|
35
|
+
return active.run(new Map(), async () => {
|
|
36
|
+
await tracker.trace({ name: "telemetry.test", run: async () => {
|
|
37
|
+
tracker.metric({ name: "telemetry.test", value: 1 }, { kind: "counter" });
|
|
38
|
+
tracker.error({ error }, { context: { operation: "telemetry.test" } });
|
|
39
|
+
await tracker.capture({ name: "telemetry_test", userId });
|
|
40
|
+
} });
|
|
41
|
+
return { providers: [...active.getStore()].map(([providerId, signals]) => ({ providerId, signals: [...signals] })) };
|
|
42
|
+
});
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=telemetry-test.js.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Tracker } from "./tracker-types.js";
|
|
2
|
+
/** Shared inert facade for unconfigured hosts and optional collaborators. Work still runs once,
|
|
3
|
+
* returning its result or original application error. No provider or process state is touched.
|
|
4
|
+
* @complexity O(1) around the supplied callback. */
|
|
5
|
+
export declare function createNoopTracker(_required: Record<string, never>, _optional?: Record<string, never>): Tracker;
|
|
6
|
+
//# sourceMappingURL=tracker-noop.d.ts.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
const SPAN = Object.freeze({ setOutcome() { } });
|
|
2
|
+
const trace = async ({ run }) => run(SPAN);
|
|
3
|
+
const NOOP = Object.freeze({ capture() { }, error() { }, metric() { }, activeTraceIds: () => undefined, trace: trace });
|
|
4
|
+
/** Shared inert facade for unconfigured hosts and optional collaborators. Work still runs once,
|
|
5
|
+
* returning its result or original application error. No provider or process state is touched.
|
|
6
|
+
* @complexity O(1) around the supplied callback. */
|
|
7
|
+
export function createNoopTracker(_required, _optional = {}) {
|
|
8
|
+
return NOOP;
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=tracker-noop.js.map
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ProductAnalyticsPort, ProductEvent } from "@jini-ai/analytics/product";
|
|
2
|
+
import type { AgentRunTrackingInput, AgentRunTrackingOptions, AgentRunTrackingOutcome, ObservabilityPort, OperationAttributes, OperationTrackingOutcome, RequestTrackingInput, RequestTrackingOptions, RequestTrackingOutcome, MetricInput, MetricOptions } from "./ports.js";
|
|
3
|
+
/** Signals share one dependency; each method retains its own typed payload. */
|
|
4
|
+
export interface TrackerErrorContext {
|
|
5
|
+
level?: 'warning' | 'error';
|
|
6
|
+
operation?: string;
|
|
7
|
+
attributes?: OperationAttributes;
|
|
8
|
+
/** Convenience label for callers that only know the route. */
|
|
9
|
+
route?: string;
|
|
10
|
+
exactSecrets?: readonly string[];
|
|
11
|
+
}
|
|
12
|
+
/** Record a semantic outcome; the facade owns ending the underlying lifecycle. First outcome wins unless work throws; explicit cancellation is preserved. */
|
|
13
|
+
export interface TrackerSpan<Outcome = OperationTrackingOutcome> {
|
|
14
|
+
setOutcome(outcome: Outcome): void;
|
|
15
|
+
}
|
|
16
|
+
/** Fixed labels and ids only; never pass user text or credential values as span attributes. */
|
|
17
|
+
export interface OperationSpanOptions {
|
|
18
|
+
attributes?: OperationAttributes;
|
|
19
|
+
}
|
|
20
|
+
export interface RequestSpanOptions {
|
|
21
|
+
request: RequestTrackingInput & RequestTrackingOptions;
|
|
22
|
+
}
|
|
23
|
+
export interface AgentSpanOptions {
|
|
24
|
+
agent: AgentRunTrackingInput & AgentRunTrackingOptions;
|
|
25
|
+
}
|
|
26
|
+
/** Provider failures never escape. Application callback errors retain their original identity.
|
|
27
|
+
* Required fields precede optional settings; no provider-specific types cross this boundary. */
|
|
28
|
+
export interface Tracker {
|
|
29
|
+
/** Current tracing IDs, absent without an active span; optional for older host facades. */
|
|
30
|
+
activeTraceIds?(required?: Record<string, never>, optional?: Record<string, never>): import('./ports.js').TraceIds | undefined;
|
|
31
|
+
/** Awaitable local admission; does not wait for remote delivery. */
|
|
32
|
+
capture(input: Pick<ProductEvent, "name" | "userId">, options?: Pick<ProductEvent, "properties">): void | Promise<void>;
|
|
33
|
+
error(input: {
|
|
34
|
+
error: Error;
|
|
35
|
+
}, options?: {
|
|
36
|
+
context?: TrackerErrorContext;
|
|
37
|
+
}): void;
|
|
38
|
+
trace<T>(input: {
|
|
39
|
+
name: string;
|
|
40
|
+
run: (span: TrackerSpan<RequestTrackingOutcome>) => T | Promise<T>;
|
|
41
|
+
}, options: RequestSpanOptions): Promise<T>;
|
|
42
|
+
trace<T>(input: {
|
|
43
|
+
name: string;
|
|
44
|
+
run: (span: TrackerSpan<AgentRunTrackingOutcome>) => T | Promise<T>;
|
|
45
|
+
}, options: AgentSpanOptions): Promise<T>;
|
|
46
|
+
trace<T>(input: {
|
|
47
|
+
name: string;
|
|
48
|
+
run: (span: TrackerSpan) => T | Promise<T>;
|
|
49
|
+
}, options?: OperationSpanOptions): Promise<T>;
|
|
50
|
+
/** Numeric measurement; defaults to a gauge. Fixed names and low-cardinality attributes only. */
|
|
51
|
+
metric(input: MetricInput, options?: MetricOptions): void;
|
|
52
|
+
}
|
|
53
|
+
export interface TrackerProviders {
|
|
54
|
+
/** Already guarded by the host's existing consent policy; never guard a second time. */
|
|
55
|
+
productAnalytics?: ProductAnalyticsPort | undefined;
|
|
56
|
+
observability?: ObservabilityPort | undefined;
|
|
57
|
+
}
|
|
58
|
+
export interface TrackerOptions {
|
|
59
|
+
warn?: ((message: string) => void) | undefined;
|
|
60
|
+
}
|
|
61
|
+
//# sourceMappingURL=tracker-types.d.ts.map
|