@nestjs/observe 0.3.19 → 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.
package/README.md CHANGED
@@ -288,6 +288,7 @@ Once the module and the instrument are in place, the agent reports, with no furt
288
288
  - **Requests, GraphQL operations, RPC messages, WebSocket gateway messages, queue jobs and scheduled jobs**, each with its tree of provider method calls.
289
289
  - **Database queries**, as a span under the method that ran them, for `pg`, `mysql2`, `mssql` and `mongodb`. Anything built on those drivers is covered without being known by name: TypeORM, Drizzle, MikroORM and Mongoose are tested in this repository, and others (Knex, Sequelize) go through the same driver calls. SQL Server is the exception: `mssql` is what TypeORM and Prisma's SQL Server adapter run on, but Knex, Sequelize and MikroORM talk to SQL Server through `tedious` directly, which is not covered yet (nor is `mssql/msnodesqlv8`). The statement is recorded with every value removed (`SELECT "o"."id" FROM "orders" "o" WHERE "o"."customer_id" = $1`). Prisma's Rust query engine does not go through these drivers and is not covered yet.
290
290
  - **Outbound HTTP calls** made with `fetch`/`undici` or `node:http`/`https` (so Axios too), as `POST api.stripe.com`. The current trace id is forwarded as `x-request-id` - by `fetch` on every supported Node version, by `node:http`/`https` from Node 22.12, the first to let a request's headers still be set at that point - so a service that also runs the agent continues the same trace; a header you set yourself is never overwritten.
291
+ - **Model calls**: a `fetch` to OpenAI, Azure OpenAI, Anthropic, Gemini or Vertex, Bedrock, Mistral, Groq, OpenRouter, Together, DeepSeek, xAI, Cohere or Perplexity also reports the model and the input, output and cached tokens its response states - read as the response passes through to your code, streams included, so it arrives exactly as it would have and a stream you cancel is cancelled at the provider too. That covers the official SDKs, the Vercel AI SDK and LangChain, which all use `fetch`; calls made through `node:http` (axios, the AWS SDK) keep their plain span. Prompts and completions are never reported. A gateway in front of the providers is added with `outgoing: { llm: { hosts: ['llm-gateway.internal:4000'] } }`, and `outgoing: { llm: false }` turns this off and leaves the global `fetch` as it was.
291
292
  - **Trace ids across queues**: a BullMQ (Pro included) or Bull job enqueued while handling a request carries that request's trace id, so the request and its job show up as one trace. Repeatable (cron) jobs start their own.
