@nestjs/observe 0.3.25 → 0.3.26

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 (94) hide show
  1. package/README.md +17 -0
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +196 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +7 -1
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +28 -3
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/project-files.d.ts +42 -1
  14. package/dist/cli/project-files.js +146 -7
  15. package/dist/cli/project-setup.d.ts +6 -0
  16. package/dist/cli/project-setup.js +14 -1
  17. package/dist/cli/wire-application.js +6 -0
  18. package/dist/custom-metrics/counter.d.ts +13 -2
  19. package/dist/custom-metrics/counter.js +33 -16
  20. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  21. package/dist/custom-metrics/finite-value.util.js +33 -1
  22. package/dist/custom-metrics/gauge.d.ts +2 -0
  23. package/dist/custom-metrics/gauge.js +41 -17
  24. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  25. package/dist/custom-metrics/label-values.util.js +51 -0
  26. package/dist/custom-metrics/summary.d.ts +23 -0
  27. package/dist/custom-metrics/summary.js +73 -2
  28. package/dist/instrument/create-instance-decorator.instrument.js +158 -96
  29. package/dist/interfaces/observe-options.interface.d.ts +3 -1
  30. package/dist/objectives/objectives.registry.js +12 -0
  31. package/dist/observe.module.js +119 -3
  32. package/dist/otlp/otlp-encoders.js +22 -5
  33. package/dist/otlp/otlp-span.mapper.js +7 -3
  34. package/dist/otlp/otlp-trace-exporter.service.js +63 -5
  35. package/dist/outgoing/http.integration.d.ts +8 -4
  36. package/dist/outgoing/http.integration.js +13 -6
  37. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  38. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  39. package/dist/outgoing/llm/llm-providers.js +72 -22
  40. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  41. package/dist/outgoing/llm/llm-usage.js +72 -25
  42. package/dist/outgoing/mssql.integration.js +16 -2
  43. package/dist/outgoing/mysql2.integration.js +17 -1
  44. package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
  45. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  46. package/dist/outgoing/pg.integration.d.ts +3 -2
  47. package/dist/outgoing/pg.integration.js +39 -11
  48. package/dist/outgoing/sql-statement.util.js +106 -14
  49. package/dist/outgoing/undici.integration.d.ts +13 -0
  50. package/dist/outgoing/undici.integration.js +68 -0
  51. package/dist/protocols/bull-observe-agent.service.js +2 -12
  52. package/dist/protocols/deferred-trace-completion.d.ts +9 -1
  53. package/dist/protocols/deferred-trace-completion.js +36 -6
  54. package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
  55. package/dist/protocols/graphql-observe-agent.service.js +166 -5
  56. package/dist/protocols/graphql-operation-parser.js +72 -18
  57. package/dist/protocols/http-observe-agent.service.d.ts +43 -9
  58. package/dist/protocols/http-observe-agent.service.js +177 -59
  59. package/dist/protocols/job-trace-runner.d.ts +35 -3
  60. package/dist/protocols/job-trace-runner.js +126 -29
  61. package/dist/protocols/queue-observe-agent.service.js +44 -20
  62. package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
  63. package/dist/protocols/rpc-observe-agent.service.js +187 -47
  64. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  65. package/dist/protocols/ws-observe-agent.service.js +226 -20
  66. package/dist/services/index.d.ts +1 -1
  67. package/dist/services/index.js +1 -1
  68. package/dist/services/logger-patcher.service.js +3 -4
  69. package/dist/services/operation-trace.registry.d.ts +45 -1
  70. package/dist/services/operation-trace.registry.js +418 -35
  71. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  72. package/dist/services/stdout-forwarder.service.js +288 -51
  73. package/dist/services/tracer.service.d.ts +23 -0
  74. package/dist/services/tracer.service.js +91 -5
  75. package/dist/utils/capture-request.util.d.ts +3 -1
  76. package/dist/utils/capture-request.util.js +100 -12
  77. package/dist/utils/fit-to-length.util.js +33 -10
  78. package/dist/utils/log-line.parser.d.ts +14 -0
  79. package/dist/utils/log-line.parser.js +7 -3
  80. package/dist/utils/log-redactor.d.ts +14 -0
  81. package/dist/utils/log-redactor.js +512 -61
  82. package/dist/utils/operation-state.util.d.ts +39 -0
  83. package/dist/utils/operation-state.util.js +50 -0
  84. package/dist/utils/redact-url-query.d.ts +26 -4
  85. package/dist/utils/redact-url-query.js +184 -32
  86. package/dist/utils/sensitive-keys.d.ts +4 -1
  87. package/dist/utils/sensitive-keys.js +48 -10
  88. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  89. package/dist/utils/shared-hook-slot.util.js +103 -0
  90. package/dist/utils/source-context.util.d.ts +8 -0
  91. package/dist/utils/source-context.util.js +88 -24
  92. package/dist/utils/source-map-resolver.util.js +8 -2
  93. package/dist/utils/trace-context.util.js +21 -6
  94. package/package.json +2 -2
