@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
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
 
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Where a project generated by `nest new` points before it is connected: the
3
+ * hosted demo, which shows what the dashboard will look like.
4
+ */
5
+ export declare const DEMO_URL = "https://www.observe-demo.nestjs.com/dashboard";
6
+ export declare const SIGN_UP_URL = "https://observe.nestjs.com";
7
+ /**
8
+ * The command that connects a project in one step: it signs the developer in,
9
+ * writes the key pair into `.env` and makes the start scripts load it.
10
+ */
11
+ export declare const LINK_COMMAND = "npx @nestjs/observe link";
12
+ export interface CredentialsNotice {
13
+ level: "log" | "warn";
14
+ message: string;
15
+ }
16
+ /**
17
+ * The one line the agent says at start-up when it has no key pair it can send
18
+ * with, so it sends nothing.
19
+ *
20
+ * Two situations look alike from inside the process and want opposite advice.
21
+ * A project fresh from `nest new` still holds the scaffolded placeholders:
22
+ * the fix is to connect it, which `npx @nestjs/observe link` does in one
23
+ * step. A deployed process with the same placeholders, or with nothing at
24
+ * all, is almost always a project that was connected on a laptop: link keeps
25
+ * the pair in `.env`, which is git-ignored and which `node dist/main` never
26
+ * loads, so production needs the two variables set where it runs. Telling
27
+ * that person to create an account sends them looking for something they
28
+ * already have, so under `NODE_ENV=production` the notice names the
29
+ * variables instead.
30
+ *
31
+ * @param scaffold the options still hold `nest new`'s placeholders
32
+ * @param unset which half of the pair is missing, when the options hold no
33
+ * placeholders but lack a key, a secret or both
34
+ */
35
+ export declare function describeMissingCredentials(input: {
36
+ scaffold: boolean;
37
+ unset?: "both" | "appKey" | "appSecret";
38
+ production: boolean;
39
+ }): CredentialsNotice;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Where a project generated by `nest new` points before it is connected: the
3
+ * hosted demo, which shows what the dashboard will look like.
4
+ */
5
+ export const DEMO_URL = "https://www.observe-demo.nestjs.com/dashboard";
6
+ export const SIGN_UP_URL = "https://observe.nestjs.com";
7
+ /**
8
+ * The command that connects a project in one step: it signs the developer in,
9
+ * writes the key pair into `.env` and makes the start scripts load it.
10
+ */
11
+ export const LINK_COMMAND = "npx @nestjs/observe link";
12
+ /** The variables `ObserveModule` reads a key pair from when its options leave it out. */
13
+ const KEY_VARIABLES = "OBSERVE_APP_KEY and OBSERVE_APP_SECRET";
14
+ /**
15
+ * The one line the agent says at start-up when it has no key pair it can send
16
+ * with, so it sends nothing.
17
+ *
18
+ * Two situations look alike from inside the process and want opposite advice.
19
+ * A project fresh from `nest new` still holds the scaffolded placeholders:
20
+ * the fix is to connect it, which `npx @nestjs/observe link` does in one
21
+ * step. A deployed process with the same placeholders, or with nothing at
22
+ * all, is almost always a project that was connected on a laptop: link keeps
23
+ * the pair in `.env`, which is git-ignored and which `node dist/main` never
24
+ * loads, so production needs the two variables set where it runs. Telling
25
+ * that person to create an account sends them looking for something they
26
+ * already have, so under `NODE_ENV=production` the notice names the
27
+ * variables instead.
28
+ *
29
+ * @param scaffold the options still hold `nest new`'s placeholders
30
+ * @param unset which half of the pair is missing, when the options hold no
31
+ * placeholders but lack a key, a secret or both
32
+ */
33
+ export function describeMissingCredentials(input) {
34
+ if (input.production) {
35
+ const state = input.scaffold
36
+ ? "appKey and appSecret are still the placeholders from nest new"
37
+ : `${describeUnset(input.unset)} not set`;
38
+ return {
39
+ level: "warn",
40
+ message: `Observe is installed but sends nothing: ${state}. ` +
41
+ `Set ${KEY_VARIABLES} in this environment, then restart the process - ` +
42
+ `${LINK_COMMAND} keeps the pair in .env, which is not deployed. ` +
43
+ `The pair is on your project's API Keys page at ${SIGN_UP_URL}.`,
44
+ };
45
+ }
46
+ if (input.scaffold) {
47
+ return {
48
+ level: "log",
49
+ message: `Observe is installed but not connected yet: appKey and appSecret are still the placeholders from nest new, so no telemetry is sent. ` +
50
+ `Run ${LINK_COMMAND} in this project to connect it, or see what this app will look like first: ${DEMO_URL}`,
51
+ };
52
+ }
53
+ // Said as a warning: a project that names no placeholders was wired by
54
+ // hand, so a missing half is configuration that did not arrive.
55
+ return {
56
+ level: "warn",
57
+ message: `Observe is installed but sends nothing: ${describeUnset(input.unset)} not set, and the hosted collector accepts no telemetry without a key and a secret. ` +
58
+ `If they come from the environment, check that ${KEY_VARIABLES} reach this process, then restart it. ` +
59
+ `To get a pair, run ${LINK_COMMAND} or create one at ${SIGN_UP_URL}.`,
60
+ };
61
+ }
62
+ function describeUnset(unset = "both") {
63
+ return unset === "both"
64
+ ? "appKey and appSecret are"
65
+ : unset === "appKey"
66
+ ? "appKey is"
67
+ : "appSecret is";
68
+ }
@@ -2,6 +2,7 @@ import { DEGRADED_MESSAGE_PREFIX, PAUSED_MESSAGE_PREFIX, } from "./degraded-inge
2
2
  import { detachedObserveWorker } from "./detached-observe-worker.js";
