@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 CHANGED
@@ -1,5 +1,35 @@
1
1
  # @jini-ai/diagnostics
2
2
 
3
+ ## 0.6.13
4
+
5
+ ### Patch Changes
6
+
7
+ - 8395a5f: `combineObservabilityPorts`: a tracker whose `run()` throws (before or after its callback) or never calls it no longer blocks the application work or later scopes; the callback runs exactly once and its own result or error reaches the caller.
8
+ - 0728914: Engine guard clean-up (`pnpm guard` 106 -> 0): layer, subpath-isolation and module-state findings fixed by moving
9
+ shared contracts to their owners instead of reaching across domains. Additive public API: `@jini-ai/core/filesystem`
10
+ (guarded-reader contracts), `useFetchQueryScope` from `@jini-ai/ui` fetch-query (per-provider query scope),
11
+ `@jini-ai/chat/react` re-exports of the accepted-input, run-state and agent-plugin chat-state helpers. The Claude
12
+ filesystem probe cache in `@jini-ai/agent-runtime` is instance-owned. No behaviour change intended; host-facing
13
+ breaks are listed in `owner-store-to-server` and `guard-host-ports`.
14
+ - 4c95673: Redact selected error codes before export, invalidate stale product-analytics consent approvals,
15
+ and share platform-neutral privacy validation between product analytics and visitor ingestion. Async product-analytics consent now
16
+ requires `consentRevision`: without it a promised approval is dropped (fail closed); synchronous
17
+ consent is unchanged. `combineObservabilityPorts` now wraps a
18
+ single enabled adapter too, so its throws never reach the caller.
19
+ - 0b413ae: PROTOTYPE (cloud/observability-1025, not for release): `ObservabilityPort` gains `trackOperation` (feature-level unit of work) and `reportError` (incident report, adapter-redacted). Breaking for hand-written port implementations: both methods are required. Noop stays zero-allocation; `combineObservabilityPorts` fans out to several enabled adapters (none → noop; one or more → each adapter isolated); `describeReportedError` gives error-tracker adapters a redacted, capped type/message/stack.
20
+ - 803a949: Observability vendor adapters as provider subpaths: `@jini-ai/diagnostics/observability/opentelemetry` (moved from Tovu core) and `@jini-ai/diagnostics/observability/sentry`, each returning `{ port, dispose }` with optional peer SDKs. Review fixes: attribute strings and `Error.name` redacted and capped; fan-out isolates each adapter's tracker creation and end; Sentry root operations start fresh traces and never call `NodeClient#init()` or channel injection. `withToolCallObservability` exports a fixed label for unregistered tool ids and adds `user.id` (pseudonymous principal).
21
+ - 63bacc5: OpenTelemetry and Sentry observability adapters moved out of `@jini-ai/diagnostics` into the `observability-opentelemetry` and `observability-sentry` provider plugins of `@jini-ai/provider-plugins`. Removed: the `@jini-ai/diagnostics/observability/opentelemetry` and `/observability/sentry` subpaths and every `@opentelemetry/*` / `@sentry/node` dev and optional peer dependency. The OTel plugin accepts any OTLP/HTTP endpoint plus generic request headers. Packages bundled into plugin artifacts now ship their LICENSE file.
22
+ - Updated dependencies [7479159]
23
+ - Updated dependencies [c31264d]
24
+ - Updated dependencies [0728914]
25
+ - Updated dependencies [4c95673]
26
+ - Updated dependencies [6ecbdb2]
27
+ - Updated dependencies [af776cd]
28
+ - Updated dependencies [63bacc5]
29
+ - Updated dependencies [212cf50]
30
+ - @jini-ai/core@0.6.13
31
+ - @jini-ai/analytics@0.6.13
32
+
3
33
  ## 0.6.12
4
34
 
5
35
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -6,11 +6,12 @@
6
6
  * generic {agent, dir} list remains an owner decision; it must not change silently during cleanup.
7
7
  */
8
8
  export { DIAGNOSTICS_CONTENT_TYPE, DIAGNOSTICS_EXPORT_PATH, DIAGNOSTICS_FILENAME_PREFIX, } from "./contract.js";
9
- export { redactJsonValue, redactJsonText, redactText, type RedactionOptions, } from "./redaction.js";
9
+ export { redactJsonValue, redactJsonText, redactText, maskLocalPaths, type RedactionOptions, } from "./redaction.js";
10
10
  export { collectLogSource, collectLogSources, findMacOSCrashReports, type CollectedFile, type CrashReportLookup, type CrashReportOptions, type LogSource, type LogSourceKind, } from "./sources.js";