@@ -22,13 +22,25 @@ export function encodeOtlpJson(resource, scope, spans) {
22
22
  ],
23
23
  });
24
24
  }
25
+ /**
26
+ * A string as a protobuf `string` field holds it, which is what the JSON
27
+ * encoding stands for. Half a surrogate pair names no character:
28
+ * `JSON.stringify` writes it as a `\ud83d` escape, and a receiver that reads
29
+ * JSON strings strictly refuses the whole request for it - every span of the
30
+ * batch, whoever's request put it there. It becomes U+FFFD, which is what
31
+ * the protobuf encoding's UTF-8 makes of it. With the `u` flag a whole pair
32
+ * is one character, outside the class.
33
+ */
34
+ function jsonText(value) {
35
+ return value.replace(/[\ud800-\udfff]/gu, "\ufffd");
36
+ }
25
37
  function jsonSpan(span) {
26
38
  return {
27
39
  traceId: span.traceId,
28
40
  spanId: span.spanId,
29
41
  ...(span.parentSpanId ? { parentSpanId: span.parentSpanId } : {}),
30
42
  ...(span.traceState ? { traceState: span.traceState } : {}),
31
- name: span.name,
43
+ name: jsonText(span.name),
32
44
  kind: span.kind,
33
45
  startTimeUnixNano: span.startTimeUnixNano.toString(),
34
46
  endTimeUnixNano: span.endTimeUnixNano.toString(),
@@ -37,23 +49,28 @@ function jsonSpan(span) {
37
49
  ? { droppedAttributesCount: span.droppedAttributesCount }
38
50
  : {}),
39
51
  ...(span.events.length > 0 ? { events: span.events.map(jsonEvent) } : {}),
40
- ...(span.status ? { status: span.status } : {}),
52
+ ...(span.status ? { status: jsonStatus(span.status) } : {}),
41
53
  flags: span.flags,
42
54
  };
43
55
  }
56
+ function jsonStatus({ code, message }) {
57
+ return message === undefined
58
+ ? { code }
59
+ : { code, message: jsonText(message) };
60
+ }
44
61
  function jsonEvent(event) {
45
62
  return {
46
63
  timeUnixNano: event.timeUnixNano.toString(),
47
- name: event.name,
64
+ name: jsonText(event.name),
48
65
  attributes: event.attributes.map(jsonKeyValue),
49
66
  };
50
67
  }
51
68
  function jsonKeyValue({ key, value }) {
52
- return { key, value: jsonAnyValue(value) };
69
+ return { key: jsonText(key), value: jsonAnyValue(value) };
53
70
  }
