@nestjs/observe 0.3.18 → 0.3.20

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.
Files changed (35) hide show
  1. package/README.md +2 -1
  2. package/dist/agent/credentials-notice.d.ts +39 -0
  3. package/dist/agent/credentials-notice.js +68 -0
  4. package/dist/agent/detached-observe-worker.assembly.js +2 -0
  5. package/dist/agent/detached-observe-worker.d.ts +5 -0
  6. package/dist/agent/detached-observe-worker.js +3 -0
  7. package/dist/agent/observe-agent.worker.js +17 -16
  8. package/dist/instrument/create-instance-decorator.instrument.js +35 -2
  9. package/dist/interfaces/observe-options.interface.d.ts +16 -1
  10. package/dist/observe.module.js +12 -0
  11. package/dist/outgoing/http.integration.js +4 -0
  12. package/dist/outgoing/llm/llm-fetch.integration.d.ts +56 -0
  13. package/dist/outgoing/llm/llm-fetch.integration.js +236 -0
  14. package/dist/outgoing/llm/llm-providers.d.ts +25 -0
  15. package/dist/outgoing/llm/llm-providers.js +96 -0
  16. package/dist/outgoing/llm/llm-usage.d.ts +67 -0
  17. package/dist/outgoing/llm/llm-usage.js +263 -0
  18. package/dist/outgoing/outgoing-observe-agent.service.d.ts +1 -0
  19. package/dist/outgoing/outgoing-observe-agent.service.js +12 -0
  20. package/dist/outgoing/outgoing-span.recorder.d.ts +9 -0
  21. package/dist/outgoing/outgoing-span.recorder.js +55 -6
  22. package/dist/protocols/deferred-trace-completion.d.ts +27 -0
  23. package/dist/protocols/deferred-trace-completion.js +91 -0
  24. package/dist/protocols/graphql-observe-agent.service.js +7 -12
  25. package/dist/protocols/http-observe-agent.service.d.ts +2 -2
  26. package/dist/protocols/http-observe-agent.service.js +22 -19
  27. package/dist/protocols/job-trace-runner.d.ts +3 -3
  28. package/dist/protocols/job-trace-runner.js +10 -20
  29. package/dist/protocols/rpc-observe-agent.service.js +15 -29
  30. package/dist/protocols/ws-observe-agent.service.js +6 -10
  31. package/dist/services/trace-sampler.service.d.ts +1 -0
  32. package/dist/services/trace-sampler.service.js +10 -4
  33. package/dist/utils/sdk-version.util.d.ts +19 -0
  34. package/dist/utils/sdk-version.util.js +34 -0
  35. package/package.json +3 -2
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Model providers the agent recognises by host, and how to read which model a
3
+ * call asked for before its response says.
4
+ *
5
+ * Recognised by host rather than by SDK: the official clients, the Vercel AI
6
+ * SDK, LangChain and a hand-written `fetch` all end in the same request to the
7
+ * same host, so a host list covers every client without knowing any of them.
8
+ */
9
+ /** The provider a call to `host` goes to, or undefined when it is not one. */
10
+ export declare function llmProviderForHost(host: string, extraHosts?: ReadonlySet<string>): string | undefined;
11
+ /**
12
+ * The model a JSON request body names, read from its first 64 KB.
13
+ *
14
+ * A pattern rather than `JSON.parse`: the body is the application's prompt,
15
+ * often far larger than the one field wanted, and every client puts `model`
16
+ * near the top. Bodies that are streams or forms are not read at all - reading
17
+ * them would consume what the request is about to send.
18
+ */
19
+ export declare function modelFromRequestBody(body: unknown): string | undefined;
20
+ /**
21
+ * The model a URL names, for the providers that put it in the path rather
22
+ * than the body: Gemini and Vertex (`.../models/gemini-2.5-flash:generateContent`)
23
+ * and Bedrock (`/model/anthropic.claude-sonnet-4-v1:0/converse`).
24
+ */
25
+ export declare function modelFromUrlPath(pathname: string): string | undefined;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Model providers the agent recognises by host, and how to read which model a
3
+ * call asked for before its response says.
4
+ *
5
+ * Recognised by host rather than by SDK: the official clients, the Vercel AI
6
+ * SDK, LangChain and a hand-written `fetch` all end in the same request to the
7
+ * same host, so a host list covers every client without knowing any of them.
8
+ */
9
+ /** Exact hosts, each with the provider name the dashboard groups by. */
10
+ const EXACT_HOSTS = {
11
+ "api.openai.com": "openai",
12
+ "api.anthropic.com": "anthropic",
13
+ "generativelanguage.googleapis.com": "google",
14
+ "api.mistral.ai": "mistral",
15
+ "api.groq.com": "groq",
16
+ "openrouter.ai": "openrouter",
17
+ "api.together.xyz": "together",
18
+ "api.deepseek.com": "deepseek",
19
+ "api.x.ai": "xai",
20
+ "api.cohere.ai": "cohere",
21
+ "api.cohere.com": "cohere",
22
+ "api.perplexity.ai": "perplexity",
23
+ };
24
+ /** Hosts that carry a tenant or a region in a subdomain. */
25
+ const HOST_PATTERNS = [
26
+ [/^[a-z0-9-]+\.openai\.azure\.com$/, "azure-openai"],
27
+ [/^[a-z0-9-]+\.services\.ai\.azure\.com$/, "azure-openai"],
28
+ [/^[a-z0-9-]+-aiplatform\.googleapis\.com$/, "vertex"],
29
+ [/^bedrock-runtime\.[a-z0-9-]+\.amazonaws\.com$/, "bedrock"],
30
+ ];
31
+ /** The provider a call to `host` goes to, or undefined when it is not one. */
32
+ export function llmProviderForHost(host, extraHosts = new Set()) {
33
+ const normalized = host.toLowerCase();
34
+ const hostname = normalized.replace(/:\d+$/, "");
35
+ const exact = EXACT_HOSTS[hostname];
36
+ if (exact) {
37
+ return exact;
38
+ }
39
+ for (const [pattern, provider] of HOST_PATTERNS) {
40
+ if (pattern.test(hostname)) {
41
+ return provider;
42
+ }
43
+ }
44
+ if (extraHosts.has(normalized) || extraHosts.has(hostname)) {
45
+ return "custom";
46
+ }
47
+ return undefined;
48
+ }
49
+ /** Most of a request body read for its `model` field. Prompts can be megabytes. */
50
+ const MODEL_SCAN_BYTES = 64 * 1024;
51
+ const MODEL_FIELD = /"model"\s*:\s*"([^"\\]{1,128})"/;
52
+ /**
53
+ * The model a JSON request body names, read from its first 64 KB.
54
+ *
55
+ * A pattern rather than `JSON.parse`: the body is the application's prompt,
56
+ * often far larger than the one field wanted, and every client puts `model`
57
+ * near the top. Bodies that are streams or forms are not read at all - reading
58
+ * them would consume what the request is about to send.
59
+ */
60
+ export function modelFromRequestBody(body) {
61
+ let text;
62
+ if (typeof body === "string") {
63
+ text = body.slice(0, MODEL_SCAN_BYTES);
64
+ }
65
+ else if (body instanceof Uint8Array) {
66
+ text = new TextDecoder().decode(body.subarray(0, MODEL_SCAN_BYTES));
67
+ }
68
+ else if (body instanceof ArrayBuffer) {
69
+ text = new TextDecoder().decode(new Uint8Array(body, 0, Math.min(body.byteLength, MODEL_SCAN_BYTES)));
70
+ }
71
+ return text ? MODEL_FIELD.exec(text)?.[1] : undefined;
72
+ }
73
+ /**
74
+ * The model a URL names, for the providers that put it in the path rather
75
+ * than the body: Gemini and Vertex (`.../models/gemini-2.5-flash:generateContent`)
76
+ * and Bedrock (`/model/anthropic.claude-sonnet-4-v1:0/converse`).
77
+ */
78
+ export function modelFromUrlPath(pathname) {
79
+ const google = /\/models\/([^/:]+):/.exec(pathname);
80
+ if (google) {
81
+ return safeDecode(google[1]);
82
+ }
83
+ const bedrock = /\/model\/([^/]+)\/(?:invoke|converse)/.exec(pathname);
84
+ if (bedrock) {
85
+ return safeDecode(bedrock[1]);
86
+ }
87
+ return undefined;
88
+ }
89
+ function safeDecode(value) {
90
+ try {
91
+ return decodeURIComponent(value);
92
+ }
93
+ catch {
94
+ return value;
95
+ }
96
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Reading token usage out of a model provider's response - a JSON body, or
3
+ * the events of a server-sent stream - without ever keeping its text.
4
+ */
5
+ /** What one call consumed, as far as the response said. */
6
+ export interface LlmUsage {
7
+ /** The model that answered - more precise than the one asked for. */
8
+ model?: string;
9
+ /** Every input token, cached ones included. */
10
+ inputTokens?: number;
11
+ outputTokens?: number;
12
+ /** The part of `inputTokens` served from the provider's prompt cache. */
13
+ cachedInputTokens?: number;
14
+ }
15
+ /**
16
+ * One usage object, in whichever provider's spelling, as input, output and
17
+ * cached input.
18
+ *
19
+ * Input means every input token. OpenAI already counts cached tokens inside
20
+ * `prompt_tokens`; Anthropic reports cache reads and writes beside
21
+ * `input_tokens`, so they are added in - otherwise its cached calls would
22
+ * look nearly free of input.
23
+ */
24
+ export declare function normalizeUsage(usage: unknown): LlmUsage;
25
+ /** Later readings win, field by field - a stream reports in pieces. */
26
+ export declare function mergeUsage(into: LlmUsage, next: LlmUsage): LlmUsage;
27
+ /**
28
+ * The usage in one parsed JSON document: a whole response body, or one event
29
+ * of a stream.
30
+ */
31
+ export declare function usageFromDocument(document: unknown): LlmUsage;
32
+ /**
33
+ * Reads a JSON response as it passes through, keeping at most 2 MB.
34
+ *
35
+ * A larger body - a long completion, a batch of embeddings - is not kept: its
36
+ * first and last 32 KB are, and the usage is matched out of those. Every
37
+ * provider writes `usage` after the content and `model` before it.
38
+ */
39
+ export declare class JsonUsageReader {
40
+ private readonly chunks;
41
+ private size;
42
+ private head;
43
+ private tail;
44
+ push(chunk: Uint8Array): void;
45
+ finish(): LlmUsage;
46
+ }
47
+ /**
48
+ * Reads a server-sent event stream as it passes through, one line at a time.
49
+ *
50
+ * Only `data:` lines that can carry usage or a model are parsed - the first
51
+ * event, and any that mention `usage` - so a long stream of text deltas costs
52
+ * a substring search per line rather than a parse.
53
+ */
54
+ export declare class SseUsageReader {
55
+ private readonly now;
56
+ private readonly decoder;
57
+ private pending;
58
+ private skipping;
59
+ private usage;
60
+ private sawEvent;
61
+ /** When the first content event arrived, for time to first token. */
62
+ firstEventAt: number | undefined;
63
+ constructor(now?: () => number);
64
+ push(chunk: Uint8Array): void;
65
+ finish(): LlmUsage;
66
+ private line;
67
+ }
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Reading token usage out of a model provider's response - a JSON body, or
3
+ * the events of a server-sent stream - without ever keeping its text.
4
+ */
5
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
+ const count = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0
7
+ ? Math.round(value)
8
+ : undefined;
9
+ const sum = (...values) => values.some((value) => value !== undefined)
10
+ ? values.reduce((total, value) => total + (value ?? 0), 0)
11
+ : undefined;
12
+ /**
13
+ * One usage object, in whichever provider's spelling, as input, output and
14
+ * cached input.
15
+ *
16
+ * Input means every input token. OpenAI already counts cached tokens inside
17
+ * `prompt_tokens`; Anthropic reports cache reads and writes beside
18
+ * `input_tokens`, so they are added in - otherwise its cached calls would
19
+ * look nearly free of input.
20
+ */
21
+ export function normalizeUsage(usage) {
22
+ if (!isObject(usage)) {
23
+ return {};
24
+ }
25
+ // Cohere v2 nests its counts.
26
+ const billed = isObject(usage.billed_units) ? usage.billed_units : undefined;
27
+ const anthropicCacheRead = count(usage.cache_read_input_tokens);
28
+ const anthropicCacheWrite = count(usage.cache_creation_input_tokens);
29
+ const openAiInput = count(usage.prompt_tokens);
30
+ const input = openAiInput ??
31
+ count(usage.promptTokenCount) ??
32
+ count(usage.inputTokens) ??
33
+ (count(usage.input_tokens) !== undefined ||
34
+ anthropicCacheRead !== undefined ||
35
+ anthropicCacheWrite !== undefined
36
+ ? sum(count(usage.input_tokens), anthropicCacheRead, anthropicCacheWrite)
37
+ : count(billed?.input_tokens));
38
+ const output = count(usage.completion_tokens) ??
39
+ count(usage.output_tokens) ??
40
+ count(usage.outputTokens) ??
41
+ sum(count(usage.candidatesTokenCount), count(usage.thoughtsTokenCount)) ??
42
+ count(billed?.output_tokens);
43
+ const details = (isObject(usage.prompt_tokens_details) && usage.prompt_tokens_details) ||
44
+ (isObject(usage.input_tokens_details) && usage.input_tokens_details) ||
45
+ undefined;
46
+ const cached = count(details?.cached_tokens) ??
47
+ anthropicCacheRead ??
48
+ count(usage.cachedContentTokenCount) ??
49
+ count(usage.prompt_cache_hit_tokens) ??
50
+ count(usage.cacheReadInputTokens);
51
+ return {
52
+ ...(input !== undefined ? { inputTokens: input } : {}),
53
+ ...(output !== undefined ? { outputTokens: output } : {}),
54
+ ...(cached !== undefined ? { cachedInputTokens: cached } : {}),
55
+ };
56
+ }
57
+ /** Later readings win, field by field - a stream reports in pieces. */
58
+ export function mergeUsage(into, next) {
59
+ return {
60
+ model: next.model ?? into.model,
61
+ inputTokens: next.inputTokens ?? into.inputTokens,
62
+ outputTokens: next.outputTokens ?? into.outputTokens,
63
+ cachedInputTokens: next.cachedInputTokens ?? into.cachedInputTokens,
64
+ };
65
+ }
66
+ const modelOf = (value) => typeof value.model === "string"
67
+ ? value.model.slice(0, 128)
68
+ : typeof value.modelVersion === "string"
69
+ ? value.modelVersion.slice(0, 128)
70
+ : undefined;
71
+ /**
72
+ * The usage in one parsed JSON document: a whole response body, or one event
73
+ * of a stream.
74
+ */
75
+ export function usageFromDocument(document) {
76
+ if (!isObject(document)) {
77
+ return {};
78
+ }
79
+ // OpenAI's Responses API streams `response.*` events around a nested
80
+ // response object; Anthropic opens its stream with `message_start` around
81
+ // a nested message.
82
+ const nested = isObject(document.response)
83
+ ? document.response
84
+ : isObject(document.message)
85
+ ? document.message
86
+ : undefined;
87
+ const source = nested ?? document;
88
+ const usage = normalizeUsage(source.usage ??
89
+ source.usageMetadata ??
90
+ document.usage ??
91
+ document.usageMetadata ??
92
+ (isObject(document.meta) ? document.meta.billed_units : undefined));
93
+ const model = modelOf(source) ?? modelOf(document);
94
+ return { ...usage, ...(model ? { model } : {}) };
95
+ }
96
+ /** Largest JSON body parsed whole. Past it only the head and tail are read. */
97
+ const MAX_JSON_BYTES = 2 * 1024 * 1024;
98
+ /** What is kept of an oversized body: usage sits at its end, model at its start. */
99
+ const EDGE_BYTES = 32 * 1024;
100
+ /**
101
+ * Reads a JSON response as it passes through, keeping at most 2 MB.
102
+ *
103
+ * A larger body - a long completion, a batch of embeddings - is not kept: its
104
+ * first and last 32 KB are, and the usage is matched out of those. Every
105
+ * provider writes `usage` after the content and `model` before it.
106
+ */
107
+ export class JsonUsageReader {
108
+ chunks = [];
109
+ size = 0;
110
+ head;
111
+ tail;
112
+ push(chunk) {
113
+ if (this.head) {
114
+ this.tail = keepTail(this.tail, chunk, EDGE_BYTES);
115
+ return;
116
+ }
117
+ this.chunks.push(chunk);
118
+ this.size += chunk.byteLength;
119
+ if (this.size > MAX_JSON_BYTES) {
120
+ const whole = concat(this.chunks, this.size);
121
+ this.head = whole.subarray(0, EDGE_BYTES);
122
+ this.tail = whole.subarray(whole.byteLength - EDGE_BYTES);
123
+ this.chunks.length = 0;
124
+ }
125
+ }
126
+ finish() {
127
+ const decoder = new TextDecoder();
128
+ if (!this.head) {
129
+ try {
130
+ return usageFromDocument(JSON.parse(decoder.decode(concat(this.chunks, this.size))));
131
+ }
132
+ catch {
133
+ return {};
134
+ }
135
+ }
136
+ return usageFromEdges(decoder.decode(this.head), decoder.decode(this.tail ?? new Uint8Array()));
137
+ }
138
+ }
139
+ /** Usage matched out of the two ends of a body too large to parse. */
140
+ function usageFromEdges(head, tail) {
141
+ const number = (name) => {
142
+ const match = new RegExp(`"${name}"\\s*:\\s*(\\d+)`).exec(tail);
143
+ return match ? { [name]: Number(match[1]) } : {};
144
+ };
145
+ const usage = normalizeUsage({
146
+ ...number("prompt_tokens"),
147
+ ...number("completion_tokens"),
148
+ ...number("input_tokens"),
149
+ ...number("output_tokens"),
150
+ ...number("cached_tokens"),
151
+ ...number("cache_read_input_tokens"),
152
+ ...number("cache_creation_input_tokens"),
153
+ ...number("promptTokenCount"),
154
+ ...number("candidatesTokenCount"),
155
+ });
156
+ const cached = /"cached_tokens"\s*:\s*(\d+)/.exec(tail);
157
+ if (cached && usage.cachedInputTokens === undefined) {
158
+ usage.cachedInputTokens = Number(cached[1]);
159
+ }
160
+ const model = /"model"\s*:\s*"([^"\\]{1,128})"/.exec(head)?.[1];
161
+ return { ...usage, ...(model ? { model } : {}) };
162
+ }
163
+ /** Longest stream line examined. Longer lines carry content, not usage. */
164
+ const MAX_SSE_LINE = 1024 * 1024;
165
+ /**
166
+ * Reads a server-sent event stream as it passes through, one line at a time.
167
+ *
168
+ * Only `data:` lines that can carry usage or a model are parsed - the first
169
+ * event, and any that mention `usage` - so a long stream of text deltas costs
170
+ * a substring search per line rather than a parse.
171
+ */
172
+ export class SseUsageReader {
173
+ now;
174
+ decoder = new TextDecoder();
175
+ pending = "";
176
+ skipping = false;
177
+ usage = {};
178
+ sawEvent = false;
179
+ /** When the first content event arrived, for time to first token. */
180
+ firstEventAt;
181
+ constructor(now = () => performance.now()) {
182
+ this.now = now;
183
+ }
184
+ push(chunk) {
185
+ const text = this.decoder.decode(chunk, { stream: true });
186
+ let start = 0;
187
+ for (;;) {
188
+ const newline = text.indexOf("\n", start);
189
+ if (newline === -1) {
190
+ break;
191
+ }
192
+ if (this.skipping) {
193
+ // The oversized line ends here, unread.
194
+ this.skipping = false;
195
+ }
196
+ else {
197
+ this.line(this.pending + text.slice(start, newline));
198
+ }
199
+ this.pending = "";
200
+ start = newline + 1;
201
+ }
202
+ if (this.skipping) {
203
+ return;
204
+ }
205
+ const rest = text.slice(start);
206
+ if (this.pending.length + rest.length > MAX_SSE_LINE) {
207
+ // An oversized line is content; drop it until its end comes past.
208
+ this.pending = "";
209
+ this.skipping = true;
210
+ return;
211
+ }
212
+ this.pending += rest;
213
+ }
214
+ finish() {
215
+ if (this.pending) {
216
+ this.line(this.pending);
217
+ this.pending = "";
218
+ }
219
+ return this.usage;
220
+ }
221
+ line(raw) {
222
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
223
+ if (!line.startsWith("data:")) {
224
+ return;
225
+ }
226
+ const data = line.slice(5).trim();
227
+ if (!data || data === "[DONE]") {
228
+ return;
229
+ }
230
+ this.firstEventAt ??= this.now();
231
+ const first = !this.sawEvent;
232
+ this.sawEvent = true;
233
+ if (!first && !data.includes("sage")) {
234
+ return;
235
+ }
236
+ try {
237
+ this.usage = mergeUsage(this.usage, usageFromDocument(JSON.parse(data)));
238
+ }
239
+ catch {
240
+ /* not JSON, or not ours to read */
241
+ }
242
+ }
243
+ }
244
+ function concat(chunks, size) {
245
+ const whole = new Uint8Array(size);
246
+ let offset = 0;
247
+ for (const chunk of chunks) {
248
+ whole.set(chunk, offset);
249
+ offset += chunk.byteLength;
250
+ }
251
+ return whole;
252
+ }
253
+ function keepTail(tail, chunk, limit) {
254
+ if (chunk.byteLength >= limit) {
255
+ return chunk.slice(chunk.byteLength - limit);
256
+ }
257
+ const previous = tail ?? new Uint8Array();
258
+ const keep = Math.min(previous.byteLength, limit - chunk.byteLength);
259
+ const next = new Uint8Array(keep + chunk.byteLength);
260
+ next.set(previous.subarray(previous.byteLength - keep), 0);
261
+ next.set(chunk, keep);
262
+ return next;
263
+ }
@@ -6,6 +6,7 @@ export declare class OutgoingObserveAgentService implements OnApplicationShutdow
6
6
  private readonly options;