11
11
  export { buildManifest, buildMachineInfo, diagnosticsFileName, type DiagnosticsAppInfo, type DiagnosticsContext, type DiagnosticsManifest, type MachineInfo, } from "./manifest.js";
12
12
  export { buildDiagnosticsZip, type DiagnosticsExportInput, type DiagnosticsExportOptions, type DiagnosticsExportResult, } from "./zip.js";
13
13
  export { buildRunEventLogSources, buildAgentCliLogSources, type AgentCliLogOptions, } from "./agent-logs.js";
14
14
  export { createNodeDiagnosticsPorts } from "./node-ports.js";
15
+ export { aggregateProcessMemory, createMemoryGrowthDetector, type ProcessMemoryReading, type MemoryKindSummary, type MemoryGrowthWarning } from './memory-growth.js';
15
16
  export type { DiagnosticsFilesystemPort, DiagnosticsSystemPort, DiagnosticsArchivePort, DiagnosticsArchiveFactoryPort, DiagnosticsPorts } from "./ports.js";
16
17
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -6,10 +6,11 @@
6
6
  * generic {agent, dir} list remains an owner decision; it must not change silently during cleanup.
7
7
  */
8
8
  export { DIAGNOSTICS_CONTENT_TYPE, DIAGNOSTICS_EXPORT_PATH, DIAGNOSTICS_FILENAME_PREFIX, } from "./contract.js";
9
- export { redactJsonValue, redactJsonText, redactText, } from "./redaction.js";
9
+ export { redactJsonValue, redactJsonText, redactText, maskLocalPaths, } from "./redaction.js";
10
10
  export { collectLogSource, collectLogSources, findMacOSCrashReports, } from "./sources.js";
11
11
  export { buildManifest, buildMachineInfo, diagnosticsFileName, } from "./manifest.js";
12
12
  export { buildDiagnosticsZip, } from "./zip.js";
13
13
  export { buildRunEventLogSources, buildAgentCliLogSources, } from "./agent-logs.js";
14
14
  export { createNodeDiagnosticsPorts } from "./node-ports.js";