292
293
  - **The code around an error's throw site**: for each in-app frame of a captured error, a few lines of source either side, read from the running process, so the dashboard shows the failing code next to the stack. This sends fragments of your application's source to Observe, stored with the error. Frames in `node_modules` and Node internals are never read. `createObserveModule({ sourceContext: false })` turns it off; the [documentation](https://www.observe.nestjs.com/documentation/sdk#error-source-context) covers tuning it instead.
293
294
  - **The release it is running**, so Releases, regressions and fix verification work without a version threaded through the build: `OBSERVE_SERVICE_VERSION` if the environment sets it, else the commit a platform or CI job exposes (Vercel, Render, Railway, Heroku, GitHub Actions, GitLab CI and others), else the commit checked out where the process runs, else a Cloud Run or Azure Container Apps revision. A container image usually carries none of these, so hand it the commit at build time - `ARG GIT_SHA` then `ENV OBSERVE_SERVICE_VERSION=$GIT_SHA`. `serviceVersion` names the release yourself, in at most 50 characters - a longer one is cut to fit, with a warning at startup; `serviceVersion: false` reports none.
@@ -437,7 +438,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
437
438
  | `traceIdGenerator` | the `x-request-id` header, else a UUIDv7 | Gives each request its trace id. |
438
439
  | `traceIdKey` | `'traceId'` | The key the trace id is stored under in the request context. |
439
440
  | `attachTraceIdToLogs` | `true` | Adds the trace id to the `ConsoleLogger`'s own output, on Nest 11.2 and later. Sending lines to the dashboard is `forwardLogs`. |
440
- | `skipInstrumentation` | `() => false` | Returns `true` for a provider instance that must not be instrumented. Nest's `Reflector` never is, whatever this returns. |
441
+ | `skipInstrumentation` | `() => false` | Returns `true` for a provider instance that must not be instrumented. Nest's `Reflector` and the `mongodb` driver's `MongoClient` and `Db` never are, whatever this returns. |
441
442
 
442
443
  ## Optional peer dependencies
443
444
 
@@ -22,14 +22,47 @@ const FALLBACK_CLASS_NAME = "Object";
22
22
  * Matched by shape as well as by class: an application with a second copy of
23
23
  * `@nestjs/core` in its tree has a second `Reflector` class, which the
24
24
  * `instanceof` alone would miss.
25
+ *
26
+ * A `MongoClient` or `Db` registered as a provider is the other.
25
27
  */
26
28
  function isFrameworkNoise(instance) {
27
29
  if (instance instanceof Reflector) {
28
30
  return true;
29
31
  }
30
32
  const candidate = instance;
31
- return (candidate.constructor?.name === "Reflector" &&
32
- typeof candidate.getAllAndOverride === "function");
33
+ return ((candidate.constructor?.name === "Reflector" &&
34
+ typeof candidate.getAllAndOverride === "function") ||
35
+ isMongoDriverHandle(instance));
36
+ }
37
+ /**
38
+ * Whether an instance is the `mongodb` driver's `MongoClient` or `Db`.
39
+ *
40
+ * Instrumenting them breaks the driver, not just the waterfall. Traced calls
41
+ * run with the proxy as receiver and untraced ones with the raw instance, so
42
+ * what a method keeps of `this` depends on whether a trace was active: a `Db`
43
+ * made at bootstrap holds the raw client, a session started in a traced
44
+ * request holds the proxy, and the driver's `session.client !== client` check
45
+ * throws "ClientSession must be from the same MongoClient" - for every
46
+ * explicit session, transaction and `withSession` on a traced request, while
47
+ * the same calls on a sampled-out one succeed. The command spans the mongodb
48
+ * integration records are the useful part anyway; `Db.collection` and
49
+ * `MongoClient.startSession` spans are not.
50
+ *
51
+ * Matched by name and shape only: the driver is an optional peer, never
52
+ * imported here, and an application may carry more than one copy of it.
53
+ */
54
+ function isMongoDriverHandle(instance) {
55
+ const candidate = instance;
56
+ switch (candidate.constructor?.name) {
57
+ case "MongoClient":
58
+ return (typeof candidate.startSession === "function" &&
59
+ typeof candidate.db === "function");
60
+ case "Db":
61
+ return (typeof candidate.collection === "function" &&
62
+ typeof candidate.databaseName === "string");
63
+ default:
64
+ return false;
65
+ }
33
66
  }
34
67
  export function createInstanceDecorator(als, operationTraceRegistry, options) {
35
68
  /**
@@ -1,4 +1,5 @@
1
1
  import type { OutgoingHttpOptions } from "../outgoing/http.integration.js";
2
+ import type { OutgoingLlmOptions } from "../outgoing/llm/llm-fetch.integration.js";
2
3
  import type { HttpCaptureOptions } from "../utils/capture-request.util.js";
3
4
  import { FactoryProvider, ModuleMetadata, Provider, Type } from "@nestjs/common";
4
5
  import { BaseRpcContext, Transport } from "@nestjs/microservices";
@@ -79,7 +80,9 @@ export interface CreateObserveModuleOptions {
79
80
  *
80
81
  * Nest's own `Reflector` is never instrumented, whatever this returns: its
81
82
  * metadata lookups run several times a request and say nothing a
82
- * waterfall is for.
83
+ * waterfall is for. Nor are the `mongodb` driver's `MongoClient` and
84
+ * `Db`: their command spans come from the mongodb integration, and a
85
+ * proxied client fails the driver's session identity checks.
83
86
  *
84
87
  * Runs before the built-in checks, so it also shields providers that
85
88
  * cannot even be inspected safely: some libraries (nestjs-cls proxy
@@ -602,6 +605,18 @@ export interface ObserveOptions {
602
605
  database?: boolean;
603
606
  /** @default true */
604
607
  http?: boolean | OutgoingHttpOptions;
608
+ /**
609
+ * Model calls: for a `fetch` to a model provider (OpenAI, Anthropic,
610
+ * Gemini, Bedrock, Mistral and others), the model and the tokens its
611
+ * response reports, read as the response passes through to the
612
+ * caller. Prompts and completions are never read into the report.
613
+ * Needs `http`; calls made through `node:http` (axios) keep their
614
+ * plain span. Off, the global `fetch` is left as it was: `forRoot`
615
+ * puts the original back, and `forRootAsync` does when the agent
616
+ * starts.
617
+ * @default true
618
+ */
619
+ llm?: boolean | OutgoingLlmOptions;
605
620
  };
606
621
  /**
607
622
  * WebSocket gateway configuration options for the Observe APM.
@@ -21,6 +21,7 @@ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "./observe.constants.js";
21
21
  import { GraphQLObserveAgentService } from "./protocols/graphql-observe-agent.service.js";
22
22
  import { HttpObserveAgentService } from "./protocols/http-observe-agent.service.js";
23
23
  import { OutgoingObserveAgentService } from "./outgoing/outgoing-observe-agent.service.js";
24
+ import { installLlmFetchObserver, llmCallsOff, uninstallLlmFetchObserver, } from "./outgoing/llm/llm-fetch.integration.js";
24
25
  import { BullObserveAgentService } from "./protocols/bull-observe-agent.service.js";
25
26
  import { QueueObserveAgentService } from "./protocols/queue-observe-agent.service.js";
26
27
  import { RpcObserveAgentService } from "./protocols/rpc-observe-agent.service.js";
@@ -125,6 +126,9 @@ export function createObserveModule(options = {}) {
125
126
  options.attachTraceIdToLogs ??= true;
126
127
  options.traceIdGenerator ??= defaultTraceIdGenerator;
127
128
  options.skipInstrumentation ??= () => false;
129
+ // Inert until the agent starts with `outgoing.llm` on - see the function.
130
+ // `forRoot` puts the original back if its options turn model calls off.
131
+ installLlmFetchObserver();
128
132
  const asyncLocalStorage = new AsyncLocalStorage();
129
133
  const operationTraceRegistry = new OperationTraceRegistry(asyncLocalStorage, options.sourceContext);
130
134
  let ObserveModule = ObserveModule_1 = class ObserveModule {
@@ -138,6 +142,14 @@ export function createObserveModule(options = {}) {
138
142
  this.options = options;
139
143
  }
140
144
  static forRoot(observeOpts) {
145
+ // Options that turn model calls off give `fetch` back now, before the
146
+ // application's clients are constructed around the wrapper.
147
+ if (llmCallsOff(observeOpts.outgoing)) {
148
+ uninstallLlmFetchObserver();
149
+ }
150
+ else {
151
+ installLlmFetchObserver();
152
+ }
141
153
  return {
142
154
  global: true,
143
155
  module: ObserveModule_1,
@@ -1,5 +1,6 @@
1
1
  import { subscribe, unsubscribe } from "diagnostics_channel";
2
2
  import { redactUrlQuery } from "../utils/redact-url-query.js";
3
+ import { attachLlmSpan } from "./llm/llm-fetch.integration.js";
3
4
  const TRACE_HEADER = "x-request-id";
4
5
  /**
5
6
  * Spans for outbound HTTP, from the diagnostics channels Node publishes on its
@@ -48,6 +49,9 @@ getRedactor = () => null) {
48
49
  });
49
50
  if (span) {
50
51
  spans.set(request, span);
52
+ // A no-op unless this request is a model call the fetch observer is
53
+ // reading - see `llm-fetch.integration.ts`.
54
+ attachLlmSpan(span);
51
55
  }
52
56
  return true;
53
57
  };
@@ -0,0 +1,56 @@
1
+ import { AsyncLocalStorage } from "async_hooks";
2
+ import type { ObserveOptions } from "../../interfaces/observe-options.interface.js";
3
+ import { OpenOutgoingSpan, OutgoingSpanRecorder } from "../outgoing-span.recorder.js";
4
+ export interface OutgoingLlmOptions {
5
+ /**
6
+ * More hosts to read as model providers - a gateway in front of them, a
7
+ * self-hosted model with an OpenAI-compatible API - as `host` or
8
+ * `host:port`. Their calls are tagged with the provider `custom`.
9
+ * @example ['llm-gateway.internal:4000']
10
+ */
11
+ hosts?: string[];
12
+ }
13
+ /**
14
+ * What one observed `fetch` call learns from the outbound span undici opens
15
+ * for it: the span, held open until the response has been read.
16
+ */
17
+ interface LlmFetchHolder {
18
+ span?: OpenOutgoingSpan;
19
+ release?: () => void;
20
+ }
21
+ /**
22
+ * Carries a holder from the `fetch` call into undici's request-create channel,
23
+ * which runs inside the call's async context. That is how the span the HTTP
24
+ * integration opens is found again here, without a header or a lookup table.
25
+ */
26
+ export declare const llmFetchContext: AsyncLocalStorage<LlmFetchHolder>;
27
+ /** Called by the HTTP integration for every span it opens. */
28
+ export declare function attachLlmSpan(span: OpenOutgoingSpan | undefined): void;
29
+ /**
30
+ * Whether an `outgoing` option turns model calls off. They are read off the
31
+ * HTTP spans, so turning those off turns model calls off with them.
32
+ */
33
+ export declare function llmCallsOff(outgoing: ObserveOptions["outgoing"]): boolean;
34
+ /**
35
+ * Wraps the global `fetch` once, inert until `activateLlmFetchObserver`.
36
+ *
37
+ * Wrapped as early as the module is created rather than when the agent
38
+ * starts: a client that captures `fetch` when it is constructed - the
39
+ * official OpenAI and Anthropic SDKs do - and is constructed before Nest
40
+ * instantiates the agent would otherwise keep the unwrapped one. Calls to
41
+ * any other host go straight to the original. An application that turns
42
+ * model calls off gets the original back - see `uninstallLlmFetchObserver`.
43
+ */
44
+ export declare function installLlmFetchObserver(): void;
45
+ /**
46
+ * Puts the original `fetch` back, for an application that turned model calls
47
+ * off: with them off, nothing of this should sit in its calls' path.
48
+ *
49
+ * Only while the wrapper is still the global one. Something that wrapped
50
+ * `fetch` again on top of it would be unwrapped too, so in that case the
51
+ * wrapper stays where it is, inert - a straight pass-through.
52
+ */
53
+ export declare function uninstallLlmFetchObserver(): void;
54
+ /** Starts reading model calls; the returned function stops it again. */
55
+ export declare function activateLlmFetchObserver(recorder: OutgoingSpanRecorder, options?: OutgoingLlmOptions): () => void;
56
+ export {};
@@ -0,0 +1,236 @@
1
+ import { AsyncLocalStorage } from "async_hooks";
2
+ import { llmProviderForHost, modelFromRequestBody, modelFromUrlPath, } from "./llm-providers.js";
3
+ import { JsonUsageReader, mergeUsage, SseUsageReader, } from "./llm-usage.js";
4
+ /**
5
+ * Carries a holder from the `fetch` call into undici's request-create channel,
6
+ * which runs inside the call's async context. That is how the span the HTTP
7
+ * integration opens is found again here, without a header or a lookup table.
8
+ */
9
+ export const llmFetchContext = new AsyncLocalStorage();
10
+ /** Called by the HTTP integration for every span it opens. */
11
+ export function attachLlmSpan(span) {
12
+ const holder = llmFetchContext.getStore();
13
+ if (!holder || !span || holder.span) {
14
+ return;
15
+ }
16
+ holder.span = span;
17
+ // Taken now, before undici can end the span: a small response can arrive
18
+ // whole, and end its span, before the caller's `await` sees it.
19
+ holder.release = span.hold?.();
20
+ }
21
+ const INSTALLED = Symbol.for("@nestjs/observe:llm-fetch");
22
+ let active;
23
+ /** The wrapper this copy of the module put in place, and what it wraps. */
24
+ let installed;
25
+ /**
26
+ * Whether an `outgoing` option turns model calls off. They are read off the
27
+ * HTTP spans, so turning those off turns model calls off with them.
28
+ */
29
+ export function llmCallsOff(outgoing) {
30
+ return (outgoing === false || outgoing?.http === false || outgoing?.llm === false);
31
+ }
32
+ /**
33
+ * Wraps the global `fetch` once, inert until `activateLlmFetchObserver`.
34
+ *
35
+ * Wrapped as early as the module is created rather than when the agent
36
+ * starts: a client that captures `fetch` when it is constructed - the
37
+ * official OpenAI and Anthropic SDKs do - and is constructed before Nest
38
+ * instantiates the agent would otherwise keep the unwrapped one. Calls to
39
+ * any other host go straight to the original. An application that turns
40
+ * model calls off gets the original back - see `uninstallLlmFetchObserver`.
41
+ */
42
+ export function installLlmFetchObserver() {
43
+ const original = globalThis.fetch;
44
+ if (typeof original !== "function" || original[INSTALLED]) {
45
+ return;
46
+ }
47
+ const observed = function fetch(input, init) {
48
+ const config = active;
49
+ if (!config) {
50
+ return original(input, init);
51
+ }
52
+ let target;
53
+ try {
54
+ target =
55
+ typeof input === "string"
56
+ ? new URL(input)
57
+ : input instanceof URL
58
+ ? input
59
+ : new URL(input.url);
60
+ }
61
+ catch {
62
+ return original(input, init);
63
+ }
64
+ const provider = llmProviderForHost(target.host, config.extraHosts);
65
+ // Outside a traced operation there is no span to tag.
66
+ if (!provider || !config.recorder.isRecording()) {
67
+ return original(input, init);
68
+ }
69
+ return observeCall(original, input, init, {
70
+ provider,
71
+ requestModel: modelFromRequestBody(init?.body) ?? modelFromUrlPath(target.pathname),
72
+ });
73
+ };
74
+ Object.defineProperty(observed, INSTALLED, { value: true });
75
+ globalThis.fetch = observed;
76
+ installed = { wrapper: observed, original };
77
+ }
78
+ /**
79
+ * Puts the original `fetch` back, for an application that turned model calls
80
+ * off: with them off, nothing of this should sit in its calls' path.
81
+ *
82
+ * Only while the wrapper is still the global one. Something that wrapped
83
+ * `fetch` again on top of it would be unwrapped too, so in that case the
84
+ * wrapper stays where it is, inert - a straight pass-through.
85
+ */
86
+ export function uninstallLlmFetchObserver() {
87
+ active = undefined;
88
+ if (installed && globalThis.fetch === installed.wrapper) {
89
+ globalThis.fetch = installed.original;
90
+ installed = undefined;
91
+ }
92
+ }
93
+ /** Starts reading model calls; the returned function stops it again. */
94
+ export function activateLlmFetchObserver(recorder, options = {}) {
95
+ installLlmFetchObserver();
96
+ const config = {
97
+ recorder,
98
+ extraHosts: new Set((options.hosts ?? []).map((host) => host.toLowerCase())),
99
+ };
100
+ active = config;
101
+ return () => {
102
+ if (active === config) {
103
+ active = undefined;
104
+ }
105
+ };
106
+ }
107
+ async function observeCall(original, input, init, call) {
108
+ const startedAt = performance.now();
109
+ const holder = {};
110
+ const tag = (usage, stream, firstEventAt) => {
111
+ try {
112
+ holder.span?.tag?.(spanTags(call, mergeUsage({ model: call.requestModel }, usage), {
113
+ stream,
114
+ timeToFirstToken: firstEventAt === undefined
115
+ ? undefined
116
+ : round(firstEventAt - startedAt),
117
+ }));
118
+ }
119
+ catch {
120
+ /* a lost tag must never cost the caller its response */
121
+ }
122
+ finally {
123
+ holder.release?.();
124
+ }
125
+ };
126
+ let response;
127
+ try {
128
+ response = await llmFetchContext.run(holder, () => original(input, init));
129
+ }
130
+ catch (error) {
131
+ tag({}, false);
132
+ throw error;
133
+ }
134
+ const contentType = response.headers.get("content-type") ?? "";
135
+ const stream = contentType.includes("text/event-stream");
136
+ const reader = stream
137
+ ? new SseUsageReader()
138
+ : contentType.includes("json")
139
+ ? new JsonUsageReader()
140
+ : undefined;
141
+ // No span was opened for it (an outer entry point covers the call), or
142
+ // there is nothing to read: the response goes back untouched.
143
+ if (!holder.span || !reader || !response.body) {
144
+ tag({}, stream);
145
+ return response;
146
+ }
147
+ let tagged = false;
148
+ const finish = () => {
149
+ if (tagged) {
150
+ return;
151
+ }
152
+ tagged = true;
153
+ let usage = {};
154
+ try {
155
+ usage = reader.finish();
156
+ }
157
+ catch {
158
+ /* unreadable: tag the call without its usage */
159
+ }
160
+ tag(usage, stream, reader instanceof SseUsageReader ? reader.firstEventAt : undefined);
161
+ };
162
+ // Read only as the caller reads, and cancelled when the caller cancels: a
163
+ // tee would keep pulling a stream the caller abandoned, and the model would
164
+ // go on generating - and billing - a completion nobody reads.
165
+ const source = response.body.getReader();
166
+ const body = new ReadableStream({
167
+ async pull(controller) {
168
+ let chunk;
169
+ try {
170
+ chunk = await source.read();
171
+ }
172
+ catch (error) {
173
+ finish();
174
+ controller.error(error);
175
+ return;
176
+ }
177
+ if (chunk.done) {
178
+ finish();
179
+ controller.close();
180
+ return;
181
+ }
182
+ try {
183
+ reader.push(chunk.value);
184
+ }
185
+ catch {
186
+ /* the bytes still reach the caller */
187
+ }
188
+ controller.enqueue(chunk.value);
189
+ },
190
+ cancel(reason) {
191
+ finish();
192
+ return source.cancel(reason);
193
+ },
194
+ }, { highWaterMark: 0 });
195
+ return rewrap(response, body);
196
+ }
197
+ /** The same response, reading through `body`. */
198
+ function rewrap(response, body) {
199
+ const wrapped = new Response(body, {
200
+ status: response.status,
201
+ statusText: response.statusText,
202
+ headers: response.headers,
203
+ });
204
+ // Read-only getters on a constructed response; the original's values are
205
+ // what the caller would have seen.
206
+ Object.defineProperties(wrapped, {
207
+ url: { value: response.url },
208
+ redirected: { value: response.redirected },
209
+ type: { value: response.type },
210
+ });
211
+ return wrapped;
212
+ }
213
+ /** The call, as tags on its outbound span - what the waterfall shows. */
214
+ function spanTags(call, usage, extra) {
215
+ return {
216
+ "llm.provider": call.provider,
217
+ // A path-borne Bedrock model id can run long; tags are not the place.
218
+ ...(usage.model ? { "llm.model": usage.model.slice(0, 128) } : {}),
219
+ ...(usage.inputTokens !== undefined
220
+ ? { "llm.input_tokens": usage.inputTokens }
221
+ : {}),
222
+ ...(usage.outputTokens !== undefined
223
+ ? { "llm.output_tokens": usage.outputTokens }
224
+ : {}),
225
+ ...(usage.cachedInputTokens !== undefined
226
+ ? { "llm.cached_input_tokens": usage.cachedInputTokens }
227
+ : {}),
228
+ ...(extra.stream ? { "llm.stream": true } : {}),
229
+ ...(extra.timeToFirstToken !== undefined
230
+ ? { "llm.time_to_first_token_ms": extra.timeToFirstToken }
231
+ : {}),
232
+ };
233
+ }
234
+ function round(value) {
235
+ return Math.round(value * 100) / 100;
236
+ }
@@ -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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.19",
3
+ "version": "0.3.20",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics and custom metrics",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://observe.nestjs.com",