@watchtowerobservability/node 0.4.0 → 0.6.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/README.md +44 -9
- package/dist/cjs/buffer.d.ts +2 -3
- package/dist/cjs/buffer.js +6 -6
- package/dist/cjs/env.d.ts +12 -0
- package/dist/cjs/env.js +37 -0
- package/dist/cjs/errors.d.ts +8 -0
- package/dist/cjs/errors.js +23 -0
- package/dist/cjs/index.d.ts +34 -12
- package/dist/cjs/index.js +106 -52
- package/dist/cjs/instrument.d.ts +7 -0
- package/dist/cjs/instrument.js +51 -0
- package/dist/cjs/integrations/genai-agents.d.ts +4 -1
- package/dist/cjs/integrations/genai-agents.js +27 -24
- package/dist/cjs/integrations/genai-frameworks.d.ts +25 -0
- package/dist/cjs/integrations/genai-frameworks.js +211 -0
- package/dist/cjs/integrations/genai.d.ts +1 -0
- package/dist/cjs/integrations/genai.js +7 -2
- package/dist/cjs/integrations/next.d.ts +4 -1
- package/dist/cjs/integrations/next.js +13 -7
- package/dist/cjs/load.d.ts +2 -0
- package/dist/cjs/load.js +54 -5
- package/dist/cjs/metrics.d.ts +1 -2
- package/dist/cjs/metrics.js +6 -6
- package/dist/cjs/origin.d.ts +9 -0
- package/dist/cjs/origin.js +43 -0
- package/dist/cjs/redact.d.ts +8 -0
- package/dist/cjs/redact.js +43 -0
- package/dist/cjs/register.d.ts +1 -0
- package/dist/cjs/register.js +29 -0
- package/dist/cjs/sampling.d.ts +53 -0
- package/dist/cjs/sampling.js +98 -0
- package/dist/esm/buffer.d.ts +2 -3
- package/dist/esm/buffer.js +6 -6
- package/dist/esm/env.d.ts +12 -0
- package/dist/esm/env.js +33 -0
- package/dist/esm/errors.d.ts +8 -0
- package/dist/esm/errors.js +22 -0
- package/dist/esm/index.d.ts +34 -12
- package/dist/esm/index.js +104 -51
- package/dist/esm/instrument.d.ts +7 -0
- package/dist/esm/instrument.js +48 -0
- package/dist/esm/integrations/genai-agents.d.ts +4 -1
- package/dist/esm/integrations/genai-agents.js +4 -4
- package/dist/esm/integrations/genai-frameworks.d.ts +25 -0
- package/dist/esm/integrations/genai-frameworks.js +206 -0
- package/dist/esm/integrations/genai.d.ts +1 -0
- package/dist/esm/integrations/genai.js +3 -1
- package/dist/esm/integrations/next.d.ts +4 -1
- package/dist/esm/integrations/next.js +11 -6
- package/dist/esm/load.d.ts +2 -0
- package/dist/esm/load.js +78 -2
- package/dist/esm/metrics.d.ts +1 -2
- package/dist/esm/metrics.js +5 -5
- package/dist/esm/origin.d.ts +9 -0
- package/dist/esm/origin.js +39 -0
- package/dist/esm/redact.d.ts +8 -0
- package/dist/esm/redact.js +39 -0
- package/dist/esm/register.d.ts +1 -0
- package/dist/esm/register.js +27 -0
- package/dist/esm/sampling.d.ts +53 -0
- package/dist/esm/sampling.js +91 -0
- package/package.json +86 -14
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.instrumentAll = instrumentAll;
|
|
4
|
+
// Auto-instrumentation: node:http, fetch (undici), pg and ioredis, each only when its optional peer package is installed.
|
|
5
|
+
const load_js_1 = require("./load.js");
|
|
6
|
+
const ENTRIES = [
|
|
7
|
+
{
|
|
8
|
+
pkg: '@opentelemetry/instrumentation-http', ctor: 'HttpInstrumentation',
|
|
9
|
+
// our own exports and API calls must not become spans
|
|
10
|
+
opts: (self) => ({ ignoreOutgoingRequestHook: (r) => self.some((u) => (r.hostname || r.host) === u.hostname && String(r.port ?? (u.protocol === 'https:' ? 443 : 80)) === String(u.port || (u.protocol === 'https:' ? 443 : 80))) }),
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
pkg: '@opentelemetry/instrumentation-undici', ctor: 'UndiciInstrumentation',
|
|
14
|
+
opts: (self) => ({ ignoreRequestHook: (r) => self.some((u) => r.origin === u.origin) }),
|
|
15
|
+
},
|
|
16
|
+
{ pkg: '@opentelemetry/instrumentation-pg', ctor: 'PgInstrumentation', opts: () => ({}) },
|
|
17
|
+
{ pkg: '@opentelemetry/instrumentation-ioredis', ctor: 'IORedisInstrumentation', opts: () => ({}) },
|
|
18
|
+
];
|
|
19
|
+
/** Register whichever of the four instrumentations is installed. Returns the package names that were enabled. */
|
|
20
|
+
function instrumentAll(p, selfUrls) {
|
|
21
|
+
let registerInstrumentations;
|
|
22
|
+
try {
|
|
23
|
+
({ registerInstrumentations } = (0, load_js_1.load)('@opentelemetry/instrumentation'));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return []; // optional peer not installed
|
|
27
|
+
}
|
|
28
|
+
const self = selfUrls.flatMap((u) => { try {
|
|
29
|
+
return [new URL(u)];
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return [];
|
|
33
|
+
} });
|
|
34
|
+
const found = [];
|
|
35
|
+
const names = [];
|
|
36
|
+
for (const e of ENTRIES) {
|
|
37
|
+
try {
|
|
38
|
+
const Ctor = (0, load_js_1.load)(e.pkg)[e.ctor];
|
|
39
|
+
if (Ctor) {
|
|
40
|
+
found.push(new Ctor(e.opts(self)));
|
|
41
|
+
names.push(e.pkg);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// package not installed (or failed to construct): skip it, never break init
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (found.length)
|
|
49
|
+
registerInstrumentations({ instrumentations: found, tracerProvider: p.tracerProvider, meterProvider: p.meterProvider });
|
|
50
|
+
return names;
|
|
51
|
+
}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import type { Span } from '@opentelemetry/api';
|
|
1
|
+
import type { Attributes, Span } from '@opentelemetry/api';
|
|
2
2
|
type Obj = Record<string, unknown>;
|
|
3
|
+
export declare const obj: (v: unknown) => Obj;
|
|
4
|
+
export declare const s: (v: unknown) => string;
|
|
5
|
+
export declare function start(name: string, attrs: Attributes, parent?: Span, startTime?: number): Span;
|
|
3
6
|
/** The part of LlamaIndex.TS `Settings.callbackManager` used here. */
|
|
4
7
|
export interface CallbackManagerLike {
|
|
5
8
|
on(event: string, handler: (e: {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.AgentsProcessor = void 0;
|
|
3
|
+
exports.AgentsProcessor = exports.s = exports.obj = void 0;
|
|
4
|
+
exports.start = start;
|
|
4
5
|
exports.instrumentLlamaIndex = instrumentLlamaIndex;
|
|
5
6
|
exports.instrumentOpenAIAgents = instrumentOpenAIAgents;
|
|
6
7
|
// GenAI spans for frameworks with their own hooks: LlamaIndex.TS (callback manager events) and the OpenAI Agents
|
|
@@ -10,41 +11,43 @@ exports.instrumentOpenAIAgents = instrumentOpenAIAgents;
|
|
|
10
11
|
const api_1 = require("@opentelemetry/api");
|
|
11
12
|
const genai_stream_js_1 = require("./genai-stream.js");
|
|
12
13
|
const obj = (v) => (v && typeof v === 'object' ? v : {});
|
|
14
|
+
exports.obj = obj;
|
|
13
15
|
const s = (v) => (typeof v === 'string' ? v : '');
|
|
14
|
-
|
|
16
|
+
exports.s = s;
|
|
17
|
+
function start(name, attrs, parent, startTime) {
|
|
15
18
|
const ctx = parent ? api_1.trace.setSpan(api_1.context.active(), parent) : api_1.context.active();
|
|
16
19
|
const clean = Object.fromEntries(Object.entries(attrs).filter(([, v]) => v !== undefined && v !== ''));
|
|
17
|
-
return api_1.trace.getTracer('watchtower').startSpan(name, { kind: api_1.SpanKind.INTERNAL, attributes: clean }, ctx);
|
|
20
|
+
return api_1.trace.getTracer('watchtower').startSpan(name, { kind: api_1.SpanKind.INTERNAL, attributes: clean, ...(startTime !== undefined ? { startTime } : {}) }, ctx);
|
|
18
21
|
}
|
|
19
22
|
/** instrumentLlamaIndex(Settings) (from `llamaindex`): llm-start/stream/end and tool call events as spans. */
|
|
20
23
|
function instrumentLlamaIndex(settings) {
|
|
21
24
|
const open = new Map(), t0 = new Map();
|
|
22
25
|
const cm = settings.callbackManager;
|
|
23
26
|
cm.on('llm-start', (e) => {
|
|
24
|
-
const id = s(obj(e.detail).id);
|
|
27
|
+
const id = (0, exports.s)((0, exports.obj)(e.detail).id);
|
|
25
28
|
open.set(id, start('chat', { 'gen_ai.operation.name': 'chat', 'gen_ai.system': 'llama_index' }));
|
|
26
29
|
t0.set(id, Date.now());
|
|
27
30
|
});
|
|
28
31
|
cm.on('llm-stream', (e) => {
|
|
29
|
-
const id = s(obj(e.detail).id), at = t0.get(id);
|
|
32
|
+
const id = (0, exports.s)((0, exports.obj)(e.detail).id), at = t0.get(id);
|
|
30
33
|
if (at !== undefined) {
|
|
31
34
|
t0.delete(id);
|
|
32
35
|
open.get(id)?.setAttribute('gen_ai.response.time_to_first_chunk', (Date.now() - at) / 1000);
|
|
33
36
|
}
|
|
34
37
|
});
|
|
35
38
|
cm.on('llm-end', (e) => {
|
|
36
|
-
const d = obj(e.detail), id = s(d.id), span = open.get(id);
|
|
39
|
+
const d = (0, exports.obj)(e.detail), id = (0, exports.s)(d.id), span = open.get(id);
|
|
37
40
|
if (!span)
|
|
38
41
|
return;
|
|
39
42
|
open.delete(id);
|
|
40
43
|
t0.delete(id);
|
|
41
|
-
const res = obj(d.response);
|
|
44
|
+
const res = (0, exports.obj)(d.response);
|
|
42
45
|
const x = (0, genai_stream_js_1.extract)(res.raw);
|
|
43
|
-
const msg = obj(res.message), opts = obj(msg.options);
|
|
46
|
+
const msg = (0, exports.obj)(res.message), opts = (0, exports.obj)(msg.options);
|
|
44
47
|
for (const tc of Array.isArray(opts.toolCall) ? opts.toolCall : []) {
|
|
45
|
-
const name = s(obj(tc).name);
|
|
48
|
+
const name = (0, exports.s)((0, exports.obj)(tc).name);
|
|
46
49
|
if (name)
|
|
47
|
-
x.tools.push([name, s(obj(tc).id) || undefined]);
|
|
50
|
+
x.tools.push([name, (0, exports.s)((0, exports.obj)(tc).id) || undefined]);
|
|
48
51
|
}
|
|
49
52
|
if (x.model)
|
|
50
53
|
span.updateName(`chat ${x.model}`);
|
|
@@ -52,7 +55,7 @@ function instrumentLlamaIndex(settings) {
|
|
|
52
55
|
span.end();
|
|
53
56
|
});
|
|
54
57
|
cm.on('llm-tool-call', (e) => {
|
|
55
|
-
const name = s(obj(obj(e.detail).toolCall).name);
|
|
58
|
+
const name = (0, exports.s)((0, exports.obj)((0, exports.obj)(e.detail).toolCall).name);
|
|
56
59
|
start(`execute_tool ${name}`.trim(), { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': name }).end();
|
|
57
60
|
});
|
|
58
61
|
return { open };
|
|
@@ -63,27 +66,27 @@ class AgentsProcessor {
|
|
|
63
66
|
async onTraceStart() { }
|
|
64
67
|
async onTraceEnd() { }
|
|
65
68
|
async onSpanStart(sp) {
|
|
66
|
-
const d = obj(sp.spanData), type = s(d.type), parent = sp.parentId ? this.open.get(sp.parentId) : undefined;
|
|
69
|
+
const d = (0, exports.obj)(sp.spanData), type = (0, exports.s)(d.type), parent = sp.parentId ? this.open.get(sp.parentId) : undefined;
|
|
67
70
|
let name = type || 'agents';
|
|
68
71
|
let attrs = {};
|
|
69
72
|
if (type === 'agent') {
|
|
70
|
-
name = `invoke_agent ${s(d.name)}`.trim();
|
|
71
|
-
attrs = { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': s(d.name), 'gen_ai.system': 'openai' };
|
|
73
|
+
name = `invoke_agent ${(0, exports.s)(d.name)}`.trim();
|
|
74
|
+
attrs = { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': (0, exports.s)(d.name), 'gen_ai.system': 'openai' };
|
|
72
75
|
}
|
|
73
76
|
else if (type === 'generation' || type === 'response') {
|
|
74
|
-
name = `chat ${s(d.model)}`.trim();
|
|
75
|
-
attrs = { 'gen_ai.operation.name': 'chat', 'gen_ai.system': 'openai', 'gen_ai.request.model': s(d.model) };
|
|
77
|
+
name = `chat ${(0, exports.s)(d.model)}`.trim();
|
|
78
|
+
attrs = { 'gen_ai.operation.name': 'chat', 'gen_ai.system': 'openai', 'gen_ai.request.model': (0, exports.s)(d.model) };
|
|
76
79
|
}
|
|
77
80
|
else if (type === 'function') {
|
|
78
|
-
name = `execute_tool ${s(d.name)}`.trim();
|
|
79
|
-
attrs = { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': s(d.name) };
|
|
81
|
+
name = `execute_tool ${(0, exports.s)(d.name)}`.trim();
|
|
82
|
+
attrs = { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': (0, exports.s)(d.name) };
|
|
80
83
|
}
|
|
81
84
|
else if (type === 'handoff') {
|
|
82
|
-
attrs = { 'gen_ai.operation.name': 'handoff', 'gen_ai.handoff.from_agent': s(d.from_agent), 'gen_ai.handoff.to_agent': s(d.to_agent) };
|
|
85
|
+
attrs = { 'gen_ai.operation.name': 'handoff', 'gen_ai.handoff.from_agent': (0, exports.s)(d.from_agent), 'gen_ai.handoff.to_agent': (0, exports.s)(d.to_agent) };
|
|
83
86
|
}
|
|
84
87
|
else if (type === 'guardrail') {
|
|
85
|
-
name = `guardrail ${s(d.name)}`.trim();
|
|
86
|
-
attrs = { 'gen_ai.guardrail.name': s(d.name) };
|
|
88
|
+
name = `guardrail ${(0, exports.s)(d.name)}`.trim();
|
|
89
|
+
attrs = { 'gen_ai.guardrail.name': (0, exports.s)(d.name) };
|
|
87
90
|
}
|
|
88
91
|
if (sp.spanId)
|
|
89
92
|
this.open.set(sp.spanId, start(name, attrs, parent));
|
|
@@ -93,10 +96,10 @@ class AgentsProcessor {
|
|
|
93
96
|
if (!span || !sp.spanId)
|
|
94
97
|
return;
|
|
95
98
|
this.open.delete(sp.spanId);
|
|
96
|
-
const d = obj(sp.spanData);
|
|
99
|
+
const d = (0, exports.obj)(sp.spanData);
|
|
97
100
|
if (d.type === 'generation') {
|
|
98
|
-
const u = obj(d.usage);
|
|
99
|
-
(0, genai_stream_js_1.applyExtract)(span, { model: s(d.model) || undefined, input: u.input_tokens, output: u.output_tokens, reasons: [], tools: [] });
|
|
101
|
+
const u = (0, exports.obj)(d.usage);
|
|
102
|
+
(0, genai_stream_js_1.applyExtract)(span, { model: (0, exports.s)(d.model) || undefined, input: u.input_tokens, output: u.output_tokens, reasons: [], tools: [] });
|
|
100
103
|
}
|
|
101
104
|
else if (d.type === 'response') {
|
|
102
105
|
(0, genai_stream_js_1.applyExtract)(span, (0, genai_stream_js_1.extract)(d._response ?? d.response));
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Span } from '@opentelemetry/api';
|
|
2
|
+
type Fn = (...a: unknown[]) => unknown;
|
|
3
|
+
/**
|
|
4
|
+
* langchainCallbackHandler(): pass it as `callbacks: [handler]` to a LangChain.js model, chain or LangGraph.js graph
|
|
5
|
+
* (`graph.invoke(input, { callbacks: [handler] })`). LangGraph nodes (chains whose metadata names `langgraph_node`)
|
|
6
|
+
* and the graph itself become `invoke_agent` spans, tools `execute_tool`, model calls `chat`, nested as they run;
|
|
7
|
+
* plain LCEL chains get no span. Returns a plain handler object (LangChain wraps it) with the open spans for tests.
|
|
8
|
+
*/
|
|
9
|
+
export declare function langchainCallbackHandler(): Record<string, unknown> & {
|
|
10
|
+
open: Map<string, Span>;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* instrumentVercelAI({ generateText, streamText }) with the functions from `ai`: returns wrapped copies (ES module
|
|
14
|
+
* exports cannot be patched). Pass `agentName` to name the run (default: the `experimental_telemetry.functionId`, else `agent`).
|
|
15
|
+
* const { generateText } = instrumentVercelAI({ generateText: ai.generateText });
|
|
16
|
+
* A multi-step loop (`maxSteps` / `stopWhen`) gives one `invoke_agent` span with a `chat` span per step and an
|
|
17
|
+
* `execute_tool` span per tool call.
|
|
18
|
+
*/
|
|
19
|
+
export declare function instrumentVercelAI<T extends {
|
|
20
|
+
generateText?: Fn;
|
|
21
|
+
streamText?: Fn;
|
|
22
|
+
}>(ai: T, agentName?: string): T;
|
|
23
|
+
/** instrumentMastra(agent): wraps `agent.generate` and `agent.stream` of a Mastra `Agent`; the run is named after the agent. Returns the agent. */
|
|
24
|
+
export declare function instrumentMastra<T>(agent: T): T;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.langchainCallbackHandler = langchainCallbackHandler;
|
|
4
|
+
exports.instrumentVercelAI = instrumentVercelAI;
|
|
5
|
+
exports.instrumentMastra = instrumentMastra;
|
|
6
|
+
// GenAI spans for the TypeScript agent frameworks: LangGraph.js (a LangChain.js callback handler), the Vercel AI SDK
|
|
7
|
+
// agent loop (generateText / streamText with several steps) and Mastra agents. Same shape as the Python
|
|
8
|
+
// instrumentors and `genai-agents.ts`: `invoke_agent` / `chat` / `execute_tool` spans, nested as the run nests,
|
|
9
|
+
// never any prompt, completion or tool argument text. CrewAI has no JavaScript port, so there is no CrewAI hook here.
|
|
10
|
+
// Nothing is imported from the frameworks: each function takes their object.
|
|
11
|
+
const api_1 = require("@opentelemetry/api");
|
|
12
|
+
const genai_agents_js_1 = require("./genai-agents.js");
|
|
13
|
+
const num = (v) => (typeof v === 'number' ? v : undefined);
|
|
14
|
+
const thenable = (v) => !!v && typeof v.then === 'function';
|
|
15
|
+
function fail(span, e) {
|
|
16
|
+
span.recordException(e);
|
|
17
|
+
span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: e?.message });
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* langchainCallbackHandler(): pass it as `callbacks: [handler]` to a LangChain.js model, chain or LangGraph.js graph
|
|
21
|
+
* (`graph.invoke(input, { callbacks: [handler] })`). LangGraph nodes (chains whose metadata names `langgraph_node`)
|
|
22
|
+
* and the graph itself become `invoke_agent` spans, tools `execute_tool`, model calls `chat`, nested as they run;
|
|
23
|
+
* plain LCEL chains get no span. Returns a plain handler object (LangChain wraps it) with the open spans for tests.
|
|
24
|
+
*/
|
|
25
|
+
function langchainCallbackHandler() {
|
|
26
|
+
const open = new Map(), up = new Map();
|
|
27
|
+
const begin = (runId, parentId, name, attrs) => {
|
|
28
|
+
up.set(runId, parentId);
|
|
29
|
+
let p = parentId;
|
|
30
|
+
while (p !== undefined && !open.has(p))
|
|
31
|
+
p = up.get(p); // a parent without a span: skip to its own parent
|
|
32
|
+
open.set(runId, (0, genai_agents_js_1.start)(name, attrs, p === undefined ? undefined : open.get(p)));
|
|
33
|
+
};
|
|
34
|
+
const close = (runId, error) => {
|
|
35
|
+
up.delete(runId);
|
|
36
|
+
const span = open.get(runId);
|
|
37
|
+
open.delete(runId);
|
|
38
|
+
if (span && error !== undefined)
|
|
39
|
+
fail(span, error);
|
|
40
|
+
return span;
|
|
41
|
+
};
|
|
42
|
+
const llmStart = (extra, llm) => (runId, parentId) => {
|
|
43
|
+
const p = (0, genai_agents_js_1.obj)((0, genai_agents_js_1.obj)(extra).invocation_params), k = (0, genai_agents_js_1.obj)((0, genai_agents_js_1.obj)(llm).kwargs);
|
|
44
|
+
const model = (0, genai_agents_js_1.s)(p.model) || (0, genai_agents_js_1.s)(p.model_name) || (0, genai_agents_js_1.s)(k.model) || (0, genai_agents_js_1.s)(k.modelName);
|
|
45
|
+
begin(runId, parentId, `chat ${model}`.trim(), { 'gen_ai.operation.name': 'chat', 'gen_ai.system': 'langchain', 'gen_ai.request.model': model });
|
|
46
|
+
};
|
|
47
|
+
const ender = (runId, error) => { close(runId, error)?.end(); };
|
|
48
|
+
const h = {
|
|
49
|
+
open,
|
|
50
|
+
handleChatModelStart: (llm, _m, runId, parentId, extra) => llmStart(extra, llm)(runId, parentId),
|
|
51
|
+
handleLLMStart: (llm, _p, runId, parentId, extra) => llmStart(extra, llm)(runId, parentId),
|
|
52
|
+
handleLLMEnd: (output, runId) => {
|
|
53
|
+
const span = close(runId);
|
|
54
|
+
if (!span)
|
|
55
|
+
return;
|
|
56
|
+
const o = (0, genai_agents_js_1.obj)(output), tu = (0, genai_agents_js_1.obj)((0, genai_agents_js_1.obj)(o.llmOutput).tokenUsage);
|
|
57
|
+
const first = Array.isArray(o.generations) && Array.isArray(o.generations[0]) ? (0, genai_agents_js_1.obj)(o.generations[0][0]) : {};
|
|
58
|
+
const msg = (0, genai_agents_js_1.obj)(first.message), um = (0, genai_agents_js_1.obj)(msg.usage_metadata), rm = (0, genai_agents_js_1.obj)(msg.response_metadata);
|
|
59
|
+
const input = num(tu.promptTokens) ?? num(um.input_tokens), out = num(tu.completionTokens) ?? num(um.output_tokens);
|
|
60
|
+
if (input !== undefined)
|
|
61
|
+
span.setAttribute('gen_ai.usage.input_tokens', input);
|
|
62
|
+
if (out !== undefined)
|
|
63
|
+
span.setAttribute('gen_ai.usage.output_tokens', out);
|
|
64
|
+
if ((0, genai_agents_js_1.s)(rm.model_name))
|
|
65
|
+
span.setAttribute('gen_ai.response.model', (0, genai_agents_js_1.s)(rm.model_name));
|
|
66
|
+
if ((0, genai_agents_js_1.s)(rm.finish_reason))
|
|
67
|
+
span.setAttribute('gen_ai.response.finish_reasons', [(0, genai_agents_js_1.s)(rm.finish_reason)]);
|
|
68
|
+
span.end();
|
|
69
|
+
},
|
|
70
|
+
handleLLMError: (e, runId) => ender(runId, e),
|
|
71
|
+
handleChainStart: (_c, _i, runId, parentId, _t, metadata, _rt, runName) => {
|
|
72
|
+
const m = (0, genai_agents_js_1.obj)(metadata), node = (0, genai_agents_js_1.s)(m.langgraph_node);
|
|
73
|
+
// only LangGraph runs get spans (the graph root and its nodes); plain LCEL chains are noise
|
|
74
|
+
if (!node && !(parentId === undefined && m.langgraph_step !== undefined)) {
|
|
75
|
+
up.set(runId, parentId);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const who = node && runName === node ? node : runName || node || 'graph';
|
|
79
|
+
begin(runId, parentId, `invoke_agent ${who}`, { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': who, 'gen_ai.system': 'langgraph' });
|
|
80
|
+
},
|
|
81
|
+
handleChainEnd: (_o, runId) => ender(runId),
|
|
82
|
+
handleChainError: (e, runId) => ender(runId, e),
|
|
83
|
+
handleToolStart: (tool, _i, runId, parentId, _t, _m, runName) => {
|
|
84
|
+
const name = runName || (0, genai_agents_js_1.s)((0, genai_agents_js_1.obj)(tool).name) || (0, genai_agents_js_1.s)((0, genai_agents_js_1.obj)((0, genai_agents_js_1.obj)(tool).kwargs).name);
|
|
85
|
+
begin(runId, parentId, `execute_tool ${name}`.trim(), { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': name });
|
|
86
|
+
},
|
|
87
|
+
handleToolEnd: (_o, runId) => ender(runId),
|
|
88
|
+
handleToolError: (e, runId) => ender(runId, e),
|
|
89
|
+
};
|
|
90
|
+
return h;
|
|
91
|
+
}
|
|
92
|
+
/** Wraps every `execute` of an AI SDK / Mastra tool set so each call is an `execute_tool` span under the agent run. */
|
|
93
|
+
function wrapTools(tools, root) {
|
|
94
|
+
const out = {};
|
|
95
|
+
for (const [name, t] of Object.entries((0, genai_agents_js_1.obj)(tools))) {
|
|
96
|
+
const tool = (0, genai_agents_js_1.obj)(t), exec = tool.execute;
|
|
97
|
+
if (typeof exec !== 'function') {
|
|
98
|
+
out[name] = t;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
out[name] = {
|
|
102
|
+
...tool,
|
|
103
|
+
execute: (...a) => {
|
|
104
|
+
const sp = (0, genai_agents_js_1.start)(`execute_tool ${name}`, { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': name }, root);
|
|
105
|
+
const done = (e) => { if (e !== undefined)
|
|
106
|
+
fail(sp, e); sp.end(); };
|
|
107
|
+
try {
|
|
108
|
+
const r = exec.apply(tool, a);
|
|
109
|
+
if (thenable(r))
|
|
110
|
+
r.then(() => done(), (e) => done(e ?? new Error('tool failed')));
|
|
111
|
+
else
|
|
112
|
+
done();
|
|
113
|
+
return r;
|
|
114
|
+
}
|
|
115
|
+
catch (e) {
|
|
116
|
+
done(e);
|
|
117
|
+
throw e;
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* One agent run as an `invoke_agent` span. `onStepFinish` (injected, the caller's own still runs) turns every model
|
|
126
|
+
* step into a `chat` span with usage, timed from the previous step's end; tool `execute` calls become
|
|
127
|
+
* `execute_tool` spans. `optsAt` is the position of the options argument. A stream ends the run in `onFinish` /
|
|
128
|
+
* `onError`; a promise ends it when it settles.
|
|
129
|
+
*/
|
|
130
|
+
function agentRun(system, name, orig, self, args, optsAt, stream) {
|
|
131
|
+
const root = (0, genai_agents_js_1.start)(`invoke_agent ${name}`.trim(), { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': name, 'gen_ai.system': system });
|
|
132
|
+
let ended = false, last = Date.now();
|
|
133
|
+
const end = (e) => { if (ended)
|
|
134
|
+
return; ended = true; if (e !== undefined)
|
|
135
|
+
fail(root, e); root.end(); };
|
|
136
|
+
const opts = { ...(0, genai_agents_js_1.obj)(args[optsAt]) };
|
|
137
|
+
const onStep = opts.onStepFinish, onFinish = opts.onFinish, onError = opts.onError;
|
|
138
|
+
opts.onStepFinish = (e) => {
|
|
139
|
+
const d = (0, genai_agents_js_1.obj)(e), u = (0, genai_agents_js_1.obj)(d.usage), r = (0, genai_agents_js_1.obj)(d.response);
|
|
140
|
+
const model = (0, genai_agents_js_1.s)(r.modelId) || (0, genai_agents_js_1.s)(r.model) || (0, genai_agents_js_1.s)(d.model);
|
|
141
|
+
const sp = (0, genai_agents_js_1.start)(`chat ${model}`.trim(), { 'gen_ai.operation.name': 'chat', 'gen_ai.system': system, 'gen_ai.response.model': model }, root, last);
|
|
142
|
+
const input = num(u.inputTokens) ?? num(u.promptTokens), out = num(u.outputTokens) ?? num(u.completionTokens);
|
|
143
|
+
if (input !== undefined)
|
|
144
|
+
sp.setAttribute('gen_ai.usage.input_tokens', input);
|
|
145
|
+
if (out !== undefined)
|
|
146
|
+
sp.setAttribute('gen_ai.usage.output_tokens', out);
|
|
147
|
+
if ((0, genai_agents_js_1.s)(d.finishReason))
|
|
148
|
+
sp.setAttribute('gen_ai.response.finish_reasons', [(0, genai_agents_js_1.s)(d.finishReason)]);
|
|
149
|
+
sp.end();
|
|
150
|
+
last = Date.now();
|
|
151
|
+
return onStep?.(e);
|
|
152
|
+
};
|
|
153
|
+
if (stream) {
|
|
154
|
+
opts.onFinish = (e) => { end(); return onFinish?.(e); };
|
|
155
|
+
opts.onError = (e) => { end((0, genai_agents_js_1.obj)(e).error ?? e ?? new Error('stream failed')); return onError?.(e); };
|
|
156
|
+
}
|
|
157
|
+
if (opts.tools)
|
|
158
|
+
opts.tools = wrapTools(opts.tools, root);
|
|
159
|
+
const a = [...args];
|
|
160
|
+
a[optsAt] = opts;
|
|
161
|
+
let res;
|
|
162
|
+
try {
|
|
163
|
+
res = api_1.context.with(api_1.trace.setSpan(api_1.context.active(), root), () => orig.apply(self, a));
|
|
164
|
+
}
|
|
165
|
+
catch (e) {
|
|
166
|
+
end(e);
|
|
167
|
+
throw e;
|
|
168
|
+
}
|
|
169
|
+
if (!stream) {
|
|
170
|
+
// side branch only: the caller keeps the framework's own promise
|
|
171
|
+
if (thenable(res))
|
|
172
|
+
res.then(() => end(), (e) => end(e ?? new Error('run failed')));
|
|
173
|
+
else
|
|
174
|
+
end();
|
|
175
|
+
}
|
|
176
|
+
return res;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* instrumentVercelAI({ generateText, streamText }) with the functions from `ai`: returns wrapped copies (ES module
|
|
180
|
+
* exports cannot be patched). Pass `agentName` to name the run (default: the `experimental_telemetry.functionId`, else `agent`).
|
|
181
|
+
* const { generateText } = instrumentVercelAI({ generateText: ai.generateText });
|
|
182
|
+
* A multi-step loop (`maxSteps` / `stopWhen`) gives one `invoke_agent` span with a `chat` span per step and an
|
|
183
|
+
* `execute_tool` span per tool call.
|
|
184
|
+
*/
|
|
185
|
+
function instrumentVercelAI(ai, agentName) {
|
|
186
|
+
const out = { ...ai };
|
|
187
|
+
const nameOf = (a) => agentName || (0, genai_agents_js_1.s)((0, genai_agents_js_1.obj)((0, genai_agents_js_1.obj)(a[0]).experimental_telemetry).functionId) || 'agent';
|
|
188
|
+
if (typeof ai.generateText === 'function') {
|
|
189
|
+
const f = ai.generateText;
|
|
190
|
+
out.generateText = function (...a) { return agentRun('vercel_ai', nameOf(a), f, this, a, 0, false); };
|
|
191
|
+
}
|
|
192
|
+
if (typeof ai.streamText === 'function') {
|
|
193
|
+
const f = ai.streamText;
|
|
194
|
+
out.streamText = function (...a) { return agentRun('vercel_ai', nameOf(a), f, this, a, 0, true); };
|
|
195
|
+
}
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
/** instrumentMastra(agent): wraps `agent.generate` and `agent.stream` of a Mastra `Agent`; the run is named after the agent. Returns the agent. */
|
|
199
|
+
function instrumentMastra(agent) {
|
|
200
|
+
const a = agent;
|
|
201
|
+
const name = (0, genai_agents_js_1.s)(a.name) || 'agent';
|
|
202
|
+
for (const [method, stream] of [['generate', false], ['stream', true]]) {
|
|
203
|
+
const f = a[method];
|
|
204
|
+
if (typeof f !== 'function' || f.__wt)
|
|
205
|
+
continue;
|
|
206
|
+
const wrapped = function (...args) { return agentRun('mastra', name, f, this, args, 1, stream); };
|
|
207
|
+
wrapped.__wt = true;
|
|
208
|
+
a[method] = wrapped;
|
|
209
|
+
}
|
|
210
|
+
return agent;
|
|
211
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { instrumentLlamaIndex, instrumentOpenAIAgents } from './genai-agents.js';
|
|
2
|
+
export { instrumentMastra, instrumentVercelAI, langchainCallbackHandler } from './genai-frameworks.js';
|
|
2
3
|
/**
|
|
3
4
|
* instrumentOpenAI(new OpenAI()): chat.completions.create and responses.create. Returns the client.
|
|
4
5
|
* For an OpenAI-compatible gateway pass its name: instrumentOpenAI(new OpenAI({ baseURL: litellmUrl }), 'litellm').
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.instrumentOpenAIAgents = exports.instrumentLlamaIndex = void 0;
|
|
3
|
+
exports.langchainCallbackHandler = exports.instrumentVercelAI = exports.instrumentMastra = exports.instrumentOpenAIAgents = exports.instrumentLlamaIndex = void 0;
|
|
4
4
|
exports.instrumentOpenAI = instrumentOpenAI;
|
|
5
5
|
exports.instrumentBedrock = instrumentBedrock;
|
|
6
6
|
exports.instrumentGoogleGenAI = instrumentGoogleGenAI;
|
|
@@ -9,7 +9,8 @@ exports.instrumentMistral = instrumentMistral;
|
|
|
9
9
|
exports.instrumentOllama = instrumentOllama;
|
|
10
10
|
exports.vercelAiTelemetry = vercelAiTelemetry;
|
|
11
11
|
// GenAI spans (OTel GenAI semconv) for the openai, anthropic, AWS Bedrock, Google GenAI, Mistral and Ollama SDKs (and
|
|
12
|
-
// LiteLLM through its OpenAI-compatible proxy), LlamaIndex and the OpenAI Agents SDK (genai-agents.ts),
|
|
12
|
+
// LiteLLM through its OpenAI-compatible proxy), LlamaIndex and the OpenAI Agents SDK (genai-agents.ts), LangGraph.js,
|
|
13
|
+
// Mastra and the Vercel AI SDK agent loop (genai-frameworks.ts), and a
|
|
13
14
|
// telemetry option for the Vercel AI SDK. Streams record time to first chunk, usage and tool calls (genai-stream.ts).
|
|
14
15
|
// Prompt and completion text is never recorded.
|
|
15
16
|
const api_1 = require("@opentelemetry/api");
|
|
@@ -17,6 +18,10 @@ const genai_stream_js_1 = require("./genai-stream.js");
|
|
|
17
18
|
var genai_agents_js_1 = require("./genai-agents.js");
|
|
18
19
|
Object.defineProperty(exports, "instrumentLlamaIndex", { enumerable: true, get: function () { return genai_agents_js_1.instrumentLlamaIndex; } });
|
|
19
20
|
Object.defineProperty(exports, "instrumentOpenAIAgents", { enumerable: true, get: function () { return genai_agents_js_1.instrumentOpenAIAgents; } });
|
|
21
|
+
var genai_frameworks_js_1 = require("./genai-frameworks.js");
|
|
22
|
+
Object.defineProperty(exports, "instrumentMastra", { enumerable: true, get: function () { return genai_frameworks_js_1.instrumentMastra; } });
|
|
23
|
+
Object.defineProperty(exports, "instrumentVercelAI", { enumerable: true, get: function () { return genai_frameworks_js_1.instrumentVercelAI; } });
|
|
24
|
+
Object.defineProperty(exports, "langchainCallbackHandler", { enumerable: true, get: function () { return genai_frameworks_js_1.langchainCallbackHandler; } });
|
|
20
25
|
const DONE = Symbol('wt.instrumented');
|
|
21
26
|
const plain = (b) => (b || {});
|
|
22
27
|
function wrap(target, method, system, req = plain) {
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import * as wt from '../index.js';
|
|
2
|
+
/** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
|
|
3
|
+
export declare function makeRegister(options?: wt.InitOptions): () => Promise<void>;
|
|
1
4
|
/** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
|
|
2
|
-
export declare
|
|
5
|
+
export declare const register: () => Promise<void>;
|
|
3
6
|
/** Next.js onRequestError: server render, route handler and server action errors. */
|
|
4
7
|
export declare function onRequestError(err: unknown, request?: {
|
|
5
8
|
path?: string;
|
|
@@ -33,17 +33,23 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.register =
|
|
36
|
+
exports.register = void 0;
|
|
37
|
+
exports.makeRegister = makeRegister;
|
|
37
38
|
exports.onRequestError = onRequestError;
|
|
38
39
|
// instrumentation.js: module.exports = require('@watchtowerobservability/node/next');
|
|
40
|
+
// or, with options: export const register = makeRegister({ redact }); export { onRequestError } from '@watchtowerobservability/node/next';
|
|
39
41
|
const wt = __importStar(require("../index.js"));
|
|
40
|
-
/** Next.js instrumentation
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
42
|
+
/** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
|
|
43
|
+
function makeRegister(options = {}) {
|
|
44
|
+
return async function register() {
|
|
45
|
+
const rt = process.env.NEXT_RUNTIME;
|
|
46
|
+
if ((rt && rt !== 'nodejs') || !(options.apiKey || process.env.WT_INGEST_KEY))
|
|
47
|
+
return;
|
|
48
|
+
wt.init(options);
|
|
49
|
+
};
|
|
46
50
|
}
|
|
51
|
+
/** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
|
|
52
|
+
exports.register = makeRegister();
|
|
47
53
|
/** Next.js onRequestError: server render, route handler and server action errors. */
|
|
48
54
|
async function onRequestError(err, request, context) {
|
|
49
55
|
const c = context || {};
|
package/dist/cjs/load.d.ts
CHANGED
package/dist/cjs/load.js
CHANGED
|
@@ -1,11 +1,60 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.load = load;
|
|
4
|
-
|
|
5
|
-
//
|
|
4
|
+
exports.need = need;
|
|
5
|
+
// Optional-peer loader. Each peer is required by a LITERAL name inside a try block so bundlers (webpack, esbuild, Next's
|
|
6
|
+
// file tracer) can follow it; a computed `require(name)` is invisible to them. This is the CommonJS form;
|
|
7
|
+
// scripts/build.mjs prepends `const require = createRequire(import.meta.url)` for dist/esm (webpack follows that too).
|
|
8
|
+
// The cwd fallback only matters when `require` does not exist (test runners running the TS source as ESM).
|
|
6
9
|
const node_module_1 = require("node:module");
|
|
10
|
+
const NONE = Symbol('not a known peer');
|
|
11
|
+
function known(id) {
|
|
12
|
+
try { // bundlers only tolerate an optional require that is lexically inside try
|
|
13
|
+
switch (id) {
|
|
14
|
+
case '@opentelemetry/context-async-hooks': return require('@opentelemetry/context-async-hooks');
|
|
15
|
+
case '@opentelemetry/core': return require('@opentelemetry/core');
|
|
16
|
+
case '@opentelemetry/exporter-logs-otlp-http': return require('@opentelemetry/exporter-logs-otlp-http');
|
|
17
|
+
case '@opentelemetry/exporter-metrics-otlp-http': return require('@opentelemetry/exporter-metrics-otlp-http');
|
|
18
|
+
case '@opentelemetry/exporter-trace-otlp-http': return require('@opentelemetry/exporter-trace-otlp-http');
|
|
19
|
+
case '@opentelemetry/otlp-transformer': return require('@opentelemetry/otlp-transformer');
|
|
20
|
+
case '@opentelemetry/resources': return require('@opentelemetry/resources');
|
|
21
|
+
case '@opentelemetry/sdk-logs': return require('@opentelemetry/sdk-logs');
|
|
22
|
+
case '@opentelemetry/sdk-metrics': return require('@opentelemetry/sdk-metrics');
|
|
23
|
+
case '@opentelemetry/sdk-trace': return require('@opentelemetry/sdk-trace');
|
|
24
|
+
case '@opentelemetry/instrumentation-runtime-node': return require('@opentelemetry/instrumentation-runtime-node');
|
|
25
|
+
case '@opentelemetry/instrumentation': return require('@opentelemetry/instrumentation');
|
|
26
|
+
case '@opentelemetry/instrumentation-http': return require('@opentelemetry/instrumentation-http');
|
|
27
|
+
case '@opentelemetry/instrumentation-undici': return require('@opentelemetry/instrumentation-undici');
|
|
28
|
+
case '@opentelemetry/instrumentation-pg': return require('@opentelemetry/instrumentation-pg');
|
|
29
|
+
case '@opentelemetry/instrumentation-ioredis': return require('@opentelemetry/instrumentation-ioredis');
|
|
30
|
+
case 'winston-transport': return require('winston-transport');
|
|
31
|
+
default: return NONE;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch (e) {
|
|
35
|
+
throw e;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
7
38
|
function load(id) {
|
|
8
|
-
if (typeof require
|
|
9
|
-
return
|
|
10
|
-
|
|
39
|
+
if (typeof require !== 'function')
|
|
40
|
+
return (0, node_module_1.createRequire)(`${process.cwd()}/`)(id);
|
|
41
|
+
const m = known(id);
|
|
42
|
+
return m === NONE ? require(id) : m;
|
|
43
|
+
}
|
|
44
|
+
const SDK_PEERS = [
|
|
45
|
+
'@opentelemetry/context-async-hooks', '@opentelemetry/core', '@opentelemetry/exporter-logs-otlp-http',
|
|
46
|
+
'@opentelemetry/exporter-metrics-otlp-http', '@opentelemetry/exporter-trace-otlp-http', '@opentelemetry/otlp-transformer',
|
|
47
|
+
'@opentelemetry/resources', '@opentelemetry/sdk-logs', '@opentelemetry/sdk-metrics', '@opentelemetry/sdk-trace',
|
|
48
|
+
];
|
|
49
|
+
/** Load an OpenTelemetry SDK package (an optional peer); a missing one throws an error naming what to install. */
|
|
50
|
+
function need(id) {
|
|
51
|
+
try {
|
|
52
|
+
return load(id);
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
if (e?.code === 'MODULE_NOT_FOUND' && String(e.message).includes(id)) {
|
|
56
|
+
throw new Error(`@watchtowerobservability/node needs the OpenTelemetry SDK, which is not installed (missing ${id}). Run: npm install ${SDK_PEERS.join(' ')}`);
|
|
57
|
+
}
|
|
58
|
+
throw e;
|
|
59
|
+
}
|
|
11
60
|
}
|
package/dist/cjs/metrics.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { Resource } from '@opentelemetry/resources';
|
|
2
|
-
import { MeterProvider } from '@opentelemetry/sdk-metrics';
|
|
3
|
-
import type { PushMetricExporter } from '@opentelemetry/sdk-metrics';
|
|
2
|
+
import type { MeterProvider, PushMetricExporter } from '@opentelemetry/sdk-metrics';
|
|
4
3
|
/** Explicit flag, else `WATCHTOWER_LOGS` / `WATCHTOWER_METRICS` (default on); `OTEL_*_EXPORTER=none` turns it off. */
|
|
5
4
|
export declare function switchOn(name: string, otelExporterEnv: string, flag?: boolean): boolean;
|
|
6
5
|
export interface Metrics {
|
package/dist/cjs/metrics.js
CHANGED
|
@@ -40,8 +40,6 @@ exports.startMetrics = startMetrics;
|
|
|
40
40
|
// metrics (event loop delay and utilization, GC, heap) come from the optional peer
|
|
41
41
|
// @opentelemetry/instrumentation-runtime-node when it is installed.
|
|
42
42
|
const nodePath = __importStar(require("node:path"));
|
|
43
|
-
const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
|
|
44
|
-
const exporter_metrics_otlp_http_1 = require("@opentelemetry/exporter-metrics-otlp-http");
|
|
45
43
|
const buffer_js_1 = require("./buffer.js");
|
|
46
44
|
const load_js_1 = require("./load.js");
|
|
47
45
|
/** Explicit flag, else `WATCHTOWER_LOGS` / `WATCHTOWER_METRICS` (default on); `OTEL_*_EXPORTER=none` turns it off. */
|
|
@@ -54,20 +52,22 @@ function switchOn(name, otelExporterEnv, flag) {
|
|
|
54
52
|
return !['off', 'false', '0', 'no'].includes((env[name] || 'on').trim().toLowerCase());
|
|
55
53
|
}
|
|
56
54
|
function startMetrics(endpoint, headers, resource, bufferDir, fetch, exporter) {
|
|
55
|
+
const sdk = (0, load_js_1.need)('@opentelemetry/sdk-metrics');
|
|
57
56
|
const url = `${endpoint}/v1/metrics`;
|
|
58
57
|
let exp = exporter;
|
|
59
58
|
if (!exp) {
|
|
59
|
+
const { AggregationTemporalityPreference, OTLPMetricExporter } = (0, load_js_1.need)('@opentelemetry/exporter-metrics-otlp-http');
|
|
60
60
|
const delta = process.env.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE
|
|
61
|
-
? {} : { temporalityPreference:
|
|
62
|
-
exp = new
|
|
61
|
+
? {} : { temporalityPreference: AggregationTemporalityPreference.DELTA };
|
|
62
|
+
exp = new OTLPMetricExporter({ url, headers, ...delta });
|
|
63
63
|
if (bufferDir)
|
|
64
64
|
exp = new buffer_js_1.MetricSpool(exp, nodePath.join(bufferDir, 'metrics'), url, headers, fetch);
|
|
65
65
|
}
|
|
66
66
|
const interval = Number(process.env.OTEL_METRIC_EXPORT_INTERVAL) || 60000;
|
|
67
|
-
const reader = new
|
|
67
|
+
const reader = new sdk.PeriodicExportingMetricReader({
|
|
68
68
|
exporter: exp, exportIntervalMillis: interval, exportTimeoutMillis: Math.min(30000, interval),
|
|
69
69
|
});
|
|
70
|
-
const provider = new
|
|
70
|
+
const provider = new sdk.MeterProvider({ resource, readers: [reader] });
|
|
71
71
|
let runtime;
|
|
72
72
|
try {
|
|
73
73
|
const mod = (0, load_js_1.load)('@opentelemetry/instrumentation-runtime-node');
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SpanProcessor } from '@opentelemetry/sdk-trace';
|
|
2
|
+
export interface Frame {
|
|
3
|
+
file: string;
|
|
4
|
+
line: number;
|
|
5
|
+
fn?: string;
|
|
6
|
+
}
|
|
7
|
+
/** The first application frame of a V8 stack, or undefined. */
|
|
8
|
+
export declare function firstAppFrame(stack: string): Frame | undefined;
|
|
9
|
+
export declare function codeOrigin(): SpanProcessor;
|