15
+ export { aggregateProcessMemory, createMemoryGrowthDetector } from './memory-growth.js';
15
16
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,57 @@
1
+ /** Pure, bounded memory aggregation and sustained-growth detection; hosts own sampling and consent. */
2
+ export interface ProcessMemoryReading {
3
+ id: number;
4
+ kind: string;
5
+ rssBytes: number;
6
+ heapUsedBytes?: number;
7
+ }
8
+ export interface MemoryKindSummary {
9
+ kind: string;
10
+ count: number;
11
+ rssMb: number;
12
+ heapUsedMb?: number;
13
+ }
14
+ interface Point {
15
+ at: number;
16
+ rssMb: number;
17
+ }
18
+ export interface MemoryGrowthWarning {
19
+ kind: string;
20
+ reason: 'rss-limit' | 'sustained-growth';
21
+ series: readonly Point[];
22
+ }
23
+ interface MemoryGrowthDetector {
24
+ observe(required: {
25
+ processes: readonly ProcessMemoryReading[];
26
+ }, options?: Record<string, never>): MemoryGrowthWarning[];
27
+ reset(required?: Record<string, never>, options?: {
28
+ keepRateLimits?: boolean;
29
+ }): void;
30
+ }
31
+ /** Aggregate before rounding, deduplicating process IDs; no identity leaves the summary.
32
+ * @returns One row per process kind. @complexity O(p) time and space for p processes.
33
+ */
34
+ export declare function aggregateProcessMemory({ processes }: {
35
+ processes: readonly ProcessMemoryReading[];
36
+ }, _options?: {}): MemoryKindSummary[];
37
+ /** Small rolling windows keyed by local process identity. Gone processes are forgotten; kind
38
+ * changes and backwards clocks reset history. Rate limiting is per process, not per process kind.
39
+ * @param required Clock port, injected so tests advance time without waiting.
40
+ * @param options Thresholds and caps. Overflow drops oldest observations; it cannot grow memory.
41
+ * @returns observe and reset, with no sampler, timers, I/O or provider dependencies.
42
+ * @complexity O(p*w) per observation; O(min(p,maxProcesses)*maxSamples) retained state.
43
+ */
44
+ export declare function createMemoryGrowthDetector({ now }: {
45
+ now: () => number;
46
+ }, { windowMs, floorMs, growthMb, limitMb, rateLimitMs, maxSamples, maxProcesses, maxGapMs, }?: {
47
+ windowMs?: number;
48
+ floorMs?: number;
49
+ growthMb?: number;
50
+ limitMb?: number;
51
+ rateLimitMs?: number;
52
+ maxSamples?: number;
53
+ maxProcesses?: number;
54
+ maxGapMs?: number;
55
+ }): MemoryGrowthDetector;
56
+ export {};
57
+ //# sourceMappingURL=memory-growth.d.ts.map
@@ -0,0 +1,105 @@
1
+ const MB = 1_000_000;
2
+ /** Aggregate before rounding, deduplicating process IDs; no identity leaves the summary.
3
+ * @returns One row per process kind. @complexity O(p) time and space for p processes.
4
+ */
5
+ export function aggregateProcessMemory({ processes }, _options = {}) {
6
+ const seen = new Set();
7
+ const groups = new Map();
8
+ for (const row of processes) {
9
+ if (seen.has(row.id))
10
+ continue;
11
+ seen.add(row.id);
12
+ const group = groups.get(row.kind) ?? { count: 0, rss: 0 };
13
+ group.count++;
14
+ group.rss += row.rssBytes;
15
+ if (row.heapUsedBytes !== undefined)
16
+ group.heap = (group.heap ?? 0) + row.heapUsedBytes;
17
+ groups.set(row.kind, group);
18
+ }
19
+ return [...groups].map(([kind, group]) => ({ kind, count: group.count, rssMb: Math.round(group.rss / MB),
20
+ ...(group.heap === undefined ? {} : { heapUsedMb: Math.round(group.heap / MB) }) }));
21
+ }
22
+ /** Lowest reading in [from, to]: one GC drop lowers it, a transient spike never raises it. O(w). */
23
+ function floorMb({ series, from, to }, _options = {}) {
24
+ let floor = Infinity;
25
+ for (const point of series)
26
+ if (point.at >= from && point.at <= to)
27
+ floor = Math.min(floor, point.rssMb);
28
+ return floor;
29
+ }
30
+ /** Floors, never raw readings: RSS peaks are mostly uncollected V8 garbage (GC sawtooth), so a GC
31
+ * drop never raises an alarm and a real leak shows as a rising post-GC floor. The limit needs a
32
+ * full floor span above it; growth compares the late floor with the early floor of a full window.
33
+ * @complexity O(w) in bounded window points. No effects.
34
+ */
35
+ function growthReason({ series, at, windowMs, floorMs, growthMb, limitMb }, _options = {}) {
36
+ const first = series[0];
37
+ if (at - first.at < floorMs)
38
+ return;
39
+ const late = floorMb({ series, from: at - floorMs, to: at });
40
+ if (late > limitMb)
41
+ return 'rss-limit';
42
+ if (at - first.at < windowMs)
43
+ return;
44
+ return late - floorMb({ series, from: first.at, to: first.at + floorMs }) >= growthMb ? 'sustained-growth' : undefined;
45
+ }
46
+ /** Small rolling windows keyed by local process identity. Gone processes are forgotten; kind
47
+ * changes and backwards clocks reset history. Rate limiting is per process, not per process kind.
48
+ * @param required Clock port, injected so tests advance time without waiting.
49
+ * @param options Thresholds and caps. Overflow drops oldest observations; it cannot grow memory.
50
+ * @returns observe and reset, with no sampler, timers, I/O or provider dependencies.
51
+ * @complexity O(p*w) per observation; O(min(p,maxProcesses)*maxSamples) retained state.
52
+ */
53
+ export function createMemoryGrowthDetector({ now }, { windowMs = 60 * 60_000, floorMs = 15 * 60_000, growthMb = 300, limitMb = 2000, rateLimitMs = 24 * 60 * 60_000, maxSamples = 64, maxProcesses = 512, maxGapMs = 10 * 60_000, } = {}) {
54
+ const histories = new Map();
55
+ /** A changed kind or backwards clock cannot join two different process lifetimes. */
56
+ function historyFor({ row, at }, _options = {}) {
57
+ const previous = histories.get(row.id);
58
+ const lastAt = previous?.series.at(-1)?.at ?? at;
59
+ if (previous && previous.kind === row.kind) {
60
+ if (at < lastAt || at - lastAt > maxGapMs)
61
+ previous.series = [];
62
+ return previous;
63
+ }
64
+ const history = { kind: row.kind, series: [] };
65
+ histories.set(row.id, history);
66
+ return history;
67
+ }
68
+ /** Retain one predecessor at the window edge so ordinary timer jitter still spans sixty minutes. */
69
+ function append({ history, at, rssBytes }, _options = {}) {
70
+ history.series.push({ at, rssMb: rssBytes / MB });
71
+ while (history.series.length > 1 && history.series[1].at <= at - windowMs)
72
+ history.series.shift();
73
+ history.series = history.series.slice(-maxSamples);
74
+ }
75
+ return {
76
+ reset(_required = {}, { keepRateLimits = false } = {}) {
77
+ if (!keepRateLimits) {
78
+ histories.clear();
79
+ return;
80
+ }
81
+ for (const history of histories.values())
82
+ history.series = [];
83
+ },
84
+ observe({ processes }, _options = {}) {
85
+ const at = now();
86
+ const selected = [...new Map(processes.map(row => [row.id, row])).values()].slice(0, maxProcesses);
87
+ const live = new Set(selected.map(row => row.id));
88
+ for (const id of histories.keys())
89
+ if (!live.has(id))
90
+ histories.delete(id);
91
+ const warnings = [];
92
+ for (const row of selected) {
93
+ const history = historyFor({ row, at });
94
+ append({ history, at, rssBytes: row.rssBytes });
95
+ const reason = growthReason({ series: history.series, at, windowMs, floorMs, growthMb, limitMb });
96
+ if (!reason || at - (history.warnedAt ?? -Infinity) < rateLimitMs)
97
+ continue;
98
+ history.warnedAt = at;
99
+ warnings.push({ kind: row.kind, reason, series: history.series.map(point => ({ at: point.at, rssMb: Math.round(point.rssMb) })) });
100
+ }
101
+ return warnings;
102
+ },
103
+ };
104
+ }
105
+ //# sourceMappingURL=memory-growth.js.map
@@ -0,0 +1,44 @@
1
+ /** Sanitized adapter diagnostics. No raw errors, URLs, headers or credentials cross this boundary. */
2
+ export interface ProviderTelemetryReport {
3
+ phase: "export" | "shutdown";
4
+ outcome: "ok" | "failed";
5
+ host: string;
6
+ errorClass?: string;
7
+ statusCode?: number;
8
+ }
9
+ export interface ProviderTelemetryStatus extends ProviderTelemetryReport {
10
+ at: string;
11
+ }
12
+ export interface ProviderDeliveryStatus {
13
+ providerId: string;
14
+ lastExport: ProviderTelemetryStatus | null;
15
+ lastShutdown: ProviderTelemetryStatus | null;
16
+ }
17
+ export interface TelemetryDeliveryMonitor {
18
+ register(required: {
19
+ providerId: string;
20
+ }, optional?: Record<string, never>): void;
21
+ report(required: {
22
+ providerId: string;
23
+ report: ProviderTelemetryReport;
24
+ }, optional?: Record<string, never>): void;
25
+ read(required: Record<string, never>, optional?: Record<string, never>): ProviderDeliveryStatus[];
26
+ }
27
+ /** Reduces opaque SDK failures to fixed labels; even an Error's name can contain credentials.
28
+ * @returns Error class and optional HTTP status, never a message, stack, URL or header.
29
+ * @complexity O(1); hostile getters degrade to the fixed Error label.
30
+ */
31
+ export declare function describeTelemetryFailure({ error }: {
32
+ error: unknown;
33
+ }, _options?: {}): Pick<ProviderTelemetryReport, "errorClass" | "statusCode">;
34
+ /** Keeps delivery evidence separate from configuration and logs each distinct failure until recovery.
35
+ * @param required Host warning sink; receives sanitized adapter fields only.
36
+ * @param optional Injected wall clock for status timestamps.
37
+ * @returns Per-provider reporter and detached status reader. @complexity O(p + f) retained state.
38
+ */
39
+ export declare function createTelemetryDeliveryMonitor({ warn }: {
40
+ warn: (message: string) => void;
41
+ }, { now }?: {
42
+ now?: () => string;
43
+ }): TelemetryDeliveryMonitor;
44
+ //# sourceMappingURL=delivery.d.ts.map
@@ -0,0 +1,65 @@
1
+ const ERROR_CLASSES = new Set(["Error", "TypeError", "RangeError", "TimeoutError", "AbortError", "OTLPExporterError", "PluginProviderError"]);
2
+ /** HTTP status is numeric and bounded; transport codes and text are deliberately not exposed. */
3
+ function httpStatus(value) {
4
+ return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599 ? value : undefined;
5
+ }
6
+ /** Reduces opaque SDK failures to fixed labels; even an Error's name can contain credentials.
7
+ * @returns Error class and optional HTTP status, never a message, stack, URL or header.
8
+ * @complexity O(1); hostile getters degrade to the fixed Error label.
9
+ */
10
+ export function describeTelemetryFailure({ error }, _options = {}) {
11
+ if (typeof error !== "object" || error === null)
12
+ return { errorClass: "Error" };
13
+ try {
14
+ const value = error;
15
+ const errorClass = typeof value.name === "string" && ERROR_CLASSES.has(value.name) ? value.name : "Error";
16
+ const statusCode = httpStatus(value.statusCode ?? value.status ?? value.code);
17
+ return { errorClass, ...(statusCode === undefined ? {} : { statusCode }) };
18
+ }
19
+ catch {
20
+ return { errorClass: "Error" };
21
+ }
22
+ }
23
+ /** Keeps delivery evidence separate from configuration and logs each distinct failure until recovery.
24
+ * @param required Host warning sink; receives sanitized adapter fields only.
25
+ * @param optional Injected wall clock for status timestamps.
26
+ * @returns Per-provider reporter and detached status reader. @complexity O(p + f) retained state.
27
+ */
28
+ export function createTelemetryDeliveryMonitor({ warn }, { now = () => new Date().toISOString() } = {}) {
29
+ const statuses = new Map();
30
+ const logged = new Map();
31
+ return {
32
+ register({ providerId }, _options = {}) {
33
+ statuses.set(providerId, { lastExport: null, lastShutdown: null });
34
+ },
35
+ report({ providerId, report }, _options = {}) {
36
+ const state = statuses.get(providerId) ?? { lastExport: null, lastShutdown: null };
37
+ const status = { ...report, at: now() };
38
+ if (report.phase === "export")
39
+ state.lastExport = status;
40
+ else
41
+ state.lastShutdown = status;
42
+ statuses.set(providerId, state);
43
+ if (report.outcome !== "failed") {
44
+ logged.delete(providerId);
45
+ return;
46
+ }
47
+ const kind = JSON.stringify([report.phase, report.errorClass, report.statusCode, report.host]);
48
+ const failures = logged.get(providerId) ?? new Set();
49
+ if (failures.has(kind))
50
+ return;
51
+ failures.add(kind);
52
+ logged.set(providerId, failures);
53
+ try {
54
+ warn(`observability: ${providerId} ${report.phase} failed (${report.errorClass ?? "Error"}${report.statusCode === undefined ? "" : `, HTTP ${report.statusCode}`}, host ${report.host})`);
55
+ }
56
+ catch { /* A broken log sink must not fail an exporter callback or shutdown. */ }
57
+ },
58
+ read(_required, _options = {}) {
59
+ return [...statuses].map(([providerId, state]) => ({ providerId,
60
+ lastExport: state.lastExport ? { ...state.lastExport } : null,
61
+ lastShutdown: state.lastShutdown ? { ...state.lastShutdown } : null }));
62
+ },
63
+ };
64
+ }
65
+ //# sourceMappingURL=delivery.js.map
@@ -0,0 +1,15 @@
1
+ export interface ReportedErrorDescription {
2
+ type: string;
3
+ message: string;
4
+ stack?: string;
5
+ }
6
+ /** Vendor-neutral, redacted view of a reported error that any error-tracker adapter can send.
7
+ * Secret shapes (tokens, keys, `password=…`) are blanked; e-mails and hostnames are NOT — callers
8
+ * must not put personal data in error messages (see the plan's PII section).
9
+ * @param required The raw error as handed to `ObservabilityPort.reportError`.
10
+ * @returns Type label, redacted capped message, and redacted capped stack when there is one.
11
+ * @complexity O(n) in message + stack length. */
12
+ export declare function describeReportedError({ error }: {
13
+ error: unknown;
14
+ }, _options?: {}): ReportedErrorDescription;
15
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1,25 @@
1
+ import { redactSecretShapes } from '../core/secrets-only.js';
2
+ import { errorType } from './otel.js';
3
+ // Error trackers group by type + message and show the stack, so unlike span exports (type only) they
4
+ // need text. Both pass through the same secret-shape redaction request targets use, then are capped
5
+ // (redact first: a cut could leave a secret prefix too short to match):
6
+ // a handler error can embed a whole response body.
7
+ const MAX_MESSAGE = 1024;
8
+ const MAX_STACK_LINES = 30;
9
+ function redact(text) {
10
+ return redactSecretShapes({ text, policy: {} }).text;
11
+ }
12
+ /** Vendor-neutral, redacted view of a reported error that any error-tracker adapter can send.
13
+ * Secret shapes (tokens, keys, `password=…`) are blanked; e-mails and hostnames are NOT — callers
14
+ * must not put personal data in error messages (see the plan's PII section).
15
+ * @param required The raw error as handed to `ObservabilityPort.reportError`.
16
+ * @returns Type label, redacted capped message, and redacted capped stack when there is one.
17
+ * @complexity O(n) in message + stack length. */
18
+ export function describeReportedError({ error }, _options = {}) {
19
+ const type = errorType(error);
20
+ const raw = error instanceof Error ? error.message : typeof error === 'string' ? error : type;
21
+ const stack = error instanceof Error && typeof error.stack === 'string'
22
+ ? redact(error.stack).split('\n').slice(0, MAX_STACK_LINES).join('\n') : undefined;
23
+ return { type, message: redact(raw).slice(0, MAX_MESSAGE), ...(stack ? { stack } : {}) };
24
+ }
25
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,18 @@
1
+ import type { ObservabilityPort } from './ports.js';
2
+ /**
3
+ * Sends every signal to each enabled adapter: the "both configured" answer (say OpenTelemetry for
4
+ * traces and an error tracker for incidents), with no adapter knowing about the other. Noop ports are
5
+ * dropped; none left returns the shared noop (still zero-cost). One left is still wrapped: returning
6
+ * the raw port would let its throws (creating a tracker, ending it, reporting) reach the caller.
7
+ * @param required The candidate ports, in nesting order (outermost first).
8
+ * @returns A port; every signal reaches every adapter, and one adapter throwing (creating a tracker,
9
+ * ending it, or reporting) never skips the rest or reaches the caller.
10
+ * @param optional.onFailure Receives provider faults only, never application callback errors.
11
+ * @complexity O(n) per signal for n enabled adapters.
12
+ */
13
+ export declare function combineObservabilityPorts({ ports }: {
14
+ ports: readonly ObservabilityPort[];
15
+ }, { onFailure }?: {
16
+ onFailure?: () => void;
17
+ }): ObservabilityPort;
18
+ //# sourceMappingURL=fanout.d.ts.map
@@ -0,0 +1,165 @@
1
+ import { createNoopObservabilityPort, isNoopObservabilityPort } from './noop.js';
2
+ const NOOP = createNoopObservabilityPort({});
3
+ /** One adapter's tracker, isolated (review 2026-10-25 #3): an adapter that throws while CREATING its
4
+ * tracker gets the shared noop tracker for this signal instead of failing the caller's work, so the
5
+ * other adapters still see it. */
6
+ function isolatedStart(start, fallback, failed) {
7
+ try {
8
+ const tracker = start();
9
+ const lifecycle = tracker;
10
+ if (!lifecycle || typeof lifecycle.end !== 'function' || (lifecycle.run !== undefined && typeof lifecycle.run !== 'function'))
11
+ throw new TypeError('Invalid telemetry lifecycle');
12
+ return tracker;
13
+ }
14
+ catch {
15
+ failed();
16
+ return fallback();
17
+ }
18
+ }
19
+ const replay = (outcome) => {
20
+ if (outcome.ok)
21
+ return outcome.value;
22
+ throw outcome.error;
23
+ };
24
+ /** A value a tracker returned instead of the recorded one is dropped; if it is a promise, its
25
+ * rejection is observed here so dropping it never becomes an unhandled rejection. */
26
+ function discard(value, failed) {
27
+ if (typeof value?.then === 'function')
28
+ value.then(undefined, failed);
29
+ }
30
+ /** One adapter's scope around `inner`, contained (Codex wave-2 MED): an adapter's run() that throws
31
+ * before calling `inner` runs the work unscoped; one that throws after it keeps the work's own result
32
+ * or error; one that returns without calling it still gets the work run. `inner` runs exactly once
33
+ * (Codex fix-lane HIGH): its outcome is recorded, a second call from the tracker replays it instead of
34
+ * re-running app work, and the caller always gets that recorded outcome, so a tracker that swallows
35
+ * the work's error or substitutes a result cannot hide or change it. */
36
+ function containedScope(run, inner, failed) {
37
+ return () => {
38
+ let outcome;
39
+ const once = () => {
40
+ if (!outcome) {
41
+ try {
42
+ outcome = { ok: true, value: inner() };
43
+ }
44
+ catch (error) {
45
+ outcome = { ok: false, error };
46
+ }
47
+ }
48
+ return replay(outcome);
49
+ };
50
+ let returned;
51
+ try {
52
+ returned = run(once);
53
+ }
54
+ catch (error) {
55
+ if (outcome?.ok !== false || outcome.error !== error)
56
+ failed();
57
+ }
58
+ if (outcome?.ok !== true || returned !== outcome.value)
59
+ discard(returned, failed);
60
+ return once();
61
+ };
62
+ }
63
+ /** One tracker over several: run() nests every scope (so each adapter sees the work as its own
64
+ * child), end() settles all. The first tracker's extra fields (a request id) are kept. Each end() is
65
+ * isolated: one adapter throwing at settle time must neither skip the rest nor turn work that already
66
+ * happened (a tool call that changed state) into a failed request for the caller. */
67
+ function combine(trackers, failed) {
68
+ const run = (fn) => trackers.reduceRight((inner, t) => (t.run ? containedScope(t.run.bind(t), inner, failed) : inner), fn)();
69
+ const end = (outcome) => { for (const t of trackers) {
70
+ try {
71
+ void Promise.resolve(t.end(outcome)).catch(failed);
72
+ }
73
+ catch {
74
+ failed(); /* settle the rest */
75
+ }
76
+ } };
77
+ return { ...trackers[0], run, end };
78
+ }
79
+ /** Starts the same signal on every live adapter, each isolated, and combines the trackers. */
80
+ function fanOut(live, signal, args, failed) {
81
+ const trackers = live.map((port) => isolatedStart(() => port[signal](...args), () => NOOP[signal](...args), failed));
82
+ return combine(trackers, failed);
83
+ }
84
+ /** Preserve admission through fan-out; false/noop and rejected providers never consume an incident.
85
+ * @returns Local hand-off evidence, never an exporter delivery guarantee. @complexity O(1).
86
+ */
87
+ function handOffError({ port, report, failed }, _options = {}) {
88
+ try {
89
+ const result = port.reportError(report);
90
+ if (result instanceof Promise)
91
+ return result.then(value => value !== false, () => { failed(); return false; });
92
+ return result !== false;
93
+ }
94
+ catch {
95
+ failed();
96
+ return false;
97
+ }
98
+ }
99
+ /**
100
+ * Sends every signal to each enabled adapter: the "both configured" answer (say OpenTelemetry for
101
+ * traces and an error tracker for incidents), with no adapter knowing about the other. Noop ports are
102
+ * dropped; none left returns the shared noop (still zero-cost). One left is still wrapped: returning
103
+ * the raw port would let its throws (creating a tracker, ending it, reporting) reach the caller.
104
+ * @param required The candidate ports, in nesting order (outermost first).
105
+ * @returns A port; every signal reaches every adapter, and one adapter throwing (creating a tracker,
106
+ * ending it, or reporting) never skips the rest or reaches the caller.
107
+ * @param optional.onFailure Receives provider faults only, never application callback errors.
108
+ * @complexity O(n) per signal for n enabled adapters.
109
+ */
110
+ export function combineObservabilityPorts({ ports }, { onFailure } = {}) {
111
+ const failed = () => { try {
112
+ onFailure?.();
113
+ }
114
+ catch { /* Diagnostics never fail the caller. */ } };
115
+ const live = ports.filter((port) => !isNoopObservabilityPort(port));
116
+ if (live.length === 0)
117
+ return createNoopObservabilityPort({});
118
+ const activeTraceIds = (_required = {}, _optional = {}) => {
119
+ for (const port of live) {
120
+ try {
121
+ const ids = port.activeTraceIds?.();
122
+ if (ids)
123
+ return ids;
124
+ }
125
+ catch {
126
+ failed();
127
+ }
128
+ }
129
+ return undefined;
130
+ };
131
+ return {
132
+ activeTraceIds,
133
+ get supportsMetric() { return live.some(port => port.supportsMetric === true); },
134
+ trackRequest: (...args) => fanOut(live, 'trackRequest', args, failed),
135
+ trackDbQuery: (...args) => fanOut(live, 'trackDbQuery', args, failed),
136
+ trackOutboundCall: (...args) => fanOut(live, 'trackOutboundCall', args, failed),
137
+ trackAgentRun: (...args) => fanOut(live, 'trackAgentRun', args, failed),
138
+ trackOperation: (...args) => fanOut(live, 'trackOperation', args, failed),
139
+ metric: (input, options = {}) => {
140
+ for (const port of live) {
141
+ try {
142
+ void Promise.resolve(port.metric(input, options)).catch(failed);
143
+ }
144
+ catch {
145
+ failed(); /* keep reaching the rest */
146
+ }
147
+ }
148
+ },
149
+ reportError: (report) => {
150
+ // Providers own independent traces. Carry the selected structural trace explicitly so error
151
+ // destinations can correlate with local logs without pretending their own trace IDs match.
152
+ const trace = report.context.trace ?? activeTraceIds();
153
+ const correlated = trace ? { ...report, context: { ...report.context, trace } } : report;
154
+ // reportError never throws; keep reaching the rest even when one provider refuses admission.
155
+ const results = live.map(port => handOffError({ port, report: correlated, failed }));
156
+ if (results.includes(true))
157
+ return true;
158
+ // One fulfilled admission is enough; a stalled destination must not delay another's receipt.
159
+ const admissions = results.map(async (result) => { if (!await result)
160
+ throw new Error('Report refused'); return true; });
161
+ return Promise.any(admissions).catch(() => false);
162
+ },
163
+ };
164
+ }
165
+ //# sourceMappingURL=fanout.js.map
@@ -8,8 +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; DB, outbound and
12
- * agent-run signals go straight to the tracing adapter (the no-op without one).
11
+ * @returns Request tracking with exactly one completion event per request; DB, outbound,
12
+ * agent-run and operation signals, numeric metrics and error reports go straight to the tracing adapter (the no-op without one).
13
13
  * @throws Hook errors propagate to the caller; adapters choose their own error policy.