3
3
  import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
4
4
  import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
5
+ import { readSdkVersion } from "../utils/sdk-version.util.js";
5
6
  /**
6
7
  * How the telemetry worker is put together, in one place.
7
8
  *
@@ -26,6 +27,7 @@ export function detachedWorkerData(input) {
26
27
  wireShapes: SECTION_SHAPES,
27
28
  degradedPrefix: DEGRADED_MESSAGE_PREFIX,
28
29
  pausedPrefix: PAUSED_MESSAGE_PREFIX,
30
+ sdkVersion: readSdkVersion(),
29
31
  };
30
32
  return { sharedBuffer: input.sharedBuffer, config };
31
33
  }
@@ -23,6 +23,11 @@ export interface DetachedWorkerConfig {
23
23
  degradedPrefix: string;
24
24
  /** `PAUSED_MESSAGE_PREFIX`, as data, for the same reason. */
25
25
  pausedPrefix: string;
26
+ /**
27
+ * This package's version (`readSdkVersion`), read on the main thread: the
28
+ * worker runs as eval'd source and cannot resolve a manifest of its own.
29
+ */
30
+ sdkVersion: string;
26
31
  }
27
32
  export interface DetachedWorkerData {
28
33
  sharedBuffer: SharedArrayBuffer;
@@ -68,6 +68,9 @@ describeRefusal) => {
68
68
  // config key would put a broken header on every batch. The value is
69
69
  // pinned by worker-degraded-reply.spec.ts.
70
70
  "x-observe-ingest-modes": "reduced, trimmed, paced, errors-only",
71
+ // Which agent sent the batch, so the collector can tell an application
72
+ // still on an old release that a newer one exists.
73
+ "x-observe-sdk-version": config.sdkVersion,
71
74
  };
72
75
  // Omitted rather than sent empty when unconfigured: a collector in
73
76
  // placeholder mode accepts an unauthenticated batch, and blank credentials
@@ -23,6 +23,7 @@ import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.serv
23
23
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
24
24
  import { parseDegradedMessage, parseOveragePauseReason, parsePausedMessage, } from "./degraded-ingest.protocol.js";
25
25
  import { detachedWorkerData, detachedWorkerSource, } from "./detached-observe-worker.assembly.js";
26
+ import { describeMissingCredentials, SIGN_UP_URL, } from "./credentials-notice.js";
26
27
  import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
27
28
  const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
28
29
  const MIN_RUNTIME_METRICS_INTERVAL = 30000; // 30 seconds
@@ -75,8 +76,6 @@ const MIN_FINAL_RUNTIME_WINDOW_MS = 10_000;
75
76
  */
76
77
  const SCAFFOLD_APP_KEY = "YOUR_APP_KEY";
77
78
  const SCAFFOLD_APP_SECRET = "YOUR_APP_SECRET";
78
- const DEMO_URL = "https://www.observe-demo.nestjs.com/dashboard";
79
- const SIGN_UP_URL = "https://observe.nestjs.com";
80
79
  const DASHBOARD_URL = `${SIGN_UP_URL}/dashboard`;
81
80
  let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
82
81
  observeAgentSharedBuffer;
@@ -133,23 +132,25 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
133
132
  // needs no key or secret, so a missing one is not worth a warning.
134
133
  this.logger.log("Observe is disabled (enabled: false): nothing is recorded or sent.");
135
134
  }
136
- else if (this.hasScaffoldCredentials) {
135
+ else if (this.hasScaffoldCredentials || this.lacksHostedCredentials) {
137
136
  // Nothing is sent, so there is no worker to start. The flush timer below
138
137
  // still runs and empties the buffer, which the instrumentation keeps
139
138
  // writing into either way.
140
- this.logger.log(`Observe is installed but not connected yet: appKey and appSecret are still the placeholders from nest new, so no telemetry is sent. ` +
141
- `See what this app will look like: ${DEMO_URL} - then create a free account at ${SIGN_UP_URL} for your own key and secret.`);
142
- }
143
- else if (this.lacksHostedCredentials) {
144
- // The same arrangement, said as a warning: this is a deployment missing
145
- // its configuration, not a project fresh from the generator.
146
- const unset = !this.options.appKey && !this.options.appSecret
147
- ? "appKey and appSecret are"
148
- : !this.options.appKey
149
- ? "appKey is"
150
- : "appSecret is";
151
- this.logger.warn(`Observe is installed but sends nothing: ${unset} not set, and the hosted collector accepts no telemetry without a key and a secret. ` +
152
- `If they come from the environment, check that both variables reach this process, then restart it. Create a key and secret at ${SIGN_UP_URL}.`);
139
+ const notice = describeMissingCredentials({
140
+ scaffold: this.hasScaffoldCredentials,
141
+ unset: !this.options.appKey && !this.options.appSecret
142
+ ? "both"
143
+ : !this.options.appKey
144
+ ? "appKey"
145
+ : "appSecret",
146
+ production: process.env.NODE_ENV === "production",
147
+ });
148
+ if (notice.level === "warn") {
149
+ this.logger.warn(notice.message);
150
+ }
151
+ else {
152
+ this.logger.log(notice.message);
153
+ }
153
154
  }
154
155
  else {
155
156
  this.initializeWorker();
@@ -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
+ }