agentrail-node 0.0.0 → 0.3.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/LICENSE +201 -0
- package/README.md +179 -0
- package/dist/client.d.ts +17 -0
- package/dist/client.js +116 -0
- package/dist/http.d.ts +10 -0
- package/dist/http.js +197 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +27 -0
- package/dist/init.d.ts +4 -0
- package/dist/init.js +80 -0
- package/dist/limits.d.ts +18 -0
- package/dist/limits.js +18 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +712 -0
- package/dist/options.d.ts +101 -0
- package/dist/options.js +79 -0
- package/dist/performance.d.ts +4 -0
- package/dist/performance.js +37 -0
- package/dist/pino.d.ts +6 -0
- package/dist/pino.js +35 -0
- package/dist/privacy.d.ts +28 -0
- package/dist/privacy.js +338 -0
- package/dist/processors.d.ts +11 -0
- package/dist/processors.js +64 -0
- package/dist/queue.d.ts +54 -0
- package/dist/queue.js +179 -0
- package/dist/runtime.d.ts +88 -0
- package/dist/runtime.js +67 -0
- package/dist/suppression.d.ts +3 -0
- package/dist/suppression.js +14 -0
- package/package.json +70 -3
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { PrincipalKind, Surface, IpLocation } from 'agentrail-core';
|
|
2
|
+
export interface VerifiedIdentity {
|
|
3
|
+
readonly kind: PrincipalKind;
|
|
4
|
+
/** An ID the application has already authenticated. Never supplied from a request claim alone. */
|
|
5
|
+
readonly id: string;
|
|
6
|
+
readonly actingUserId?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface AuthorizedOperation {
|
|
9
|
+
readonly namespaceId: string;
|
|
10
|
+
/** A business attempt ID the application has already authorized. Hashed locally; never exported. */
|
|
11
|
+
readonly instanceRef: string;
|
|
12
|
+
readonly role: 'start' | 'progress' | 'terminal';
|
|
13
|
+
}
|
|
14
|
+
export interface PluginInvocation {
|
|
15
|
+
readonly bindingId: string;
|
|
16
|
+
/** An opaque invocation ID, never tool arguments or a user identifier. */
|
|
17
|
+
readonly invocationId: string;
|
|
18
|
+
}
|
|
19
|
+
export type PerformanceContext = {
|
|
20
|
+
readonly environment: 'production' | 'test';
|
|
21
|
+
} & ({
|
|
22
|
+
readonly operation: AuthorizedOperation;
|
|
23
|
+
readonly eventName: string;
|
|
24
|
+
readonly plugin?: PluginInvocation;
|
|
25
|
+
} | {
|
|
26
|
+
readonly operation: AuthorizedOperation;
|
|
27
|
+
readonly eventName?: string;
|
|
28
|
+
readonly plugin: PluginInvocation;
|
|
29
|
+
} | {
|
|
30
|
+
readonly operation?: never;
|
|
31
|
+
readonly eventName?: never;
|
|
32
|
+
readonly plugin: PluginInvocation;
|
|
33
|
+
});
|
|
34
|
+
export interface MilestoneContext {
|
|
35
|
+
/** Explicit evidence supplied after application authorization; never inferred from tool inputs or results. */
|
|
36
|
+
readonly performance?: PerformanceContext;
|
|
37
|
+
readonly surface: Surface;
|
|
38
|
+
readonly kind: string;
|
|
39
|
+
readonly mcp?: {
|
|
40
|
+
readonly method: string;
|
|
41
|
+
/** The tool, resource or prompt's registered name, never a value from its arguments. */
|
|
42
|
+
readonly name?: string;
|
|
43
|
+
readonly client?: string;
|
|
44
|
+
readonly clientVersion?: string;
|
|
45
|
+
readonly protocol?: string;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export interface QueueOptions {
|
|
49
|
+
readonly maxRecords: number;
|
|
50
|
+
readonly batchSize: number;
|
|
51
|
+
readonly scheduledDelayMs: number;
|
|
52
|
+
readonly exportTimeoutMs: number;
|
|
53
|
+
readonly flushTimeoutMs: number;
|
|
54
|
+
readonly shutdownTimeoutMs: number;
|
|
55
|
+
}
|
|
56
|
+
export interface NodeOptions {
|
|
57
|
+
/** Retain customer propagation for unmanaged work; register the returned SDK propagator once. */
|
|
58
|
+
readonly propagator?: import('@opentelemetry/api').TextMapPropagator;
|
|
59
|
+
readonly collector: {
|
|
60
|
+
readonly endpoint: string;
|
|
61
|
+
readonly secret: string;
|
|
62
|
+
};
|
|
63
|
+
readonly hashKey: string;
|
|
64
|
+
readonly serviceName: string;
|
|
65
|
+
readonly serviceInstanceId?: string;
|
|
66
|
+
/** Exact http(s) origins permitted to receive signed trace context. Defaults to none. */
|
|
67
|
+
readonly outboundOrigins?: readonly string[];
|
|
68
|
+
readonly ignoreIncomingRequest?: (request: import('node:http').IncomingMessage) => boolean;
|
|
69
|
+
/** Use trusted platform metadata or a preloaded local database; never the exporter connection's IP. */
|
|
70
|
+
readonly incomingLocation?: (request: import('node:http').IncomingMessage) => Omit<IpLocation, 'observedAt'> | null;
|
|
71
|
+
readonly logs?: {
|
|
72
|
+
readonly includeFields?: readonly string[];
|
|
73
|
+
readonly uncorrelated?: boolean;
|
|
74
|
+
};
|
|
75
|
+
readonly queue?: Partial<QueueOptions>;
|
|
76
|
+
readonly onError?: (error: CaptureError) => void;
|
|
77
|
+
}
|
|
78
|
+
export type CaptureCode = 'queue_full' | 'export_failed' | 'deadline' | 'closed' | 'handoff_refused' | 'entry_not_recording' | 'location_failed' | 'identity_outside_request' | 'invalid_performance'
|
|
79
|
+
/** MCP payloads past the queue's payload memory budget: the span went without them. */
|
|
80
|
+
| 'payload_budget'
|
|
81
|
+
/** The application's MCP payload redact hook threw: the span went without payloads. */
|
|
82
|
+
| 'payload_redact_failed';
|
|
83
|
+
export declare class CaptureError extends Error {
|
|
84
|
+
readonly code: CaptureCode;
|
|
85
|
+
readonly signal: 'traces' | 'logs' | 'context';
|
|
86
|
+
readonly count: number;
|
|
87
|
+
readonly name = "AgentrailCaptureError";
|
|
88
|
+
constructor(code: CaptureCode, signal: 'traces' | 'logs' | 'context', count: number, cause?: Error);
|
|
89
|
+
}
|
|
90
|
+
export declare class ConfigurationError extends Error {
|
|
91
|
+
readonly name = "AgentrailConfigurationError";
|
|
92
|
+
}
|
|
93
|
+
export interface ResolvedOptions {
|
|
94
|
+
readonly input: NodeOptions;
|
|
95
|
+
readonly endpoint: string;
|
|
96
|
+
readonly instance: string;
|
|
97
|
+
readonly origins: ReadonlySet<string>;
|
|
98
|
+
readonly queue: QueueOptions;
|
|
99
|
+
readonly report: (error: CaptureError) => void;
|
|
100
|
+
}
|
|
101
|
+
export declare function resolveOptions(input: NodeOptions): ResolvedOptions;
|
package/dist/options.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { reportWithoutCapture } from './suppression.js';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
export class CaptureError extends Error {
|
|
4
|
+
code;
|
|
5
|
+
signal;
|
|
6
|
+
count;
|
|
7
|
+
name = 'AgentrailCaptureError';
|
|
8
|
+
constructor(code, signal, count, cause) {
|
|
9
|
+
super(`Agentrail ${signal} capture: ${code} (${count} records).`, cause === undefined ? undefined : { cause });
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.signal = signal;
|
|
12
|
+
this.count = count;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export class ConfigurationError extends Error {
|
|
16
|
+
name = 'AgentrailConfigurationError';
|
|
17
|
+
}
|
|
18
|
+
const defaults = {
|
|
19
|
+
maxRecords: 2048,
|
|
20
|
+
batchSize: 128,
|
|
21
|
+
scheduledDelayMs: 1000,
|
|
22
|
+
exportTimeoutMs: 5000,
|
|
23
|
+
flushTimeoutMs: 10000,
|
|
24
|
+
shutdownTimeoutMs: 10000,
|
|
25
|
+
};
|
|
26
|
+
export function resolveOptions(input) {
|
|
27
|
+
const endpoint = new URL(input.collector.endpoint);
|
|
28
|
+
if (!['http:', 'https:'].includes(endpoint.protocol) ||
|
|
29
|
+
endpoint.username ||
|
|
30
|
+
endpoint.password ||
|
|
31
|
+
endpoint.search ||
|
|
32
|
+
endpoint.hash)
|
|
33
|
+
throw new ConfigurationError('Use an http(s) OTLP base URL without credentials, query or fragment.');
|
|
34
|
+
if (![
|
|
35
|
+
input.collector.secret,
|
|
36
|
+
input.hashKey,
|
|
37
|
+
input.serviceName,
|
|
38
|
+
input.serviceInstanceId ?? 'present',
|
|
39
|
+
].every((value) => value.length > 0))
|
|
40
|
+
throw new ConfigurationError('Configure a source secret, workspace hash key and service identity.');
|
|
41
|
+
if ([input.serviceName, input.serviceInstanceId].some((value) => value !== undefined &&
|
|
42
|
+
(value.length > 4096 ||
|
|
43
|
+
value.includes('\u0000') ||
|
|
44
|
+
!value.isWellFormed())))
|
|
45
|
+
throw new ConfigurationError('Service names and instance IDs must be well-formed text of at most 4096 characters without NUL.');
|
|
46
|
+
const queue = { ...defaults, ...input.queue };
|
|
47
|
+
if (!Object.values(queue).every((value) => Number.isSafeInteger(value) && value > 0) ||
|
|
48
|
+
queue.batchSize > queue.maxRecords ||
|
|
49
|
+
queue.exportTimeoutMs >
|
|
50
|
+
Math.min(queue.flushTimeoutMs, queue.shutdownTimeoutMs))
|
|
51
|
+
throw new ConfigurationError('Use positive queue limits, batchSize <= maxRecords and deadlines >= exportTimeoutMs.');
|
|
52
|
+
const origins = new Set((input.outboundOrigins ?? []).map((origin) => {
|
|
53
|
+
const url = new URL(origin);
|
|
54
|
+
if (url.origin !== origin || !['http:', 'https:'].includes(url.protocol))
|
|
55
|
+
throw new ConfigurationError('outboundOrigins must contain exact http(s) origins.');
|
|
56
|
+
return origin;
|
|
57
|
+
}));
|
|
58
|
+
return {
|
|
59
|
+
input,
|
|
60
|
+
endpoint: endpoint.href.replace(/\/$/u, ''),
|
|
61
|
+
instance: input.serviceInstanceId ?? randomUUID(),
|
|
62
|
+
origins,
|
|
63
|
+
queue,
|
|
64
|
+
report: (error) => {
|
|
65
|
+
reportWithoutCapture(() => {
|
|
66
|
+
if (input.onError === undefined) {
|
|
67
|
+
console.error(error);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
input.onError(error);
|
|
72
|
+
}
|
|
73
|
+
catch (callbackError) {
|
|
74
|
+
console.error('Agentrail onError callback failed.', callbackError, error);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Attributes } from '@opentelemetry/api';
|
|
2
|
+
import { type PerformanceContext } from './options.js';
|
|
3
|
+
/** Only normalized, allowlisted evidence enters the span context. */
|
|
4
|
+
export declare function performanceAttributes(input: PerformanceContext, hashKey: string): Attributes;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { createHmac } from 'node:crypto';
|
|
2
|
+
import { ConfigurationError } from './options.js';
|
|
3
|
+
// Matches the collector's UUID contract, including version and variant.
|
|
4
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
5
|
+
/** Only normalized, allowlisted evidence enters the span context. */
|
|
6
|
+
export function performanceAttributes(input, hashKey) {
|
|
7
|
+
const attributes = { 'agentrail.environment': input.environment };
|
|
8
|
+
if (input.plugin !== undefined) {
|
|
9
|
+
if (!uuid.test(input.plugin.bindingId) ||
|
|
10
|
+
input.plugin.invocationId.length === 0 ||
|
|
11
|
+
input.plugin.invocationId.length > 256 ||
|
|
12
|
+
!input.plugin.invocationId.isWellFormed() ||
|
|
13
|
+
input.plugin.invocationId.includes('\u0000'))
|
|
14
|
+
throw new ConfigurationError('Use a canonical binding ID and an opaque invocation ID of 1–256 characters.');
|
|
15
|
+
attributes['agentrail.plugin.binding_id'] = input.plugin.bindingId;
|
|
16
|
+
attributes['agentrail.plugin.invocation_id'] = input.plugin.invocationId;
|
|
17
|
+
}
|
|
18
|
+
if (input.operation !== undefined) {
|
|
19
|
+
const { namespaceId, instanceRef, role } = input.operation;
|
|
20
|
+
if (!uuid.test(namespaceId) ||
|
|
21
|
+
instanceRef.length === 0 ||
|
|
22
|
+
!instanceRef.isWellFormed())
|
|
23
|
+
throw new ConfigurationError('Use a canonical namespace ID and a nonempty, well-formed authorized operation reference.');
|
|
24
|
+
attributes['agentrail.operation.namespace_id'] = namespaceId;
|
|
25
|
+
attributes['agentrail.operation.hash'] = createHmac('sha256', hashKey)
|
|
26
|
+
.update(JSON.stringify(['agentrail.operation', namespaceId, instanceRef]))
|
|
27
|
+
.digest('hex');
|
|
28
|
+
attributes['agentrail.workflow.role'] = role;
|
|
29
|
+
if (input.eventName !== undefined) {
|
|
30
|
+
if (input.eventName.length > 120 ||
|
|
31
|
+
!/^[a-zA-Z][a-zA-Z0-9_.:-]*$/u.test(input.eventName))
|
|
32
|
+
throw new ConfigurationError('Use a business event name of 1–120 letters, digits, dots, underscores, colons or hyphens, starting with a letter.');
|
|
33
|
+
attributes['agentrail.workflow.event_name'] = input.eventName;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return attributes;
|
|
37
|
+
}
|
package/dist/pino.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { LoggerOptions } from 'pino';
|
|
2
|
+
import type { AgentrailNode } from './client.js';
|
|
3
|
+
type Hooks = NonNullable<LoggerOptions['hooks']>;
|
|
4
|
+
/** Compose into pino({ hooks: pino(client, existingHooks) }). Captures synchronously in the caller's context. */
|
|
5
|
+
export declare function pino(client: AgentrailNode, existing?: Hooks): Hooks;
|
|
6
|
+
export {};
|
package/dist/pino.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Compose into pino({ hooks: pino(client, existingHooks) }). Captures synchronously in the caller's context. */
|
|
2
|
+
export function pino(client, existing = {}) {
|
|
3
|
+
return {
|
|
4
|
+
...existing,
|
|
5
|
+
logMethod(args, method, level) {
|
|
6
|
+
if (existing.logMethod === undefined)
|
|
7
|
+
method.apply(this, args);
|
|
8
|
+
else
|
|
9
|
+
existing.logMethod.call(this, args, method, level);
|
|
10
|
+
const first = args[0];
|
|
11
|
+
const fields = typeof first === 'object' && first !== null ? { ...first } : {};
|
|
12
|
+
if (typeof first === 'string')
|
|
13
|
+
fields.msg = first;
|
|
14
|
+
else if (typeof args[1] === 'string')
|
|
15
|
+
fields.msg = args[1];
|
|
16
|
+
const error = first instanceof Error ? first : fields.err;
|
|
17
|
+
const severityNumber = level >= 60
|
|
18
|
+
? 21
|
|
19
|
+
: level >= 50
|
|
20
|
+
? 17
|
|
21
|
+
: level >= 40
|
|
22
|
+
? 13
|
|
23
|
+
: level >= 30
|
|
24
|
+
? 9
|
|
25
|
+
: level >= 20
|
|
26
|
+
? 5
|
|
27
|
+
: 1;
|
|
28
|
+
client.log({
|
|
29
|
+
severityNumber,
|
|
30
|
+
fields,
|
|
31
|
+
...(error instanceof Error ? { errorType: error.name } : {}),
|
|
32
|
+
});
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Context, SpanContext } from '@opentelemetry/api';
|
|
2
|
+
import type { ReadableSpan } from '@opentelemetry/sdk-trace';
|
|
3
|
+
import type { ReadableLogRecord } from '@opentelemetry/sdk-logs';
|
|
4
|
+
import type { SeverityNumber } from '@opentelemetry/api-logs';
|
|
5
|
+
import type { Runtime } from './runtime.js';
|
|
6
|
+
export interface StructuredLog {
|
|
7
|
+
readonly severityNumber?: SeverityNumber;
|
|
8
|
+
readonly severityText?: string;
|
|
9
|
+
readonly errorType?: string;
|
|
10
|
+
readonly eventName?: string;
|
|
11
|
+
/** Only explicitly selected fields are included as message text. */
|
|
12
|
+
readonly fields?: Readonly<Record<string, unknown>>;
|
|
13
|
+
}
|
|
14
|
+
export declare function spanContextOnly(input: SpanContext): SpanContext;
|
|
15
|
+
export declare function boundedText(input: string, limit: number): string;
|
|
16
|
+
export declare function boundedText(input: unknown, limit: number): string | undefined;
|
|
17
|
+
export declare function copySpan(span: ReadableSpan, runtime: Runtime): ReadableSpan | undefined;
|
|
18
|
+
/** The UTF-8 size of the MCP payload text an exported span holds. */
|
|
19
|
+
export declare function payloadBytes(span: ReadableSpan): number;
|
|
20
|
+
/** The exported span without its MCP payloads. */
|
|
21
|
+
export declare function withoutPayloads(span: ReadableSpan): ReadableSpan;
|
|
22
|
+
/**
|
|
23
|
+
* An upper estimate of an exported span's OTLP protobuf size: its text as
|
|
24
|
+
* UTF-8, and a generous allowance for each field's tag, length and value.
|
|
25
|
+
*/
|
|
26
|
+
export declare function estimatedBytes(span: ReadableSpan): number;
|
|
27
|
+
export declare function copyLog(record: ReadableLogRecord, runtime: Runtime): ReadableLogRecord | undefined;
|
|
28
|
+
export declare function makeLog(input: StructuredLog, ctx: Context, runtime: Runtime): ReadableLogRecord | undefined;
|
package/dist/privacy.js
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import { parseMarker } from 'agentrail-core';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { trace, SpanKind } from '@opentelemetry/api';
|
|
4
|
+
import { millisToHrTime } from '@opentelemetry/core';
|
|
5
|
+
export function spanContextOnly(input) {
|
|
6
|
+
return {
|
|
7
|
+
traceId: input.traceId,
|
|
8
|
+
spanId: input.spanId,
|
|
9
|
+
traceFlags: input.traceFlags,
|
|
10
|
+
...(input.isRemote === undefined ? {} : { isRemote: input.isRemote }),
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
const scope = { name: 'agentrail-node' };
|
|
14
|
+
export function boundedText(input, limit) {
|
|
15
|
+
return typeof input === 'string'
|
|
16
|
+
? input.replaceAll('\u0000', '').slice(0, limit).toWellFormed()
|
|
17
|
+
: undefined;
|
|
18
|
+
}
|
|
19
|
+
function text(input) {
|
|
20
|
+
return boundedText(input, 4096);
|
|
21
|
+
}
|
|
22
|
+
function sanitizedUrl(input) {
|
|
23
|
+
if (typeof input !== 'string' || !URL.canParse(input))
|
|
24
|
+
return undefined;
|
|
25
|
+
const url = new URL(input);
|
|
26
|
+
if (!['http:', 'https:'].includes(url.protocol))
|
|
27
|
+
return undefined;
|
|
28
|
+
const markers = url.searchParams.getAll('h');
|
|
29
|
+
url.search = '';
|
|
30
|
+
url.hash = '';
|
|
31
|
+
url.username = '';
|
|
32
|
+
url.password = '';
|
|
33
|
+
for (const marker of markers)
|
|
34
|
+
if (parseMarker(marker).valid)
|
|
35
|
+
url.searchParams.append('h', marker);
|
|
36
|
+
// Omit optional URL evidence instead of truncating its meaning or rejecting unrelated spans in the batch.
|
|
37
|
+
return url.href.length <= 4096 ? url.href : undefined;
|
|
38
|
+
}
|
|
39
|
+
export function copySpan(span, runtime) {
|
|
40
|
+
const metadata = runtime.spans.get(span);
|
|
41
|
+
if (metadata === undefined)
|
|
42
|
+
return undefined;
|
|
43
|
+
const attrs = {};
|
|
44
|
+
const original = span.attributes;
|
|
45
|
+
const fields = {
|
|
46
|
+
'http.request.method': original['http.request.method'] ?? original['http.method'],
|
|
47
|
+
'http.route': original['http.route'],
|
|
48
|
+
'http.response.status_code': original['http.response.status_code'] ?? original['http.status_code'],
|
|
49
|
+
'user_agent.original': original['user_agent.original'] ?? original['http.user_agent'],
|
|
50
|
+
'error.type': original['error.type'] ??
|
|
51
|
+
original['exception.type'] ??
|
|
52
|
+
span.events.find((event) => event.name === 'exception')?.attributes?.['exception.type'],
|
|
53
|
+
};
|
|
54
|
+
for (const [key, value] of Object.entries(fields))
|
|
55
|
+
if (typeof value === 'number' || typeof value === 'string')
|
|
56
|
+
attrs[key] = typeof value === 'string' ? boundedText(value, 4096) : value;
|
|
57
|
+
const address = original['server.address'];
|
|
58
|
+
const path = original['url.path'];
|
|
59
|
+
const scheme = original['url.scheme'];
|
|
60
|
+
const port = original['server.port'];
|
|
61
|
+
const query = original['url.query'];
|
|
62
|
+
const incomingUrl = typeof address === 'string' &&
|
|
63
|
+
typeof path === 'string' &&
|
|
64
|
+
typeof scheme === 'string'
|
|
65
|
+
? `${scheme}://${address}${typeof port === 'number' ? `:${port}` : ''}${path}${typeof query === 'string' ? `?${query}` : ''}`
|
|
66
|
+
: undefined;
|
|
67
|
+
const url = sanitizedUrl(original['url.full'] ?? original['http.url'] ?? incomingUrl);
|
|
68
|
+
if (url !== undefined)
|
|
69
|
+
attrs['url.full'] = url;
|
|
70
|
+
// An MCP handler inside its transport span is neither a step nor an entry:
|
|
71
|
+
// the transport span is the call.
|
|
72
|
+
const mark = metadata.mark?.step === false ? undefined : metadata.mark;
|
|
73
|
+
const step = mark !== undefined;
|
|
74
|
+
const entry = step || span.kind === SpanKind.SERVER || span.kind === SpanKind.CONSUMER;
|
|
75
|
+
if (entry)
|
|
76
|
+
Object.assign(attrs, metadata.mark?.identity ?? metadata.state.identity);
|
|
77
|
+
if (entry && metadata.state.location) {
|
|
78
|
+
const location = metadata.state.location;
|
|
79
|
+
for (const field of ['country', 'region', 'city', 'source']) {
|
|
80
|
+
const value = location[field];
|
|
81
|
+
if (value !== null)
|
|
82
|
+
attrs[`agentrail.client.location.${field}`] = boundedText(value, 128);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (span.kind === SpanKind.SERVER)
|
|
86
|
+
attrs['agentrail.ingress.verified'] = metadata.state.verifiedIngress;
|
|
87
|
+
if (mark !== undefined)
|
|
88
|
+
Object.assign(attrs, {
|
|
89
|
+
'agentrail.step': true,
|
|
90
|
+
'agentrail.step.surface': mark.surface,
|
|
91
|
+
'agentrail.step.kind': mark.kind,
|
|
92
|
+
});
|
|
93
|
+
if (metadata.mark?.performance !== undefined)
|
|
94
|
+
Object.assign(attrs, metadata.mark.performance);
|
|
95
|
+
const mcp = metadata.mark?.mcp;
|
|
96
|
+
if (mcp !== undefined) {
|
|
97
|
+
// The OpenTelemetry MCP server span's names. A resource is named only
|
|
98
|
+
// by its URI there, which can carry what was asked for, so it gets none.
|
|
99
|
+
attrs['mcp.method.name'] = boundedText(mcp.method, 128);
|
|
100
|
+
if (mcp.name !== undefined && mcp.method === 'tools/call')
|
|
101
|
+
attrs['gen_ai.tool.name'] = boundedText(mcp.name, 256);
|
|
102
|
+
if (mcp.name !== undefined && mcp.method === 'prompts/get')
|
|
103
|
+
attrs['gen_ai.prompt.name'] = boundedText(mcp.name, 256);
|
|
104
|
+
if (mcp.client !== undefined)
|
|
105
|
+
attrs['agentrail.mcp.client.name'] = boundedText(mcp.client, 128);
|
|
106
|
+
if (mcp.clientVersion !== undefined)
|
|
107
|
+
attrs['agentrail.mcp.client.version'] = boundedText(mcp.clientVersion, 128);
|
|
108
|
+
if (mcp.protocol !== undefined)
|
|
109
|
+
attrs['agentrail.mcp.protocol.version'] = boundedText(mcp.protocol, 64);
|
|
110
|
+
}
|
|
111
|
+
const facts = metadata.mark?.mcpFacts;
|
|
112
|
+
if (facts !== undefined)
|
|
113
|
+
Object.assign(attrs, mcpAttributes(facts));
|
|
114
|
+
const parent = span.parentSpanContext;
|
|
115
|
+
return {
|
|
116
|
+
name: boundedText(metadata.mark?.name ??
|
|
117
|
+
(typeof attrs['http.request.method'] === 'string'
|
|
118
|
+
? `HTTP ${attrs['http.request.method']}`
|
|
119
|
+
: 'backend.operation'), 4096),
|
|
120
|
+
kind: span.kind,
|
|
121
|
+
spanContext: () => spanContextOnly(span.spanContext()),
|
|
122
|
+
...(parent === undefined
|
|
123
|
+
? {}
|
|
124
|
+
: { parentSpanContext: spanContextOnly(parent) }),
|
|
125
|
+
startTime: [...span.startTime],
|
|
126
|
+
endTime: [...span.endTime],
|
|
127
|
+
duration: [...span.duration],
|
|
128
|
+
ended: span.ended,
|
|
129
|
+
status: { code: span.status.code },
|
|
130
|
+
attributes: attrs,
|
|
131
|
+
links: [
|
|
132
|
+
...span.links,
|
|
133
|
+
...(span.kind === SpanKind.SERVER ? metadata.state.links : []),
|
|
134
|
+
].map((link) => ({ context: spanContextOnly(link.context) })),
|
|
135
|
+
events: [],
|
|
136
|
+
resource: runtime.resource,
|
|
137
|
+
instrumentationScope: scope,
|
|
138
|
+
droppedAttributesCount: 0,
|
|
139
|
+
droppedEventsCount: 0,
|
|
140
|
+
droppedLinksCount: 0,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/** A method the collector keeps; any other is named only in the span name. */
|
|
144
|
+
const MCP_METHOD = /^[A-Za-z0-9_./-]{1,128}$/u;
|
|
145
|
+
function mcpAttributes(facts) {
|
|
146
|
+
const attrs = { 'agentrail.mcp.layer': facts.layer };
|
|
147
|
+
const optional = {
|
|
148
|
+
'agentrail.mcp.method': MCP_METHOD.test(facts.method)
|
|
149
|
+
? facts.method
|
|
150
|
+
: undefined,
|
|
151
|
+
'agentrail.mcp.session.id_hash': facts.sessionHash,
|
|
152
|
+
'agentrail.mcp.request.bytes': facts.requestBytes,
|
|
153
|
+
'agentrail.mcp.response.bytes': facts.responseBytes,
|
|
154
|
+
'agentrail.mcp.jsonrpc.error_code': facts.errorCode,
|
|
155
|
+
'agentrail.mcp.result.is_error': facts.isError,
|
|
156
|
+
// JSON text after the application's redact hook, never bounded by the
|
|
157
|
+
// 4,096-character cap: the capture truncates it only to fit one export.
|
|
158
|
+
'agentrail.mcp.request.payload': facts.requestPayload,
|
|
159
|
+
'agentrail.mcp.response.payload': facts.responsePayload,
|
|
160
|
+
'agentrail.mcp.request.truncated': facts.requestTruncated,
|
|
161
|
+
'agentrail.mcp.response.truncated': facts.responseTruncated,
|
|
162
|
+
};
|
|
163
|
+
for (const [key, value] of Object.entries(optional))
|
|
164
|
+
if (value !== undefined)
|
|
165
|
+
attrs[key] = value;
|
|
166
|
+
return { ...attrs, ...requestAttributes(facts) };
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* The request facts of a step whose message came by HTTP, as the contract's
|
|
170
|
+
* `mcpSpans.requestFacts` names them: the HTTP request's method, URL (its
|
|
171
|
+
* query cut to the marker lane, as on an HTTP span), user agent, header
|
|
172
|
+
* names, `Accept` and `Accept-Encoding`, the answer's status, and the
|
|
173
|
+
* message's JSON-RPC id. None over stdio.
|
|
174
|
+
*/
|
|
175
|
+
function requestAttributes(facts) {
|
|
176
|
+
const { request } = facts;
|
|
177
|
+
if (request === undefined)
|
|
178
|
+
return {};
|
|
179
|
+
const optional = {
|
|
180
|
+
'http.request.method': boundedText(request.method, 4096),
|
|
181
|
+
'url.full': sanitizedUrl(request.url),
|
|
182
|
+
'http.response.status_code': facts.httpStatus,
|
|
183
|
+
'user_agent.original': boundedText(request.userAgent, 4096),
|
|
184
|
+
// Names only, never a value; already within their own bound.
|
|
185
|
+
'agentrail.http.request.header_names': request.headerNames,
|
|
186
|
+
'agentrail.http.request.accept': boundedText(request.accept, 4096),
|
|
187
|
+
'agentrail.http.request.accept_encoding': boundedText(request.acceptEncoding, 4096),
|
|
188
|
+
'agentrail.mcp.jsonrpc.id': boundedText(facts.jsonrpcId, 4096),
|
|
189
|
+
};
|
|
190
|
+
const attrs = {};
|
|
191
|
+
for (const [key, value] of Object.entries(optional))
|
|
192
|
+
if (value !== undefined)
|
|
193
|
+
attrs[key] = value;
|
|
194
|
+
return attrs;
|
|
195
|
+
}
|
|
196
|
+
const PAYLOAD_ATTRIBUTES = [
|
|
197
|
+
'agentrail.mcp.request.payload',
|
|
198
|
+
'agentrail.mcp.response.payload',
|
|
199
|
+
'agentrail.mcp.request.truncated',
|
|
200
|
+
'agentrail.mcp.response.truncated',
|
|
201
|
+
];
|
|
202
|
+
/** The UTF-8 size of the MCP payload text an exported span holds. */
|
|
203
|
+
export function payloadBytes(span) {
|
|
204
|
+
let total = 0;
|
|
205
|
+
for (const key of PAYLOAD_ATTRIBUTES) {
|
|
206
|
+
const value = span.attributes[key];
|
|
207
|
+
if (typeof value === 'string')
|
|
208
|
+
total += Buffer.byteLength(value);
|
|
209
|
+
}
|
|
210
|
+
return total;
|
|
211
|
+
}
|
|
212
|
+
/** The exported span without its MCP payloads. */
|
|
213
|
+
export function withoutPayloads(span) {
|
|
214
|
+
const attributes = { ...span.attributes };
|
|
215
|
+
for (const key of PAYLOAD_ATTRIBUTES)
|
|
216
|
+
Reflect.deleteProperty(attributes, key);
|
|
217
|
+
return { ...span, attributes };
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* An upper estimate of an exported span's OTLP protobuf size: its text as
|
|
221
|
+
* UTF-8, and a generous allowance for each field's tag, length and value.
|
|
222
|
+
*/
|
|
223
|
+
export function estimatedBytes(span) {
|
|
224
|
+
let total = 128 + Buffer.byteLength(span.name) + span.links.length * 64;
|
|
225
|
+
for (const [key, value] of Object.entries(span.attributes))
|
|
226
|
+
total +=
|
|
227
|
+
16 +
|
|
228
|
+
Buffer.byteLength(key) +
|
|
229
|
+
(typeof value === 'string' ? Buffer.byteLength(value) : 16);
|
|
230
|
+
return total;
|
|
231
|
+
}
|
|
232
|
+
/** Fit an already-sanitized string, including JSON escaping, without splitting a code point. */
|
|
233
|
+
function fitLogText(value, budget) {
|
|
234
|
+
const prefix = (length) => {
|
|
235
|
+
const part = value.slice(0, length);
|
|
236
|
+
return part.isWellFormed() ? part : part.slice(0, -1);
|
|
237
|
+
};
|
|
238
|
+
let low = 0;
|
|
239
|
+
let high = value.length;
|
|
240
|
+
while (low < high) {
|
|
241
|
+
const middle = Math.ceil((low + high) / 2);
|
|
242
|
+
if (JSON.stringify(prefix(middle)).length <= budget)
|
|
243
|
+
low = middle;
|
|
244
|
+
else
|
|
245
|
+
high = middle - 1;
|
|
246
|
+
}
|
|
247
|
+
return prefix(low);
|
|
248
|
+
}
|
|
249
|
+
function selectedBody(fields, selected) {
|
|
250
|
+
let result = {};
|
|
251
|
+
let body;
|
|
252
|
+
for (const field of selected) {
|
|
253
|
+
const value = fields[field];
|
|
254
|
+
let scalar;
|
|
255
|
+
if (typeof value === 'string')
|
|
256
|
+
scalar = boundedText(value, 4096);
|
|
257
|
+
else if (typeof value === 'boolean' ||
|
|
258
|
+
value === null ||
|
|
259
|
+
(typeof value === 'number' && Number.isFinite(value)))
|
|
260
|
+
scalar = value;
|
|
261
|
+
else
|
|
262
|
+
continue;
|
|
263
|
+
const candidate = { ...result, [field]: scalar };
|
|
264
|
+
let encoded = JSON.stringify(candidate);
|
|
265
|
+
if (encoded.length > 4096) {
|
|
266
|
+
if (typeof scalar !== 'string')
|
|
267
|
+
continue;
|
|
268
|
+
const overhead = JSON.stringify({ ...result, [field]: '' }).length - 2;
|
|
269
|
+
const budget = 4096 - overhead;
|
|
270
|
+
if (budget < 2)
|
|
271
|
+
continue;
|
|
272
|
+
candidate[field] = fitLogText(scalar, budget);
|
|
273
|
+
encoded = JSON.stringify(candidate);
|
|
274
|
+
}
|
|
275
|
+
result = candidate;
|
|
276
|
+
body = encoded;
|
|
277
|
+
}
|
|
278
|
+
return body;
|
|
279
|
+
}
|
|
280
|
+
export function copyLog(record, runtime) {
|
|
281
|
+
if (runtime.options.input.logs?.uncorrelated === false &&
|
|
282
|
+
record.spanContext === undefined)
|
|
283
|
+
return undefined;
|
|
284
|
+
const body = selectedBody({ message: record.body, ...record.attributes }, runtime.options.input.logs?.includeFields ?? []);
|
|
285
|
+
const attributes = { 'agentrail.log.id': randomUUID() };
|
|
286
|
+
const error = text(record.attributes['error.type'] ?? record.attributes['exception.type']);
|
|
287
|
+
if (error !== undefined)
|
|
288
|
+
attributes['error.type'] = error;
|
|
289
|
+
if (body !== undefined)
|
|
290
|
+
attributes['agentrail.log.body_allowed'] = true;
|
|
291
|
+
return {
|
|
292
|
+
hrTime: [...record.hrTime],
|
|
293
|
+
hrTimeObserved: [...record.hrTimeObserved],
|
|
294
|
+
...(record.spanContext === undefined
|
|
295
|
+
? {}
|
|
296
|
+
: { spanContext: spanContextOnly(record.spanContext) }),
|
|
297
|
+
...(record.severityNumber === undefined
|
|
298
|
+
? {}
|
|
299
|
+
: { severityNumber: record.severityNumber }),
|
|
300
|
+
...(record.severityText === undefined
|
|
301
|
+
? {}
|
|
302
|
+
: { severityText: boundedText(record.severityText, 64) }),
|
|
303
|
+
...(record.eventName === undefined
|
|
304
|
+
? {}
|
|
305
|
+
: { eventName: boundedText(record.eventName, 256) }),
|
|
306
|
+
...(body === undefined ? {} : { body }),
|
|
307
|
+
attributes,
|
|
308
|
+
resource: runtime.resource,
|
|
309
|
+
instrumentationScope: scope,
|
|
310
|
+
droppedAttributesCount: 0,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
export function makeLog(input, ctx, runtime) {
|
|
314
|
+
const state = runtime.state(ctx);
|
|
315
|
+
const spanContext = state === undefined ? undefined : trace.getSpanContext(ctx);
|
|
316
|
+
const now = millisToHrTime(Date.now());
|
|
317
|
+
return copyLog({
|
|
318
|
+
hrTime: now,
|
|
319
|
+
hrTimeObserved: now,
|
|
320
|
+
...(spanContext === undefined ? {} : { spanContext }),
|
|
321
|
+
...(input.severityNumber === undefined
|
|
322
|
+
? {}
|
|
323
|
+
: { severityNumber: input.severityNumber }),
|
|
324
|
+
...(input.severityText === undefined
|
|
325
|
+
? {}
|
|
326
|
+
: { severityText: input.severityText }),
|
|
327
|
+
...(input.eventName === undefined ? {} : { eventName: input.eventName }),
|
|
328
|
+
resource: runtime.resource,
|
|
329
|
+
instrumentationScope: scope,
|
|
330
|
+
attributes: {
|
|
331
|
+
...input.fields,
|
|
332
|
+
...(input.errorType === undefined
|
|
333
|
+
? {}
|
|
334
|
+
: { 'error.type': input.errorType }),
|
|
335
|
+
},
|
|
336
|
+
droppedAttributesCount: 0,
|
|
337
|
+
}, runtime);
|
|
338
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Sampler, SpanProcessor } from '@opentelemetry/sdk-trace';
|
|
2
|
+
import type { LogRecordProcessor } from '@opentelemetry/sdk-logs';
|
|
3
|
+
import { ExportQueue } from './queue.js';
|
|
4
|
+
import type { Runtime } from './runtime.js';
|
|
5
|
+
export declare function processors(runtime: Runtime): {
|
|
6
|
+
spanProcessor: SpanProcessor;
|
|
7
|
+
logProcessor: LogRecordProcessor;
|
|
8
|
+
sampler: (base: Sampler) => Sampler;
|
|
9
|
+
spans: ExportQueue<import("@opentelemetry/sdk-trace").ReadableSpan>;
|
|
10
|
+
logs: ExportQueue<import("@opentelemetry/sdk-logs").ReadableLogRecord>;
|
|
11
|
+
};
|