14
14
  */
15
15
  export declare function createHookObservabilityPort({ clock, requestIdGenerator }: {
@@ -2,13 +2,15 @@ import { createNoopObservabilityPort } from './noop.js';
2
2
  /** Adds request correlation and completed-request hooks using explicit ID and clock ports.
3
3
  * @param required Clock and request ID generator, scoped by the host.
4
4
  * @param options Optional logging, metrics and tracing adapters.
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
+ * @returns Request tracking with exactly one completion event per request; DB, outbound,
6
+ * agent-run and operation signals, numeric metrics and error reports go straight to the tracing adapter (the no-op without one).
7
7
  * @throws Hook errors propagate to the caller; adapters choose their own error policy.
8
8
  */
9
9
  export function createHookObservabilityPort({ clock, requestIdGenerator }, { logger, metrics, tracing } = {}) {
10
10
  const signals = tracing ?? createNoopObservabilityPort({});
11
11
  return {
12
+ get supportsMetric() { return signals.supportsMetric === true; },
13
+ activeTraceIds: (_required = {}, _optional = {}) => signals.activeTraceIds?.(),
12
14
  trackRequest(input, options = {}) {
13
15
  const requestId = options.requestId ?? requestIdGenerator.generate({});
14
16
  const startedAt = clock.nowMs();
@@ -27,6 +29,9 @@ export function createHookObservabilityPort({ clock, requestIdGenerator }, { log
27
29
  trackDbQuery: (input) => signals.trackDbQuery(input),
28
30
  trackOutboundCall: (input) => signals.trackOutboundCall(input),
29
31
  trackAgentRun: (input, options) => signals.trackAgentRun(input, options),
32
+ trackOperation: (input) => signals.trackOperation(input),
33
+ metric: (input, options = {}) => signals.metric(input, options),
34
+ reportError: (report) => signals.reportError(report),
30
35
  };
31
36
  }
32
37
  //# sourceMappingURL=hooks.js.map
@@ -5,8 +5,12 @@ export * from './config.js';
5
5
  export * from './ports.js';
6
6
  export * from './noop.js';
7
7
  export * from './otel.js';
8
+ export * from './errors.js';
9
+ export * from './fanout.js';
8
10
  export * from './hooks.js';
9
11
  export * from './instrumentation.js';
12
+ export * from './delivery.js';
13
+ export type { TelemetryTestResult, TelemetryTestSignal } from './telemetry-test.js';
10
14
  /** Selects an adapter from explicit config; disabled telemetry never invokes either factory.
11
15
  * @param options Adapter options (host span scope); ignored when telemetry is disabled. */
12
16
  export declare function createObservabilityPort({ config, exporterFactory, tracerProviderFactory }: {
@@ -14,4 +18,6 @@ export declare function createObservabilityPort({ config, exporterFactory, trace
14
18
  exporterFactory: ExporterFactory;
15
19
  tracerProviderFactory: TracerProviderFactory;
16
20
  }, options?: OtelAdapterOptions): ObservabilityPort;
21
+ export type * from "./tracker-types.js";
22
+ export { createNoopTracker } from "./tracker-noop.js";
17
23
  //# sourceMappingURL=index.d.ts.map
@@ -4,8 +4,11 @@ export * from './config.js';
4
4
  export * from './ports.js';
5
5
  export * from './noop.js';
6
6
  export * from './otel.js';
7
+ export * from './errors.js';
8
+ export * from './fanout.js';
7
9
  export * from './hooks.js';
8
10
  export * from './instrumentation.js';
11
+ export * from './delivery.js';
9
12
  /** Selects an adapter from explicit config; disabled telemetry never invokes either factory.
10
13
  * @param options Adapter options (host span scope); ignored when telemetry is disabled. */
11
14
  export function createObservabilityPort({ config, exporterFactory, tracerProviderFactory }, options = {}) {
@@ -13,4 +16,5 @@ export function createObservabilityPort({ config, exporterFactory, tracerProvide
13
16
  return createNoopObservabilityPort({});
14
17
  return createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory }, options);
15
18
  }
19
+ export { createNoopTracker } from "./tracker-noop.js";
16
20
  //# sourceMappingURL=index.js.map