7
7
  private readonly logger;
8
8
  private unsubscribeHttp?;
9
+ private deactivateLlm?;
9
10
  constructor(options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<any, any>>);
10
11
  onApplicationShutdown(): void;
11
12
  /**
@@ -17,6 +17,7 @@ import { OBSERVE_OPTIONS } from "../observe.constants.js";
17
17
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
18
18
  import { loadAsResolvedBy, loadOptionalPeer, } from "../utils/optional-peer.util.js";
19
19
  import { subscribeOutgoingHttp } from "./http.integration.js";
20
+ import { activateLlmFetchObserver, llmCallsOff, uninstallLlmFetchObserver, } from "./llm/llm-fetch.integration.js";
20
21
  import { patchMongodb } from "./mongodb.integration.js";
21
22
  import { patchMssql } from "./mssql.integration.js";
22
23
  import { patchMysql2 } from "./mysql2.integration.js";
@@ -91,9 +92,15 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
91
92
  options;
92
93
  logger = new Logger(OutgoingObserveAgentService_1.name);
93
94
  unsubscribeHttp;
95
+ deactivateLlm;
94
96
  constructor(options, operationTraceRegistry, asyncLocalStorage) {
95
97
  this.options = options;
96
98
  const outgoing = this.options.outgoing;
99
+ // `forRoot` has given `fetch` back already; `forRootAsync` options are
100
+ // only known from here.
101
+ if (llmCallsOff(outgoing)) {
102
+ uninstallLlmFetchObserver();
103
+ }
97
104
  if (outgoing === false) {
98
105
  return;
99
106
  }
@@ -111,9 +118,14 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
111
118
  ?.get(this.options.traceIdKey);
112
119
  return typeof traceId === "string" ? traceId : undefined;
113
120
  }, typeof outgoing?.http === "object" ? outgoing.http : {}, () => operationTraceRegistry.getRedactor());
121
+ // Model calls are read off the spans above, so they go with them.
122
+ if (outgoing?.llm !== false) {
123
+ this.deactivateLlm = activateLlmFetchObserver(recorder, typeof outgoing?.llm === "object" ? outgoing.llm : {});
124
+ }
114
125
  }
115
126
  }
116
127
  onApplicationShutdown() {
128
+ this.deactivateLlm?.();
117
129
  this.unsubscribeHttp?.();
118
130
  }
119
131
  /**
@@ -4,6 +4,15 @@ type Tags = Record<string, string | number | boolean>;
4
4
  /** A span that has been opened and is waiting to be told how the call went. */
