agentrail-node 0.0.0-stage → 0.2.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.
@@ -0,0 +1,64 @@
1
+ import { isCaptureSuppressed } from './suppression.js';
2
+ import { context } from '@opentelemetry/api';
3
+ import { SamplingDecision } from '@opentelemetry/sdk-trace';
4
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
5
+ import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto';
6
+ import { ExportQueue } from './queue.js';
7
+ import { copyLog, copySpan } from './privacy.js';
8
+ export function processors(runtime) {
9
+ const options = runtime.options;
10
+ const config = {
11
+ headers: { Authorization: `Bearer ${options.input.collector.secret}` },
12
+ timeoutMillis: options.queue.exportTimeoutMs,
13
+ };
14
+ const spans = new ExportQueue('traces', new OTLPTraceExporter({ ...config, url: `${options.endpoint}/v1/traces` }), options);
15
+ const logs = new ExportQueue('logs', new OTLPLogExporter({ ...config, url: `${options.endpoint}/v1/logs` }), options);
16
+ const spanProcessor = {
17
+ onStart(span, parent) {
18
+ if (isCaptureSuppressed(parent))
19
+ return;
20
+ const state = runtime.state(parent);
21
+ if (state === undefined)
22
+ return;
23
+ const mark = runtime.mark(parent);
24
+ runtime.spans.set(span, {
25
+ state,
26
+ ...(mark === undefined ? {} : { mark }),
27
+ });
28
+ state.entry.span ??= span;
29
+ },
30
+ onEnd(span) {
31
+ const copy = copySpan(span, runtime);
32
+ if (copy !== undefined)
33
+ spans.add(copy);
34
+ },
35
+ forceFlush: () => spans.flush(),
36
+ shutdown: () => spans.shutdown(),
37
+ };
38
+ const logProcessor = {
39
+ onEmit(record, ctx = context.active()) {
40
+ if (isCaptureSuppressed(ctx))
41
+ return;
42
+ // An unrelated request's log must never inherit a managed request's context.
43
+ if (runtime.state(ctx) === undefined &&
44
+ options.input.logs?.uncorrelated === false)
45
+ return;
46
+ const copy = copyLog(record, runtime);
47
+ if (copy !== undefined)
48
+ logs.add(copy);
49
+ },
50
+ forceFlush: () => logs.flush(),
51
+ shutdown: () => logs.shutdown(),
52
+ };
53
+ const sampler = (base) => ({
54
+ shouldSample(ctx, traceId, name, kind, attributes, links) {
55
+ const result = base.shouldSample(ctx, traceId, name, kind, attributes, links);
56
+ return result.decision === SamplingDecision.NOT_RECORD &&
57
+ runtime.state(ctx) !== undefined
58
+ ? { ...result, decision: SamplingDecision.RECORD }
59
+ : result;
60
+ },
61
+ toString: () => `Agentrail(${base.toString()})`,
62
+ });
63
+ return { spanProcessor, logProcessor, sampler, spans, logs };
64
+ }
@@ -0,0 +1,36 @@
1
+ import type { ExportResult } from '@opentelemetry/core';
2
+ import { type ResolvedOptions } from './options.js';
3
+ interface Exporter<T> {
4
+ export(records: T[], callback: (result: ExportResult) => void): void;
5
+ shutdown(): Promise<void>;
6
+ }
7
+ export interface QueueStats {
8
+ accepted: number;
9
+ exported: number;
10
+ dropped: number;
11
+ pending: number;
12
+ }
13
+ /** One in-flight batch; its records still consume capacity. The vendor transport owns OTLP retry policy. */
14
+ export declare class ExportQueue<T> {
15
+ private readonly signal;
16
+ private readonly exporter;
17
+ private readonly options;
18
+ private records;
19
+ private active;
20
+ private inFlight;
21
+ private cancelActive;
22
+ private timer;
23
+ private closed;
24
+ private stop;
25
+ private readonly stats;
26
+ constructor(signal: 'traces' | 'logs', exporter: Exporter<T>, options: ResolvedOptions);
27
+ diagnostics(): QueueStats;
28
+ add(record: T): void;
29
+ private drop;
30
+ private exportBatch;
31
+ private drain;
32
+ private bounded;
33
+ flush(): Promise<void>;
34
+ shutdown(): Promise<void>;
35
+ }
36
+ export {};
package/dist/queue.js ADDED
@@ -0,0 +1,132 @@
1
+ import { ExportResultCode, suppressTracing } from '@opentelemetry/core';
2
+ import { context } from '@opentelemetry/api';
3
+ import { CaptureError } from './options.js';
4
+ /** One in-flight batch; its records still consume capacity. The vendor transport owns OTLP retry policy. */
5
+ export class ExportQueue {
6
+ signal;
7
+ exporter;
8
+ options;
9
+ records = [];
10
+ active;
11
+ inFlight = 0;
12
+ cancelActive;
13
+ timer;
14
+ closed = false;
15
+ stop;
16
+ stats = { accepted: 0, exported: 0, dropped: 0 };
17
+ constructor(signal, exporter, options) {
18
+ this.signal = signal;
19
+ this.exporter = exporter;
20
+ this.options = options;
21
+ }
22
+ diagnostics() {
23
+ return { ...this.stats, pending: this.records.length + this.inFlight };
24
+ }
25
+ add(record) {
26
+ if (this.closed ||
27
+ this.records.length + this.inFlight >= this.options.queue.maxRecords) {
28
+ this.drop(this.closed ? 'closed' : 'queue_full', 1);
29
+ return;
30
+ }
31
+ this.records.push(record);
32
+ this.stats.accepted++;
33
+ if (this.records.length >= this.options.queue.batchSize)
34
+ void this.drain();
35
+ else if (this.timer === undefined) {
36
+ this.timer = setTimeout(() => {
37
+ this.timer = undefined;
38
+ void this.drain();
39
+ }, this.options.queue.scheduledDelayMs);
40
+ this.timer.unref();
41
+ }
42
+ }
43
+ drop(code, count, cause) {
44
+ this.stats.dropped += count;
45
+ this.options.report(new CaptureError(code, this.signal, count, cause));
46
+ }
47
+ exportBatch(batch) {
48
+ return new Promise((resolve) => {
49
+ let finished = false;
50
+ const done = (result) => {
51
+ if (finished)
52
+ return;
53
+ finished = true;
54
+ clearTimeout(timer);
55
+ this.cancelActive = undefined;
56
+ try {
57
+ if (result.code === ExportResultCode.SUCCESS)
58
+ this.stats.exported += batch.length;
59
+ else
60
+ this.drop('export_failed', batch.length, result.error);
61
+ }
62
+ finally {
63
+ resolve();
64
+ }
65
+ };
66
+ const timer = setTimeout(() => {
67
+ done({
68
+ code: ExportResultCode.FAILED,
69
+ error: new Error('OTLP export deadline exceeded.'),
70
+ });
71
+ }, this.options.queue.exportTimeoutMs);
72
+ this.cancelActive = () => {
73
+ done({
74
+ code: ExportResultCode.FAILED,
75
+ error: new Error('OTLP flush or shutdown deadline exceeded.'),
76
+ });
77
+ };
78
+ context.with(suppressTracing(context.active()), () => {
79
+ this.exporter.export(batch, done);
80
+ });
81
+ });
82
+ }
83
+ drain() {
84
+ if (this.active !== undefined)
85
+ return this.active;
86
+ clearTimeout(this.timer);
87
+ this.timer = undefined;
88
+ this.active = (async () => {
89
+ while (this.records.length > 0) {
90
+ const batch = this.records.splice(0, this.options.queue.batchSize);
91
+ this.inFlight = batch.length;
92
+ await this.exportBatch(batch);
93
+ this.inFlight = 0;
94
+ }
95
+ })().finally(() => {
96
+ this.active = undefined;
97
+ // A record can arrive after the loop ended but before this microtask.
98
+ // Chain its drain so flush/shutdown also wait for that delivery.
99
+ if (this.records.length > 0)
100
+ return this.drain();
101
+ });
102
+ return this.active;
103
+ }
104
+ async bounded(work, timeout) {
105
+ let timer;
106
+ await Promise.race([
107
+ work,
108
+ new Promise((resolve) => {
109
+ timer = setTimeout(() => {
110
+ const count = this.records.length;
111
+ this.records = [];
112
+ if (count > 0)
113
+ this.drop('deadline', count);
114
+ this.cancelActive?.();
115
+ resolve();
116
+ }, timeout);
117
+ }),
118
+ ]);
119
+ clearTimeout(timer);
120
+ }
121
+ async flush() {
122
+ await this.bounded(this.drain(), this.options.queue.flushTimeoutMs);
123
+ }
124
+ shutdown() {
125
+ this.stop ??= (async () => {
126
+ this.closed = true;
127
+ clearTimeout(this.timer);
128
+ await this.bounded(this.drain().then(() => this.exporter.shutdown()), this.options.queue.shutdownTimeoutMs);
129
+ })();
130
+ return this.stop;
131
+ }
132
+ }
@@ -0,0 +1,30 @@
1
+ import type { Attributes, Context, Span } from '@opentelemetry/api';
2
+ import type { MilestoneContext, ResolvedOptions, VerifiedIdentity } from './options.js';
3
+ export interface State {
4
+ identity?: Attributes;
5
+ readonly verifiedIngress: boolean;
6
+ readonly links: import('@opentelemetry/api').Link[];
7
+ readonly entry: {
8
+ span?: Span;
9
+ };
10
+ }
11
+ export interface Mark extends MilestoneContext {
12
+ readonly name: string;
13
+ readonly identity?: Attributes;
14
+ }
15
+ export declare class Runtime {
16
+ readonly options: ResolvedOptions;
17
+ readonly stateKey: symbol;
18
+ readonly markKey: symbol;
19
+ readonly spans: WeakMap<object, {
20
+ state: State;
21
+ mark?: Mark;
22
+ }>;
23
+ readonly keyId: string;
24
+ readonly resource: import("@opentelemetry/resources").Resource;
25
+ constructor(options: ResolvedOptions);
26
+ state(ctx: Context): State | undefined;
27
+ mark(ctx: Context): Mark | undefined;
28
+ newState(verifiedIngress?: boolean, links?: State['links']): State;
29
+ identity(identity: VerifiedIdentity): Attributes;
30
+ }
@@ -0,0 +1,52 @@
1
+ import { createHash, createHmac, randomUUID } from 'node:crypto';
2
+ import { createContextKey } from '@opentelemetry/api';
3
+ import { resourceFromAttributes } from '@opentelemetry/resources';
4
+ import { VERSION } from 'agentrail-core';
5
+ export class Runtime {
6
+ options;
7
+ stateKey = createContextKey(`agentrail.state.${randomUUID()}`);
8
+ markKey = createContextKey(`agentrail.milestone.${randomUUID()}`);
9
+ spans = new WeakMap();
10
+ keyId;
11
+ resource;
12
+ constructor(options) {
13
+ this.options = options;
14
+ this.keyId = createHash('sha256')
15
+ .update(options.input.hashKey)
16
+ .digest('hex')
17
+ .slice(0, 16);
18
+ this.resource = resourceFromAttributes({
19
+ 'service.name': options.input.serviceName,
20
+ 'service.instance.id': options.instance,
21
+ 'agentrail.component.name': 'agentrail-node',
22
+ 'agentrail.component.version': VERSION,
23
+ 'agentrail.hash_key_id': this.keyId,
24
+ 'agentrail.capture.surfaces': 'http,mcp,auth,custom',
25
+ });
26
+ }
27
+ state(ctx) {
28
+ return ctx.getValue(this.stateKey);
29
+ }
30
+ mark(ctx) {
31
+ return ctx.getValue(this.markKey);
32
+ }
33
+ newState(verifiedIngress = false, links = []) {
34
+ return { verifiedIngress, links, entry: {} };
35
+ }
36
+ identity(identity) {
37
+ const hash = (id) => createHmac('sha256', this.options.input.hashKey)
38
+ .update(id)
39
+ .digest('hex')
40
+ .slice(0, 32);
41
+ return {
42
+ 'agentrail.identity.verified': true,
43
+ 'agentrail.principal.kind': identity.kind,
44
+ 'agentrail.principal.id_hash': hash(identity.id),
45
+ ...(identity.actingUserId === undefined
46
+ ? {}
47
+ : {
48
+ 'agentrail.principal.acting_user_hash': hash(identity.actingUserId),
49
+ }),
50
+ };
51
+ }
52
+ }
@@ -0,0 +1,3 @@
1
+ import type { Context } from '@opentelemetry/api';
2
+ export declare function isCaptureSuppressed(ctx: Context): boolean;
3
+ export declare function reportWithoutCapture(run: () => void): void;
@@ -0,0 +1,14 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { context, createContextKey } from '@opentelemetry/api';
3
+ import { suppressTracing } from '@opentelemetry/core';
4
+ // Shared by installations in this process; never derived from a request or baggage.
5
+ const diagnostic = createContextKey('agentrail.capture.suppressed');
6
+ const reporting = new AsyncLocalStorage();
7
+ export function isCaptureSuppressed(ctx) {
8
+ return reporting.getStore() === true || ctx.getValue(diagnostic) === true;
9
+ }
10
+ export function reportWithoutCapture(run) {
11
+ reporting.run(true, () => {
12
+ context.with(suppressTracing(context.active()).setValue(diagnostic, true), run);
13
+ });
14
+ }
package/package.json CHANGED
@@ -1,6 +1,77 @@
1
1
  {
2
2
  "name": "agentrail-node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Backend HTTP traces, structured logs and MCP journey context for Agentrail.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/agentrail-co/agentrail-js.git",
9
+ "directory": "packages/node"
10
+ },
11
+ "homepage": "https://github.com/agentrail-co/agentrail-js/tree/main/packages/node#readme",
12
+ "type": "module",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ },
18
+ "./pino": {
19
+ "types": "./dist/pino.d.ts",
20
+ "import": "./dist/pino.js"
21
+ },
22
+ "./mcp": {
23
+ "types": "./dist/mcp.d.ts",
24
+ "import": "./dist/mcp.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "engines": {
33
+ "node": ">=22"
34
+ },
35
+ "dependencies": {
36
+ "@opentelemetry/api": "1.9.1",
37
+ "@opentelemetry/core": "2.10.0",
38
+ "@opentelemetry/context-async-hooks": "2.10.0",
39
+ "@opentelemetry/resources": "2.10.0",
40
+ "@opentelemetry/sdk-trace": "2.10.0",
41
+ "@opentelemetry/api-logs": "0.221.0",
42
+ "@opentelemetry/sdk-logs": "0.221.0",
43
+ "@opentelemetry/exporter-trace-otlp-proto": "0.221.0",
44
+ "@opentelemetry/exporter-logs-otlp-proto": "0.221.0",
45
+ "@opentelemetry/instrumentation": "0.221.0",
46
+ "@opentelemetry/instrumentation-http": "0.221.0",
47
+ "@opentelemetry/instrumentation-undici": "0.31.0",
48
+ "agentrail-core": "0.2.0"
49
+ },
50
+ "peerDependencies": {
51
+ "pino": ">=9 <11",
52
+ "@modelcontextprotocol/server": ">=2.3.1 <3"
53
+ },
54
+ "peerDependenciesMeta": {
55
+ "pino": {
56
+ "optional": true
57
+ },
58
+ "@modelcontextprotocol/server": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "devDependencies": {
63
+ "pino": "10.3.1",
64
+ "protobufjs": "7.6.5",
65
+ "@modelcontextprotocol/server": "2.3.1",
66
+ "@modelcontextprotocol/client": "2.3.1",
67
+ "zod": "4.4.3",
68
+ "@sentry/node": "10.76.2",
69
+ "@sentry/opentelemetry": "10.76.2",
70
+ "agentrail-contract": "0.0.0"
71
+ },
72
+ "scripts": {
73
+ "build": "tsc -p tsconfig.build.json",
74
+ "typecheck": "tsc --noEmit",
75
+ "test": "vitest run"
76
+ }
6
77
  }