agentrail-node 0.0.0 → 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.
- package/LICENSE +201 -0
- package/README.md +155 -0
- package/dist/client.d.ts +17 -0
- package/dist/client.js +95 -0
- package/dist/http.d.ts +10 -0
- package/dist/http.js +177 -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 +77 -0
- package/dist/mcp.d.ts +10 -0
- package/dist/mcp.js +45 -0
- package/dist/options.d.ts +65 -0
- package/dist/options.js +79 -0
- package/dist/pino.d.ts +6 -0
- package/dist/pino.js +35 -0
- package/dist/privacy.d.ts +19 -0
- package/dist/privacy.js +227 -0
- package/dist/processors.d.ts +11 -0
- package/dist/processors.js +64 -0
- package/dist/queue.d.ts +36 -0
- package/dist/queue.js +132 -0
- package/dist/runtime.d.ts +30 -0
- package/dist/runtime.js +52 -0
- package/dist/suppression.d.ts +3 -0
- package/dist/suppression.js +14 -0
- package/package.json +69 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type NodeOptions } from './options.js';
|
|
2
|
+
export { CaptureError, ConfigurationError, type NodeOptions, type VerifiedIdentity, type MilestoneContext, type QueueOptions, } from './options.js';
|
|
3
|
+
export type { AgentrailNode } from './client.js';
|
|
4
|
+
export type { StructuredLog } from './privacy.js';
|
|
5
|
+
export { init } from './init.js';
|
|
6
|
+
/** Construct before the application's provider. This factory never registers globals. */
|
|
7
|
+
export declare function createProcessors(options: NodeOptions): {
|
|
8
|
+
client: import("./client.js").AgentrailNode;
|
|
9
|
+
spanProcessor: import("@opentelemetry/sdk-trace").SpanProcessor;
|
|
10
|
+
logProcessor: import("@opentelemetry/sdk-logs").LogRecordProcessor;
|
|
11
|
+
sampler: (base: import("@opentelemetry/sdk-trace").Sampler) => import("@opentelemetry/sdk-trace").Sampler;
|
|
12
|
+
propagator: import("@opentelemetry/api").TextMapPropagator<any>;
|
|
13
|
+
httpOptions: import("@opentelemetry/instrumentation-http").HttpInstrumentationConfig;
|
|
14
|
+
undiciOptions: import("@opentelemetry/instrumentation-undici").UndiciInstrumentationConfig<import("@opentelemetry/instrumentation-undici").UndiciRequest, import("@opentelemetry/instrumentation-undici").UndiciResponse>;
|
|
15
|
+
};
|
|
16
|
+
export type AgentrailProcessors = ReturnType<typeof createProcessors>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { resolveOptions } from './options.js';
|
|
2
|
+
import { Runtime } from './runtime.js';
|
|
3
|
+
import { processors } from './processors.js';
|
|
4
|
+
import { createClient } from './client.js';
|
|
5
|
+
import { httpCapture } from './http.js';
|
|
6
|
+
export { CaptureError, ConfigurationError, } from './options.js';
|
|
7
|
+
export { init } from './init.js';
|
|
8
|
+
/** Construct before the application's provider. This factory never registers globals. */
|
|
9
|
+
export function createProcessors(options) {
|
|
10
|
+
const runtime = new Runtime(resolveOptions(options));
|
|
11
|
+
const queues = processors(runtime);
|
|
12
|
+
const http = httpCapture(runtime);
|
|
13
|
+
const underlying = queues.spanProcessor.onStart.bind(queues.spanProcessor);
|
|
14
|
+
queues.spanProcessor.onStart = (span, ctx) => {
|
|
15
|
+
underlying(span, ctx);
|
|
16
|
+
http.rememberPort(span, span.attributes['agentrail.network.port']);
|
|
17
|
+
};
|
|
18
|
+
return {
|
|
19
|
+
client: createClient(runtime, queues),
|
|
20
|
+
spanProcessor: queues.spanProcessor,
|
|
21
|
+
logProcessor: queues.logProcessor,
|
|
22
|
+
sampler: queues.sampler,
|
|
23
|
+
propagator: http.propagator,
|
|
24
|
+
httpOptions: http.httpOptions,
|
|
25
|
+
undiciOptions: http.undiciOptions,
|
|
26
|
+
};
|
|
27
|
+
}
|
package/dist/init.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type NodeOptions } from './options.js';
|
|
2
|
+
import type { AgentrailNode } from './client.js';
|
|
3
|
+
/** Call before loading application HTTP modules. Use createProcessors when another OTel provider owns startup. */
|
|
4
|
+
export declare function init(options: NodeOptions): Promise<AgentrailNode>;
|
package/dist/init.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { createRequire, syncBuiltinESMExports } from 'node:module';
|
|
2
|
+
import { context, propagation, trace } from '@opentelemetry/api';
|
|
3
|
+
import { logs } from '@opentelemetry/api-logs';
|
|
4
|
+
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
|
|
5
|
+
import { AlwaysOnSampler, TracerProvider } from '@opentelemetry/sdk-trace';
|
|
6
|
+
import { LoggerProvider } from '@opentelemetry/sdk-logs';
|
|
7
|
+
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
|
|
8
|
+
import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';
|
|
9
|
+
import { createProcessors } from './index.js';
|
|
10
|
+
import { ConfigurationError } from './options.js';
|
|
11
|
+
let installed;
|
|
12
|
+
/** Call before loading application HTTP modules. Use createProcessors when another OTel provider owns startup. */
|
|
13
|
+
export function init(options) {
|
|
14
|
+
if (installed !== undefined) {
|
|
15
|
+
if (installed.options !== options)
|
|
16
|
+
throw new ConfigurationError('Agentrail is already initialized. Reuse the original options and client.');
|
|
17
|
+
return Promise.resolve(installed.client);
|
|
18
|
+
}
|
|
19
|
+
const sdk = createProcessors(options);
|
|
20
|
+
const provider = new TracerProvider({
|
|
21
|
+
sampler: sdk.sampler(new AlwaysOnSampler()),
|
|
22
|
+
spanProcessors: [sdk.spanProcessor],
|
|
23
|
+
});
|
|
24
|
+
if (!trace.setGlobalTracerProvider(provider)) {
|
|
25
|
+
void sdk.client.shutdown();
|
|
26
|
+
throw new ConfigurationError('A tracer provider is already installed. Wire createProcessors into its construction instead.');
|
|
27
|
+
}
|
|
28
|
+
const manager = new AsyncLocalStorageContextManager().enable();
|
|
29
|
+
if (!context.setGlobalContextManager(manager)) {
|
|
30
|
+
trace.disable();
|
|
31
|
+
manager.disable();
|
|
32
|
+
void provider.shutdown();
|
|
33
|
+
throw new ConfigurationError('An OTel context manager is already installed. Use createProcessors with the existing setup.');
|
|
34
|
+
}
|
|
35
|
+
if (!propagation.setGlobalPropagator(sdk.propagator)) {
|
|
36
|
+
trace.disable();
|
|
37
|
+
context.disable();
|
|
38
|
+
manager.disable();
|
|
39
|
+
void provider.shutdown();
|
|
40
|
+
throw new ConfigurationError('An OTel propagator is already installed. Use createProcessors with the existing setup.');
|
|
41
|
+
}
|
|
42
|
+
const logger = new LoggerProvider({ processors: [sdk.logProcessor] });
|
|
43
|
+
const ownLogs = logs.setGlobalLoggerProvider(logger) === logger;
|
|
44
|
+
if (!ownLogs) {
|
|
45
|
+
trace.disable();
|
|
46
|
+
context.disable();
|
|
47
|
+
propagation.disable();
|
|
48
|
+
manager.disable();
|
|
49
|
+
void provider.shutdown();
|
|
50
|
+
void logger.shutdown();
|
|
51
|
+
throw new ConfigurationError('A logger provider is already installed. Use createProcessors with the existing setup.');
|
|
52
|
+
}
|
|
53
|
+
const http = new HttpInstrumentation(sdk.httpOptions);
|
|
54
|
+
const undici = new UndiciInstrumentation(sdk.undiciOptions);
|
|
55
|
+
http.setTracerProvider(provider);
|
|
56
|
+
undici.setTracerProvider(provider);
|
|
57
|
+
// Load core modules through the supported instrumentation loader, then refresh Node's ESM bindings.
|
|
58
|
+
const require = createRequire(import.meta.url);
|
|
59
|
+
require('node:http');
|
|
60
|
+
require('node:https');
|
|
61
|
+
syncBuiltinESMExports();
|
|
62
|
+
let stopping;
|
|
63
|
+
const client = {
|
|
64
|
+
...sdk.client,
|
|
65
|
+
shutdown() {
|
|
66
|
+
stopping ??= (async () => {
|
|
67
|
+
http.disable();
|
|
68
|
+
undici.disable();
|
|
69
|
+
await Promise.all([provider.shutdown(), logger.shutdown()]);
|
|
70
|
+
manager.disable();
|
|
71
|
+
})();
|
|
72
|
+
return stopping;
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
installed = { options, client };
|
|
76
|
+
return Promise.resolve(client);
|
|
77
|
+
}
|
package/dist/mcp.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AgentrailNode } from './client.js';
|
|
2
|
+
export interface McpCaptureOptions {
|
|
3
|
+
readonly client: AgentrailNode;
|
|
4
|
+
}
|
|
5
|
+
/** Wrap the callbacks passed to public registerTool/registerResource/registerPrompt APIs. No transport is patched. */
|
|
6
|
+
export declare function mcp(options: McpCaptureOptions): {
|
|
7
|
+
tool: <Args extends unknown[], Result>(name: string, handler: (...args: Args) => Result | Promise<Result>) => (...args: Args) => Promise<Result>;
|
|
8
|
+
resource: <Args extends unknown[], Result>(name: string, handler: (...args: Args) => Result | Promise<Result>) => (...args: Args) => Promise<Result>;
|
|
9
|
+
prompt: <Args extends unknown[], Result>(name: string, handler: (...args: Args) => Result | Promise<Result>) => (...args: Args) => Promise<Result>;
|
|
10
|
+
};
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { context, trace, SpanStatusCode } from '@opentelemetry/api';
|
|
2
|
+
import { boundedText } from './privacy.js';
|
|
3
|
+
function record(value) {
|
|
4
|
+
return typeof value === 'object' && value !== null
|
|
5
|
+
? value
|
|
6
|
+
: undefined;
|
|
7
|
+
}
|
|
8
|
+
/** Wrap the callbacks passed to public registerTool/registerResource/registerPrompt APIs. No transport is patched. */
|
|
9
|
+
export function mcp(options) {
|
|
10
|
+
function wrap(method, name, handler) {
|
|
11
|
+
return (...args) => {
|
|
12
|
+
// All supported registration callbacks receive ServerContext as their final argument.
|
|
13
|
+
const ctx = args.at(-1);
|
|
14
|
+
const envelope = record(ctx.mcpReq.envelope);
|
|
15
|
+
const clientInfo = record(envelope?.['io.modelcontextprotocol/clientInfo']);
|
|
16
|
+
const protocol = boundedText(envelope?.['io.modelcontextprotocol/protocolVersion'] ??
|
|
17
|
+
ctx.http?.req?.headers.get('mcp-protocol-version'), 64);
|
|
18
|
+
const client = boundedText(clientInfo?.name, 128);
|
|
19
|
+
const version = boundedText(clientInfo?.version, 128);
|
|
20
|
+
return options.client.milestone(`mcp.${method}:${name}`.slice(0, 256), {
|
|
21
|
+
surface: 'mcp',
|
|
22
|
+
kind: method === 'tools/call' ? 'tool.call' : `mcp.${method}`,
|
|
23
|
+
mcp: {
|
|
24
|
+
method,
|
|
25
|
+
...(client === undefined ? {} : { client }),
|
|
26
|
+
...(version === undefined ? {} : { clientVersion: version }),
|
|
27
|
+
...(protocol === undefined ? {} : { protocol }),
|
|
28
|
+
},
|
|
29
|
+
}, async () => {
|
|
30
|
+
const result = await handler(...args);
|
|
31
|
+
if (record(result)?.isError === true) {
|
|
32
|
+
const span = trace.getSpan(context.active());
|
|
33
|
+
span?.setStatus({ code: SpanStatusCode.ERROR });
|
|
34
|
+
span?.setAttribute('error.type', 'McpOperationError');
|
|
35
|
+
}
|
|
36
|
+
return result;
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
tool: (name, handler) => wrap('tools/call', name, handler),
|
|
42
|
+
resource: (name, handler) => wrap('resources/read', name, handler),
|
|
43
|
+
prompt: (name, handler) => wrap('prompts/get', name, handler),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { PrincipalKind, Surface } 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 MilestoneContext {
|
|
9
|
+
readonly surface: Surface;
|
|
10
|
+
readonly kind: string;
|
|
11
|
+
readonly mcp?: {
|
|
12
|
+
readonly method: string;
|
|
13
|
+
readonly client?: string;
|
|
14
|
+
readonly clientVersion?: string;
|
|
15
|
+
readonly protocol?: string;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export interface QueueOptions {
|
|
19
|
+
readonly maxRecords: number;
|
|
20
|
+
readonly batchSize: number;
|
|
21
|
+
readonly scheduledDelayMs: number;
|
|
22
|
+
readonly exportTimeoutMs: number;
|
|
23
|
+
readonly flushTimeoutMs: number;
|
|
24
|
+
readonly shutdownTimeoutMs: number;
|
|
25
|
+
}
|
|
26
|
+
export interface NodeOptions {
|
|
27
|
+
/** Retain customer propagation for unmanaged work; register the returned SDK propagator once. */
|
|
28
|
+
readonly propagator?: import('@opentelemetry/api').TextMapPropagator;
|
|
29
|
+
readonly collector: {
|
|
30
|
+
readonly endpoint: string;
|
|
31
|
+
readonly secret: string;
|
|
32
|
+
};
|
|
33
|
+
readonly hashKey: string;
|
|
34
|
+
readonly serviceName: string;
|
|
35
|
+
readonly serviceInstanceId?: string;
|
|
36
|
+
/** Exact http(s) origins permitted to receive signed trace context. Defaults to none. */
|
|
37
|
+
readonly outboundOrigins?: readonly string[];
|
|
38
|
+
readonly ignoreIncomingRequest?: (request: import('node:http').IncomingMessage) => boolean;
|
|
39
|
+
readonly logs?: {
|
|
40
|
+
readonly includeFields?: readonly string[];
|
|
41
|
+
readonly uncorrelated?: boolean;
|
|
42
|
+
};
|
|
43
|
+
readonly queue?: Partial<QueueOptions>;
|
|
44
|
+
readonly onError?: (error: CaptureError) => void;
|
|
45
|
+
}
|
|
46
|
+
export type CaptureCode = 'queue_full' | 'export_failed' | 'deadline' | 'closed' | 'handoff_refused' | 'entry_not_recording' | 'identity_outside_request';
|
|
47
|
+
export declare class CaptureError extends Error {
|
|
48
|
+
readonly code: CaptureCode;
|
|
49
|
+
readonly signal: 'traces' | 'logs' | 'context';
|
|
50
|
+
readonly count: number;
|
|
51
|
+
readonly name = "AgentrailCaptureError";
|
|
52
|
+
constructor(code: CaptureCode, signal: 'traces' | 'logs' | 'context', count: number, cause?: Error);
|
|
53
|
+
}
|
|
54
|
+
export declare class ConfigurationError extends Error {
|
|
55
|
+
readonly name = "AgentrailConfigurationError";
|
|
56
|
+
}
|
|
57
|
+
export interface ResolvedOptions {
|
|
58
|
+
readonly input: NodeOptions;
|
|
59
|
+
readonly endpoint: string;
|
|
60
|
+
readonly instance: string;
|
|
61
|
+
readonly origins: ReadonlySet<string>;
|
|
62
|
+
readonly queue: QueueOptions;
|
|
63
|
+
readonly report: (error: CaptureError) => void;
|
|
64
|
+
}
|
|
65
|
+
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
|
+
}
|
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,19 @@
|
|
|
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
|
+
export declare function copyLog(record: ReadableLogRecord, runtime: Runtime): ReadableLogRecord | undefined;
|
|
19
|
+
export declare function makeLog(input: StructuredLog, ctx: Context, runtime: Runtime): ReadableLogRecord | undefined;
|
package/dist/privacy.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
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
|
+
const entry = metadata.mark !== undefined ||
|
|
71
|
+
span.kind === SpanKind.SERVER ||
|
|
72
|
+
span.kind === SpanKind.CONSUMER;
|
|
73
|
+
if (entry)
|
|
74
|
+
Object.assign(attrs, metadata.mark?.identity ?? metadata.state.identity);
|
|
75
|
+
if (span.kind === SpanKind.SERVER)
|
|
76
|
+
attrs['agentrail.ingress.verified'] = metadata.state.verifiedIngress;
|
|
77
|
+
if (metadata.mark !== undefined)
|
|
78
|
+
Object.assign(attrs, {
|
|
79
|
+
'agentrail.step': true,
|
|
80
|
+
'agentrail.step.surface': metadata.mark.surface,
|
|
81
|
+
'agentrail.step.kind': metadata.mark.kind,
|
|
82
|
+
});
|
|
83
|
+
const mcp = metadata.mark?.mcp;
|
|
84
|
+
if (mcp !== undefined) {
|
|
85
|
+
if (mcp.client !== undefined)
|
|
86
|
+
attrs['agentrail.mcp.client.name'] = boundedText(mcp.client, 128);
|
|
87
|
+
if (mcp.clientVersion !== undefined)
|
|
88
|
+
attrs['agentrail.mcp.client.version'] = boundedText(mcp.clientVersion, 128);
|
|
89
|
+
if (mcp.protocol !== undefined)
|
|
90
|
+
attrs['agentrail.mcp.protocol.version'] = boundedText(mcp.protocol, 64);
|
|
91
|
+
}
|
|
92
|
+
const parent = span.parentSpanContext;
|
|
93
|
+
return {
|
|
94
|
+
name: boundedText(metadata.mark?.name ??
|
|
95
|
+
(typeof attrs['http.request.method'] === 'string'
|
|
96
|
+
? `HTTP ${attrs['http.request.method']}`
|
|
97
|
+
: 'backend.operation'), 4096),
|
|
98
|
+
kind: span.kind,
|
|
99
|
+
spanContext: () => spanContextOnly(span.spanContext()),
|
|
100
|
+
...(parent === undefined
|
|
101
|
+
? {}
|
|
102
|
+
: { parentSpanContext: spanContextOnly(parent) }),
|
|
103
|
+
startTime: [...span.startTime],
|
|
104
|
+
endTime: [...span.endTime],
|
|
105
|
+
duration: [...span.duration],
|
|
106
|
+
ended: span.ended,
|
|
107
|
+
status: { code: span.status.code },
|
|
108
|
+
attributes: attrs,
|
|
109
|
+
links: [
|
|
110
|
+
...span.links,
|
|
111
|
+
...(span.kind === SpanKind.SERVER ? metadata.state.links : []),
|
|
112
|
+
].map((link) => ({ context: spanContextOnly(link.context) })),
|
|
113
|
+
events: [],
|
|
114
|
+
resource: runtime.resource,
|
|
115
|
+
instrumentationScope: scope,
|
|
116
|
+
droppedAttributesCount: 0,
|
|
117
|
+
droppedEventsCount: 0,
|
|
118
|
+
droppedLinksCount: 0,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/** Fit an already-sanitized string, including JSON escaping, without splitting a code point. */
|
|
122
|
+
function fitLogText(value, budget) {
|
|
123
|
+
const prefix = (length) => {
|
|
124
|
+
const part = value.slice(0, length);
|
|
125
|
+
return part.isWellFormed() ? part : part.slice(0, -1);
|
|
126
|
+
};
|
|
127
|
+
let low = 0;
|
|
128
|
+
let high = value.length;
|
|
129
|
+
while (low < high) {
|
|
130
|
+
const middle = Math.ceil((low + high) / 2);
|
|
131
|
+
if (JSON.stringify(prefix(middle)).length <= budget)
|
|
132
|
+
low = middle;
|
|
133
|
+
else
|
|
134
|
+
high = middle - 1;
|
|
135
|
+
}
|
|
136
|
+
return prefix(low);
|
|
137
|
+
}
|
|
138
|
+
function selectedBody(fields, selected) {
|
|
139
|
+
let result = {};
|
|
140
|
+
let body;
|
|
141
|
+
for (const field of selected) {
|
|
142
|
+
const value = fields[field];
|
|
143
|
+
let scalar;
|
|
144
|
+
if (typeof value === 'string')
|
|
145
|
+
scalar = boundedText(value, 4096);
|
|
146
|
+
else if (typeof value === 'boolean' ||
|
|
147
|
+
value === null ||
|
|
148
|
+
(typeof value === 'number' && Number.isFinite(value)))
|
|
149
|
+
scalar = value;
|
|
150
|
+
else
|
|
151
|
+
continue;
|
|
152
|
+
const candidate = { ...result, [field]: scalar };
|
|
153
|
+
let encoded = JSON.stringify(candidate);
|
|
154
|
+
if (encoded.length > 4096) {
|
|
155
|
+
if (typeof scalar !== 'string')
|
|
156
|
+
continue;
|
|
157
|
+
const overhead = JSON.stringify({ ...result, [field]: '' }).length - 2;
|
|
158
|
+
const budget = 4096 - overhead;
|
|
159
|
+
if (budget < 2)
|
|
160
|
+
continue;
|
|
161
|
+
candidate[field] = fitLogText(scalar, budget);
|
|
162
|
+
encoded = JSON.stringify(candidate);
|
|
163
|
+
}
|
|
164
|
+
result = candidate;
|
|
165
|
+
body = encoded;
|
|
166
|
+
}
|
|
167
|
+
return body;
|
|
168
|
+
}
|
|
169
|
+
export function copyLog(record, runtime) {
|
|
170
|
+
if (runtime.options.input.logs?.uncorrelated === false &&
|
|
171
|
+
record.spanContext === undefined)
|
|
172
|
+
return undefined;
|
|
173
|
+
const body = selectedBody({ message: record.body, ...record.attributes }, runtime.options.input.logs?.includeFields ?? []);
|
|
174
|
+
const attributes = { 'agentrail.log.id': randomUUID() };
|
|
175
|
+
const error = text(record.attributes['error.type'] ?? record.attributes['exception.type']);
|
|
176
|
+
if (error !== undefined)
|
|
177
|
+
attributes['error.type'] = error;
|
|
178
|
+
if (body !== undefined)
|
|
179
|
+
attributes['agentrail.log.body_allowed'] = true;
|
|
180
|
+
return {
|
|
181
|
+
hrTime: [...record.hrTime],
|
|
182
|
+
hrTimeObserved: [...record.hrTimeObserved],
|
|
183
|
+
...(record.spanContext === undefined
|
|
184
|
+
? {}
|
|
185
|
+
: { spanContext: spanContextOnly(record.spanContext) }),
|
|
186
|
+
...(record.severityNumber === undefined
|
|
187
|
+
? {}
|
|
188
|
+
: { severityNumber: record.severityNumber }),
|
|
189
|
+
...(record.severityText === undefined
|
|
190
|
+
? {}
|
|
191
|
+
: { severityText: boundedText(record.severityText, 64) }),
|
|
192
|
+
...(record.eventName === undefined
|
|
193
|
+
? {}
|
|
194
|
+
: { eventName: boundedText(record.eventName, 256) }),
|
|
195
|
+
...(body === undefined ? {} : { body }),
|
|
196
|
+
attributes,
|
|
197
|
+
resource: runtime.resource,
|
|
198
|
+
instrumentationScope: scope,
|
|
199
|
+
droppedAttributesCount: 0,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
export function makeLog(input, ctx, runtime) {
|
|
203
|
+
const state = runtime.state(ctx);
|
|
204
|
+
const spanContext = state === undefined ? undefined : trace.getSpanContext(ctx);
|
|
205
|
+
const now = millisToHrTime(Date.now());
|
|
206
|
+
return copyLog({
|
|
207
|
+
hrTime: now,
|
|
208
|
+
hrTimeObserved: now,
|
|
209
|
+
...(spanContext === undefined ? {} : { spanContext }),
|
|
210
|
+
...(input.severityNumber === undefined
|
|
211
|
+
? {}
|
|
212
|
+
: { severityNumber: input.severityNumber }),
|
|
213
|
+
...(input.severityText === undefined
|
|
214
|
+
? {}
|
|
215
|
+
: { severityText: input.severityText }),
|
|
216
|
+
...(input.eventName === undefined ? {} : { eventName: input.eventName }),
|
|
217
|
+
resource: runtime.resource,
|
|
218
|
+
instrumentationScope: scope,
|
|
219
|
+
attributes: {
|
|
220
|
+
...input.fields,
|
|
221
|
+
...(input.errorType === undefined
|
|
222
|
+
? {}
|
|
223
|
+
: { 'error.type': input.errorType }),
|
|
224
|
+
},
|
|
225
|
+
droppedAttributesCount: 0,
|
|
226
|
+
}, runtime);
|
|
227
|
+
}
|
|
@@ -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
|
+
};
|