5
5
  export interface OpenOutgoingSpan {
6
6
  end(error?: unknown): void;
7
+ /** Adds tags to the span - what the response said, once it has been read. */
8
+ tag?(tags: Tags): void;
9
+ /**
10
+ * Keeps the span from closing at `end` until the returned function runs,
11
+ * so tags read from the response can still reach it. The span keeps the
12
+ * duration it had at `end`, and closes on its own `HOLD_GRACE_MS` later if
13
+ * the hold is never released.
14
+ */
15
+ hold?(): () => void;
7
16
  }
8
17
  /**
9
18
  * Opens leaf spans for calls that leave the process - a database query, an
@@ -1,5 +1,11 @@
1
1
  import { AsyncLocalStorage } from "async_hooks";
2
2
  import { CALLER_METADATA_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
3
+ /**
4
+ * How long a held span may stay open after its call ended, waiting for what
5
+ * is reading its response. Well under the second the registry waits for open
6
+ * spans before it ships an operation without them.
7
+ */
8
+ const HOLD_GRACE_MS = 250;
3
9
  /**
4
10
  * Opens leaf spans for calls that leave the process - a database query, an
5
11
  * outbound HTTP request - under whatever span is active when they are made.
@@ -52,17 +58,60 @@ export class OutgoingSpanRecorder {
52
58
  if (node) {
53
59
  node.tags = { ...node.tags, ...tags };
54
60
  }
61
+ const startTime = node?.startTime;
55
62
  let ended = false;
63
+ let holds = 0;
64
+ let deferred;
65
+ let grace;
66
+ const close = (error, endedAt) => {
67
+ // A driver may report one call twice - a callback and an `error`
68
+ // event, a settled promise and a late listener. The registry counts
69
+ // closes against opens, so the second would unbalance the snapshot.
70
+ if (ended) {
71
+ return;
72
+ }
73
+ ended = true;
74
+ clearTimeout(grace);
75
+ this.operationTraceRegistry.internalEndTraceStep(registryKey, spanId, className, methodKey, spanId, error === undefined || error === null ? undefined : error);
76
+ // A held span closes late; the call itself ended at `endedAt`.
77
+ if (node && endedAt !== undefined && startTime !== undefined) {
78
+ node.duration = Math.max(endedAt - startTime, 0);
79
+ }
80
+ };
56
81
  return {
57
82
  end: (error) => {
58
- // A driver may report one call twice - a callback and an `error`
59
- // event, a settled promise and a late listener. The registry counts
60
- // closes against opens, so the second would unbalance the snapshot.
61
- if (ended) {
83
+ if (ended || deferred) {
84
+ return;
85
+ }
86
+ if (holds === 0) {
87
+ close(error);
62
88
  return;
63
89
  }
64
- ended = true;
65
- this.operationTraceRegistry.internalEndTraceStep(registryKey, spanId, className, methodKey, spanId, error === undefined || error === null ? undefined : error);
90
+ deferred = { at: performance.now(), error };
91
+ grace = setTimeout(() => close(deferred?.error, deferred?.at), HOLD_GRACE_MS);
92
+ grace.unref?.();
93
+ },
94
+ tag: (extra) => {
95
+ if (node) {
96
+ node.tags = { ...node.tags, ...extra };
97
+ }
98
+ },
99
+ hold: () => {
100
+ if (ended) {
101
+ return () => undefined;
102
+ }
103
+ holds += 1;
104
+ let released = false;
105
+ return () => {
106
+ if (released) {
107
+ return;
108
+ }
109
+ released = true;
110
+ holds -= 1;
111
+ if (holds === 0 && deferred) {
112
+ close(deferred.error, deferred.at);
113
+ }
114
+ };
66
115
  },
67
116
  };
68
117
  }
@@ -0,0 +1,27 @@
1
+ import type { Logger } from "@nestjs/common";
2
+ /**
3
+ * Runs a callback from the module options, answering `fallback()` when it
4
+ * throws. These callbacks only shape what is recorded, so a bug in one must
5
+ * not fail the request, message or job being recorded - or, thrown from a
6
+ * timer, end the process. The first failure of each callback is reported
7
+ * with its error and `outcome`, what was given up for it; later ones are not.
8
+ */
9
+ export declare function invokeUserCallbackSafely<TArgs extends unknown[], TResult, TFallback>(callback: (...args: TArgs) => TResult, args: TArgs, receiver: unknown, fallback: () => TFallback, logger: Logger, name: string, outcome: string): TResult | TFallback;
10
+ /**
11
+ * The trace id for an operation. A generator that throws is replaced by a
12
+ * fresh uuidv7, which no open trace can share, so the operation is still
13
+ * traced under a registry key of its own.
14
+ */
15
+ export declare function generateTraceIdSafely(generator: (context: unknown) => string, context: unknown, receiver: unknown, logger: Logger): string;
16
+ /** Copies an operation's `setAttributes` into its store, unless it throws. */
17
+ export declare function setAttributesSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => Record<string, unknown>) | undefined, args: TArgs, receiver: unknown, store: Map<any, unknown>, logger: Logger, transport: string): void;
18
+ /**
19
+ * Whether `ignore` excludes an operation. One that throws excludes it as
20
+ * well: the operation still runs, but recording what a broken predicate may
21
+ * have been written to keep out is not a safe guess.
22
+ */
23
+ export declare function shouldIgnoreSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => boolean) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): boolean;
24
+ /** A bad identity callback must not prevent the trace from being closed. */
25
+ export declare function getUserIdSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => string | undefined) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): string | undefined;
26
+ /** Run deferred completion without ever leaking a rejection from its timer. */
27
+ export declare function deferTraceCompletion(completion: () => Promise<void>, logger: Logger, transport: string): void;