@watchtowerobservability/node 0.5.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 +39 -8
- 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 +29 -9
- package/dist/cjs/index.js +87 -49
- 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.js +36 -5
- 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/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 +29 -9
- package/dist/esm/index.js +87 -50
- 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.js +78 -2
- 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 +33 -2
|
@@ -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.js
CHANGED
|
@@ -2,13 +2,44 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.load = load;
|
|
4
4
|
exports.need = need;
|
|
5
|
-
// Optional-peer loader
|
|
6
|
-
//
|
|
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).
|
|
7
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
|
+
}
|
|
8
38
|
function load(id) {
|
|
9
|
-
if (typeof require
|
|
10
|
-
return
|
|
11
|
-
|
|
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;
|
|
12
43
|
}
|
|
13
44
|
const SDK_PEERS = [
|
|
14
45
|
'@opentelemetry/context-async-hooks', '@opentelemetry/core', '@opentelemetry/exporter-logs-otlp-http',
|
|
@@ -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;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.firstAppFrame = firstAppFrame;
|
|
4
|
+
exports.codeOrigin = codeOrigin;
|
|
5
|
+
const FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):\d+\)?$/;
|
|
6
|
+
const SKIP = /node_modules|^node:|[\\/]watchtower[\\/](?:dist|src)[\\/]|@watchtowerobservability[\\/]node/;
|
|
7
|
+
/** The first application frame of a V8 stack, or undefined. */
|
|
8
|
+
function firstAppFrame(stack) {
|
|
9
|
+
for (const line of stack.split('\n').slice(1)) {
|
|
10
|
+
const m = FRAME.exec(line);
|
|
11
|
+
if (!m)
|
|
12
|
+
continue;
|
|
13
|
+
const file = m[2].replace(/^file:\/\//, '');
|
|
14
|
+
if (SKIP.test(file) || SKIP.test(line.trim().slice(3)))
|
|
15
|
+
continue;
|
|
16
|
+
return { file, line: Number(m[3]), fn: m[1] && m[1] !== '<anonymous>' ? m[1] : undefined };
|
|
17
|
+
}
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
function codeOrigin() {
|
|
21
|
+
return {
|
|
22
|
+
onStart(span) {
|
|
23
|
+
const s = span;
|
|
24
|
+
if (s.attributes?.['code.filepath'] !== undefined)
|
|
25
|
+
return;
|
|
26
|
+
const holder = {};
|
|
27
|
+
const prev = Error.stackTraceLimit;
|
|
28
|
+
Error.stackTraceLimit = 30;
|
|
29
|
+
Error.captureStackTrace(holder);
|
|
30
|
+
Error.stackTraceLimit = prev;
|
|
31
|
+
const f = firstAppFrame(holder.stack ?? '');
|
|
32
|
+
if (!f)
|
|
33
|
+
return;
|
|
34
|
+
s.setAttribute('code.filepath', f.file);
|
|
35
|
+
s.setAttribute('code.lineno', f.line);
|
|
36
|
+
if (f.fn)
|
|
37
|
+
s.setAttribute('code.function', f.fn);
|
|
38
|
+
},
|
|
39
|
+
onEnd() { },
|
|
40
|
+
shutdown: () => Promise.resolve(),
|
|
41
|
+
forceFlush: () => Promise.resolve(),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { SpanProcessor } from '@opentelemetry/sdk-trace';
|
|
2
|
+
export type RedactHook = (key: string, value: unknown) => unknown;
|
|
3
|
+
/** Hook keys for the non-attribute fields. Event attributes (incl. exception.message / exception.stacktrace) use their own keys. */
|
|
4
|
+
export declare const SPAN_NAME_KEY = "span.name";
|
|
5
|
+
export declare const STATUS_MESSAGE_KEY = "status.message";
|
|
6
|
+
export declare const LOG_BODY_KEY = "log.body";
|
|
7
|
+
/** Span processor that redacts the name, status message, attributes, every event's and link's attributes before export. */
|
|
8
|
+
export declare function redactor(hook: RedactHook): SpanProcessor;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LOG_BODY_KEY = exports.STATUS_MESSAGE_KEY = exports.SPAN_NAME_KEY = void 0;
|
|
4
|
+
exports.redactor = redactor;
|
|
5
|
+
/** Hook keys for the non-attribute fields. Event attributes (incl. exception.message / exception.stacktrace) use their own keys. */
|
|
6
|
+
exports.SPAN_NAME_KEY = 'span.name';
|
|
7
|
+
exports.STATUS_MESSAGE_KEY = 'status.message';
|
|
8
|
+
exports.LOG_BODY_KEY = 'log.body';
|
|
9
|
+
function attrs(a, hook) {
|
|
10
|
+
if (!a)
|
|
11
|
+
return;
|
|
12
|
+
for (const k of Object.keys(a))
|
|
13
|
+
a[k] = hook(k, a[k]);
|
|
14
|
+
}
|
|
15
|
+
/** Assign, falling back to defineProperty if the SDK exposes the field as a getter. */
|
|
16
|
+
function put(o, k, v) {
|
|
17
|
+
try {
|
|
18
|
+
o[k] = v;
|
|
19
|
+
}
|
|
20
|
+
catch { /* readonly accessor */ }
|
|
21
|
+
if (o[k] !== v)
|
|
22
|
+
Object.defineProperty(o, k, { value: v, configurable: true, enumerable: true, writable: true });
|
|
23
|
+
}
|
|
24
|
+
/** Span processor that redacts the name, status message, attributes, every event's and link's attributes before export. */
|
|
25
|
+
function redactor(hook) {
|
|
26
|
+
return {
|
|
27
|
+
onStart() { },
|
|
28
|
+
onEnd(span) {
|
|
29
|
+
// ReadableSpan fields are readonly in the types but are plain mutable fields on the SDK span
|
|
30
|
+
const s = span;
|
|
31
|
+
put(s, 'name', String(hook(exports.SPAN_NAME_KEY, s.name) ?? ''));
|
|
32
|
+
if (s.status?.message)
|
|
33
|
+
put(s.status, 'message', String(hook(exports.STATUS_MESSAGE_KEY, s.status.message) ?? ''));
|
|
34
|
+
attrs(span.attributes, hook);
|
|
35
|
+
for (const e of s.events || [])
|
|
36
|
+
attrs(e.attributes, hook);
|
|
37
|
+
for (const l of s.links || [])
|
|
38
|
+
attrs(l.attributes, hook);
|
|
39
|
+
},
|
|
40
|
+
shutdown: () => Promise.resolve(),
|
|
41
|
+
forceFlush: () => Promise.resolve(),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
// Preload entry: `node --import @watchtowerobservability/node/register app.mjs` (ESM) or `node -r @watchtowerobservability/node/register app.js` (CommonJS).
|
|
4
|
+
// Starts the SDK from WT_*/OTEL_* env before the app loads, so http, fetch, pg and ioredis are patched in time.
|
|
5
|
+
// No-op without WT_INGEST_KEY.
|
|
6
|
+
const node_url_1 = require("node:url");
|
|
7
|
+
const node_module_1 = require("node:module");
|
|
8
|
+
const index_js_1 = require("./index.js");
|
|
9
|
+
if (process.env.WT_INGEST_KEY || process.env.OTEL_EXPORTER_OTLP_HEADERS) {
|
|
10
|
+
try {
|
|
11
|
+
// ESM modules (node:http imported from an ES module) are only patched through OpenTelemetry's loader hook
|
|
12
|
+
// (import-in-the-middle). Resolve it from the app, once per process, and skip quietly when it is not installed.
|
|
13
|
+
const g = globalThis;
|
|
14
|
+
const key = Symbol.for('watchtower.node.esm-hook');
|
|
15
|
+
if (!g[key]) {
|
|
16
|
+
g[key] = true;
|
|
17
|
+
try {
|
|
18
|
+
(0, node_module_1.register)('@opentelemetry/instrumentation/hook.mjs', (0, node_url_1.pathToFileURL)(`${process.cwd()}/`));
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// @opentelemetry/instrumentation not installed: CommonJS apps are still instrumented
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
(0, index_js_1.init)({});
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
console.warn(`[watchtower] register: ${e.message}`);
|
|
28
|
+
}
|
|
29
|
+
}
|