54
71
  function jsonAnyValue(value) {
55
72
  if (typeof value === "string") {
56
- return { stringValue: value };
73
+ return { stringValue: jsonText(value) };
57
74
  }
58
75
  if (typeof value === "boolean") {
59
76
  return { boolValue: value };
@@ -202,10 +202,14 @@ function appendNodeSpans(spans, node, traceId, parentSpanId, operationStartNs) {
202
202
  traceId,
203
203
  spanId: complete.spanId ? w3cSpanIdOf(complete.spanId) : randomSpanId(),
204
204
  parentSpanId,
205
- name: complete.name ??
206
- (client
205
+ // A manual span's name is whatever `createSpan` was given. Held to a
206
+ // string, as `toAttributes` holds the tags: anything else would fail
207
+ // the encoding, and with it the whole batch of every request's spans.
208
+ name: typeof complete.name === "string"
209
+ ? complete.name
210
+ : client
207
211
  ? complete.methodKey
208
- : `${complete.className}.${complete.methodKey}`),
212
+ : `${complete.className}.${complete.methodKey}`,
209
213
  kind: client ? SpanKind.CLIENT : SpanKind.INTERNAL,
210
214
  startTimeUnixNano: startNs,
211
215
  endTimeUnixNano: endNs,
@@ -57,6 +57,22 @@ const RETRY_MAX_MS = 60_000;
57
57
  const RETRY_AFTER_MAX_MS = 5 * 60_000;
58
58
  /** How long an idle connection to the receiver is kept for the next batch. */
59
59
  const KEEP_ALIVE_IDLE_MS = 30_000;
60
+ /**
61
+ * The most of a receiver's reply that is read. Only its first 300 characters
62
+ * are ever shown, and it is held and decoded on the application's thread:
63
+ * past this, the reading stops and the connection goes with it, and the
64
+ * status is acted on as it stands.
65
+ */
66
+ const MAX_REPLY_BYTES = 64 * 1024;
67
+ /**
68
+ * The most interim (1xx) replies one export sits through. Nothing it sends
69
+ * asks for one, and each is parsed on the application's thread: how many of
70
+ * them that thread works through is not the receiver's to choose. A proxy's
71
+ * few ahead of the answer still pass.
72
+ */
73
+ const MAX_INTERIM_REPLIES = 8;
74
+ /** The longest a timer runs; a longer delay would fire at once instead. */
75
+ const MAX_TIMER_MS = 2 ** 31 - 1;
60
76
  /**
61
77
  * Exports what the agent records as OpenTelemetry traces, over OTLP/HTTP, to
62
78
  * whatever receiver `otlp` names - a collector, Jaeger, Tempo, Honeycomb, a
@@ -407,9 +423,8 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
407
423
  },
408
424
  }, (response) => {
409
425
  const chunks = [];
410
- response.on("data", (chunk) => chunks.push(chunk));
411
- response.on("error", reject);
412
- response.on("end", () => {
426
+ let received = 0;
427
+ const settle = () => {
413
428
  const retryAfter = response.headers["retry-after"];
414
429
  resolve({
415
430
  status: response.statusCode ?? 0,
@@ -417,12 +432,55 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
417
432
  ? retryAfter[0]
418
433
  : retryAfter,
419
434
  contentType: response.headers["content-type"],
420
- body: Buffer.concat(chunks).toString("utf8"),
435
+ body: Buffer.concat(chunks, Math.min(received, MAX_REPLY_BYTES)).toString("utf8"),
421
436
  });
437
+ // A reply that ends before the batch has been written leaves a
438
+ // socket that is never pooled, timed out or closed again.
439
+ if (!request.writableFinished) {
440
+ request.destroy();
441
+ }
442
+ };
443
+ response.on("data", (chunk) => {
444
+ if (received >= MAX_REPLY_BYTES) {
445
+ return;
446
+ }
447
+ chunks.push(chunk);
448
+ received += chunk.length;
449
+ if (received >= MAX_REPLY_BYTES) {
450
+ response.destroy();
451
+ settle();
452
+ }
422
453
  });
454
+ response.on("error", reject);
455
+ response.on("end", settle);
423
456
  });
424
457
  request.on("error", reject);
425
- request.setTimeout(settings.timeoutMs, () => request.destroy(Object.assign(new Error(`no answer within ${settings.timeoutMs} ms`), { code: "ETIMEDOUT" })));
458
+ // A 101 with `Connection: Upgrade` is no response to Node: it emits
459
+ // only this, and destroys the socket without an error. Unheard, the
460
+ // export would never settle and every later one would wait behind it.
461
+ // No upgrade was asked for: it is a status like any other refusal.
462
+ request.on("upgrade", (response, socket) => {
463
+ socket.destroy();
464
+ resolve({
465
+ status: response.statusCode ?? 101,
466
+ retryAfter: undefined,
467
+ contentType: undefined,
468
+ body: "",
469
+ });
470
+ });
471
+ // A limit on the export as a whole, which is what `timeoutMillis` is.
472
+ // `request.setTimeout` measures silence on the socket instead and
473
+ // starts over with every byte: a receiver that went on writing -
474
+ // interim replies, a body a byte at a time - would hold this export,
475
+ // and every one queued behind it, open for as long as it liked.
476
+ const deadline = setTimeout(() => request.destroy(Object.assign(new Error(`no answer within ${settings.timeoutMs} ms`), { code: "ETIMEDOUT" })), Math.min(settings.timeoutMs, MAX_TIMER_MS));
477
+ request.on("close", () => clearTimeout(deadline));
478
+ let interimReplies = 0;
479
+ request.on("information", () => {
480
+ if (++interimReplies > MAX_INTERIM_REPLIES) {
481
+ request.destroy(new Error(`it sent more than ${MAX_INTERIM_REPLIES} interim (1xx) replies`));
482
+ }
483
+ });
426
484
  request.end(body);
427
485
  });
428
486
  }
@@ -45,12 +45,14 @@ export interface OutgoingTrace {
45
45
  /**
46
46
  * Spans for outbound HTTP, from the diagnostics channels Node publishes on its
47
47
  * own: `undici` - which is also what the global `fetch` runs on - and the
48
- * `node:http` client that axios, got and most SDKs sit on. Nothing is patched,
49
- * so there is no HTTP client to keep up with.
48
+ * `node:http` client that axios, got and most SDKs sit on. No HTTP client is
49
+ * patched, so there is none to keep up with.
50
50
  *
51
51
  * The handlers run synchronously inside the call that makes the request, which
52
52
  * is what puts the span under the right parent; the span is then carried to
53
- * the completion events on the request object itself.
53
+ * the completion events on the request object itself. An undici request a
54
+ * pool queued, or a redirect it follows, is created later, from a socket's
55
+ * events: `patchUndiciDispatch` puts it back in its caller's context first.
54
56
  *
55
57
  * Returns the function that removes every subscription.
56
58
  */
@@ -65,4 +67,6 @@ getRedactor?: () => LogRedactor | null,
65
67
  * `traceContext` not off, while the agent reports to NestJS Observe (see
66
68
  * `ObserveAgentSharedBuffer.isReporting`). Off unless given.
67
69
  */
68
- traceContextOn?: () => boolean): () => void;
70
+ traceContextOn?: () => boolean,
71
+ /** `http.queryParamsObfuscateRegex`, global: held to every recorded URL. */
72
+ obfuscateUrl?: RegExp): () => void;
@@ -10,12 +10,14 @@ const TRACESTATE_HEADER = "tracestate";
10
10
  /**
11
11
  * Spans for outbound HTTP, from the diagnostics channels Node publishes on its
12
12
  * own: `undici` - which is also what the global `fetch` runs on - and the
13
- * `node:http` client that axios, got and most SDKs sit on. Nothing is patched,
14
- * so there is no HTTP client to keep up with.
13
+ * `node:http` client that axios, got and most SDKs sit on. No HTTP client is
14
+ * patched, so there is none to keep up with.
15
15
  *
16
16
  * The handlers run synchronously inside the call that makes the request, which
17
17
  * is what puts the span under the right parent; the span is then carried to
18
- * the completion events on the request object itself.
18
+ * the completion events on the request object itself. An undici request a
19
+ * pool queued, or a redirect it follows, is created later, from a socket's
20
+ * events: `patchUndiciDispatch` puts it back in its caller's context first.
19
21
  *
20
22
  * Returns the function that removes every subscription.
21
23
  */
@@ -30,7 +32,9 @@ getRedactor = () => null,
30
32
  * `traceContext` not off, while the agent reports to NestJS Observe (see
31
33
  * `ObserveAgentSharedBuffer.isReporting`). Off unless given.
32
34
  */
33
- traceContextOn = () => false) {
35
+ traceContextOn = () => false,
36
+ /** `http.queryParamsObfuscateRegex`, global: held to every recorded URL. */
37
+ obfuscateUrl) {
34
38
  const spans = new WeakMap();
35
39
  /**
36
40
  * Span ids minted for a `node:http` request at `created`, where its
@@ -67,7 +71,7 @@ traceContextOn = () => false) {
67
71
  }
68
72
  const span = recorder.open("http", `${method} ${host}`, {
69
73
  "http.method": method,
70
- "http.url": redactUrlQuery(url, getRedactor()),
74
+ "http.url": redactUrlQuery(url, getRedactor(), obfuscateUrl),
71
75
  }, presetSpanId);
72
76
  if (span) {
73
77
  spans.set(request, span);
@@ -101,8 +105,11 @@ traceContextOn = () => false) {
101
105
  }
102
106
  if (sendsTraceContext() &&
103
107
  !hasUndiciHeader(request.headers, TRACEPARENT_HEADER)) {
108
+ // Sampled when the operation is recorded, as for node:http, not when
109
+ // this call got a span: one that opened as many spans as it may is
110
+ // still recorded, and its callee must not drop the trace.
104
111
  const span = spans.get(request);
105
- const headers = traceContextHeaders(trace, span?.spanId, span !== undefined);
112
+ const headers = traceContextHeaders(trace, span?.spanId, recorder.isRecording());
106
113
  request.addHeader(TRACEPARENT_HEADER, headers.traceparent);
107
114
  if (headers.tracestate &&
108
115
  !hasUndiciHeader(request.headers, TRACESTATE_HEADER)) {
@@ -104,6 +104,21 @@ export function activateLlmFetchObserver(recorder, options = {}) {
104
104
  }
105
105
  };
106
106
  }
107
+ /**
108
+ * Cancels a provider's stream once the stream handed to the caller in its
109
+ * place can no longer be read. undici does this for an unread response it
110
+ * created, but not for one whose body is locked, as the provider's is once
111
+ * it is read through here: a reply the application drops would otherwise
112
+ * hold its socket, its buffered body and its span for good.
113
+ */
114
+ const abandonedBodies = new FinalizationRegistry((release) => {
115
+ try {
116
+ release();
117
+ }
118
+ catch {
119
+ /* thrown from here it would be an uncaught exception in the host */
120
+ }
121
+ });
107
122
  async function observeCall(original, input, init, call) {
108
123
  const startedAt = performance.now();
109
124
  const holder = {};
@@ -150,6 +165,8 @@ async function observeCall(original, input, init, call) {
150
165
  return;
151
166
  }
152
167
  tagged = true;
168
+ // Read to its end, failed or cancelled: nothing is left to release.
169
+ abandonedBodies.unregister(holder);
153
170
  let usage = {};
154
171
  try {
155
172
  usage = reader.finish();
@@ -164,6 +181,21 @@ async function observeCall(original, input, init, call) {
164
181
  // go on generating - and billing - a completion nobody reads.
165
182
  const source = response.body.getReader();
166
183
  const body = new ReadableStream({
184
+ start(controller) {
185
+ // Failed between two reads - the call's signal aborted, the
186
+ // connection reset: the caller hears of it now, as from plain
187
+ // `fetch`, not at a read that may never come. A stream piped on
188
+ // (`Readable.fromWeb`) stops reading while its buffer is full and
189
+ // waits on `closed` to hang up. A normal end or a cancel fulfils
190
+ // `closed`, and `error` does nothing to a stream already done.
191
+ // Held weakly: `source` is reachable from `abandonedBodies`, and so
192
+ // is what waits on it - a strong hold here would keep `body` alive.
193
+ const handle = new WeakRef(controller);
194
+ source.closed.catch((error) => {
195
+ finish();
196
+ handle.deref()?.error(error);
197
+ });
198
+ },
167
199
  async pull(controller) {
168
200
  let chunk;
169
201
  try {
@@ -192,7 +224,36 @@ async function observeCall(original, input, init, call) {
192
224
  return source.cancel(reason);
193
225
  },
194
226
  }, { highWaterMark: 0 });
195
- return rewrap(response, body);
227
+ let wrapped;
228
+ try {
229
+ wrapped = rewrap(response, body);
230
+ }
231
+ catch {
232
+ // The `Response` constructor refuses what `fetch` takes off the wire: a
233
+ // status past 599, a reason phrase with a control character or past
234
+ // Latin-1. The caller gets the reply as it came, tagged without its
235
+ // usage. Nothing has been read from it - `pull` runs on demand - so its
236
+ // body is whole once the lock is given back. Tagged first: giving the
237
+ // lock back rejects `closed`, which `start` above would act on.
238
+ tagged = true;
239
+ source.releaseLock();
240
+ tag({}, stream);
241
+ return response;
242
+ }
243
+ // Watching `body`, not the response: a caller that keeps only the body,
244
+ // or a clone, can still read it. Nothing registered may reach `body`, or
245
+ // it would never be collected.
246
+ abandonedBodies.register(body, () => {
247
+ try {
248
+ finish();
249
+ }
250
+ finally {
251
+ source
252
+ .cancel("Response object has been garbage collected")
253
+ .catch(() => undefined);
254
+ }
255
+ }, holder);
256
+ return wrapped;
196
257
  }
197
258
  /** The same response, reading through `body`. */
198
259
  function rewrap(response, body) {
@@ -8,13 +8,25 @@
8
8
  */
9
9
  /** The provider a call to `host` goes to, or undefined when it is not one. */
10
10
  export declare function llmProviderForHost(host: string, extraHosts?: ReadonlySet<string>): string | undefined;
11
+ /**
12
+ * The `model` of the outermost object of a JSON document, or of as much of
13
+ * one as `text` holds - and nothing for text that does not open with `{`.
14
+ *
15
+ * A scan rather than `JSON.parse`, which a cut-off document would fail, and
16
+ * rather than a search for `"model":`, which finds that key at any depth: a
17
+ * tool call's input, a tool result or a JSON-mode completion can carry one,
18
+ * and what it holds is the prompt's, not the model's. Strings are skipped
19
+ * whole, so a brace or a key inside one counts for nothing. Linear, and done
20
+ * at the first `model` key of the outermost object - where clients put it.
21
+ */
22
+ export declare function topLevelModel(text: string): string | undefined;
11
23
  /**
12
24
  * The model a JSON request body names, read from its first 64 KB.
13
25
  *
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.
26
+ * Read with `topLevelModel`: the body is the application's prompt, often far
27
+ * larger than the one field wanted, and every client puts `model` near the
28
+ * top. Bodies that are streams or forms are not read at all - reading them
29
+ * would consume what the request is about to send.
18
30
  */
19
31
  export declare function modelFromRequestBody(body: unknown): string | undefined;
20
32
  /**
@@ -6,21 +6,25 @@
6
6
  * SDK, LangChain and a hand-written `fetch` all end in the same request to the
7
7
  * same host, so a host list covers every client without knowing any of them.
8
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
- };
9
+ /**
10
+ * Exact hosts, each with the provider name the dashboard groups by. A `Map`,
11
+ * not an object literal: looked up by the host of any outgoing call, and a
12
+ * host spelt `constructor` or `__proto__` found an inherited member there.
13
+ */
14
+ const EXACT_HOSTS = new Map([
15
+ ["api.openai.com", "openai"],
16
+ ["api.anthropic.com", "anthropic"],
17
+ ["generativelanguage.googleapis.com", "google"],
18
+ ["api.mistral.ai", "mistral"],
19
+ ["api.groq.com", "groq"],
20
+ ["openrouter.ai", "openrouter"],
21
+ ["api.together.xyz", "together"],
22
+ ["api.deepseek.com", "deepseek"],
23
+ ["api.x.ai", "xai"],
24
+ ["api.cohere.ai", "cohere"],
25
+ ["api.cohere.com", "cohere"],
26
+ ["api.perplexity.ai", "perplexity"],
27
+ ]);
24
28
  /** Hosts that carry a tenant or a region in a subdomain. */
25
29
  const HOST_PATTERNS = [
26
30
  [/^[a-z0-9-]+\.openai\.azure\.com$/, "azure-openai"],
@@ -32,7 +36,7 @@ const HOST_PATTERNS = [
32
36
  export function llmProviderForHost(host, extraHosts = new Set()) {
33
37
  const normalized = host.toLowerCase();
34
38
  const hostname = normalized.replace(/:\d+$/, "");
35
- const exact = EXACT_HOSTS[hostname];
39
+ const exact = EXACT_HOSTS.get(hostname);
36
40
  if (exact) {
37
41
  return exact;
38
42
  }
@@ -48,14 +52,60 @@ export function llmProviderForHost(host, extraHosts = new Set()) {
48
52
  }
49
53
  /** Most of a request body read for its `model` field. Prompts can be megabytes. */
50
54
  const MODEL_SCAN_BYTES = 64 * 1024;
51
- const MODEL_FIELD = /"model"\s*:\s*"([^"\\]{1,128})"/;
55
+ /** What follows a `"model"` key: the value, when it is a short string. */
56
+ const MODEL_VALUE = /\s*:\s*"([^"\\]{1,128})"/y;
57
+ /**
58
+ * The `model` of the outermost object of a JSON document, or of as much of
59
+ * one as `text` holds - and nothing for text that does not open with `{`.
60
+ *
61
+ * A scan rather than `JSON.parse`, which a cut-off document would fail, and
62
+ * rather than a search for `"model":`, which finds that key at any depth: a
63
+ * tool call's input, a tool result or a JSON-mode completion can carry one,
64
+ * and what it holds is the prompt's, not the model's. Strings are skipped
65
+ * whole, so a brace or a key inside one counts for nothing. Linear, and done
66
+ * at the first `model` key of the outermost object - where clients put it.
67
+ */
68
+ export function topLevelModel(text) {
69
+ let index = text.search(/\S/);
70
+ if (index === -1 || text[index] !== "{") {
71
+ return undefined;
72
+ }
73
+ let depth = 0;
74
+ for (; index < text.length; index++) {
75
+ const char = text[index];
76
+ if (char === '"') {
77
+ const start = index;
78
+ for (index++; index < text.length && text[index] !== '"'; index++) {
79
+ if (text[index] === "\\") {
80
+ index++;
81
+ }
82
+ }
83
+ if (depth === 1 &&
84
+ index - start === 6 &&
85
+ text.startsWith('"model"', start)) {
86
+ MODEL_VALUE.lastIndex = index + 1;
87
+ const value = MODEL_VALUE.exec(text);
88
+ if (value) {
89
+ return value[1];
90
+ }
91
+ }
92
+ }
93
+ else if (char === "{" || char === "[") {
94
+ depth++;
95
+ }
96
+ else if ((char === "}" || char === "]") && --depth === 0) {
97
+ return undefined;
98
+ }
99
+ }
100
+ return undefined;
101
+ }
52
102
  /**
53
103
  * The model a JSON request body names, read from its first 64 KB.
54
104
  *
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.
105
+ * Read with `topLevelModel`: the body is the application's prompt, often far
106
+ * larger than the one field wanted, and every client puts `model` near the
107
+ * top. Bodies that are streams or forms are not read at all - reading them
108
+ * would consume what the request is about to send.
59
109
  */
60
110
  export function modelFromRequestBody(body) {
61
111
  let text;
@@ -68,7 +118,7 @@ export function modelFromRequestBody(body) {
68
118
  else if (body instanceof ArrayBuffer) {
69
119
  text = new TextDecoder().decode(new Uint8Array(body, 0, Math.min(body.byteLength, MODEL_SCAN_BYTES)));
70
120
  }
71
- return text ? MODEL_FIELD.exec(text)?.[1] : undefined;
121
+ return text ? topLevelModel(text) : undefined;
72
122
  }
73
123
  /**
74
124
  * The model a URL names, for the providers that put it in the path rather
@@ -1,7 +1,3 @@
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
1
  /** What one call consumed, as far as the response said. */
6
2
  export interface LlmUsage {
7
3
  /** The model that answered - more precise than the one asked for. */
@@ -35,10 +31,14 @@ export declare function usageFromDocument(document: unknown): LlmUsage;
35
31
  * A larger body - a long completion, a batch of embeddings - is not kept: its
36
32
  * first and last 32 KB are, and the usage is matched out of those. Every
37
33
  * provider writes `usage` after the content and `model` before it.
34
+ *
35
+ * The bytes are copied, not the chunks kept: a chunk object costs a few
36
+ * hundred bytes of heap whatever it holds, and the sender decides how the
37
+ * body is cut - one byte at a time, a 2 MB body would be held a hundred
38
+ * times over.
38
39
  */
39
40
  export declare class JsonUsageReader {
40
- private readonly chunks;
41
- private size;
41
+ private body;
42
42
  private head;
43
43
  private tail;
44
44
  push(chunk: Uint8Array): void;
@@ -50,6 +50,11 @@ export declare class JsonUsageReader {
50
50
  * Only `data:` lines that can carry usage or a model are parsed - the first
51
51
  * event, and any that mention `usage` - so a long stream of text deltas costs
52
52
  * a substring search per line rather than a parse.
53
+ *
54
+ * A line still arriving is held as bytes, copied, and decoded once it is
55
+ * whole: grown a chunk at a time as a string, a line sent a byte at a time
56
+ * would be a million string objects. A line feed is never part of another
57
+ * UTF-8 character, so the bytes split into lines as the text does.
53
58
  */
54
59
  export declare class SseUsageReader {
55
60
  private readonly now;