metergraph 0.6.10 → 0.6.13

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
@@ -1,8 +1,19 @@
1
1
  # metergraph (TypeScript)
2
2
 
3
- Zero-runtime-dependency capture for OpenAI, Anthropic, and Gemini clients plus
4
- provider-independent Vercel AI SDK language models on Node 18+, including AWS
5
- Lambda. Worker-style `waitUntil` hooks are present but are not part of the v1
3
+ See where your agentic AI application's LLM spend comes from. Attribute usage
4
+ to functions, agents, and workflows without changing provider call sites, then
5
+ send it to Metergraph Cloud or your self-hosted Metergraph server.
6
+
7
+ [Metergraph](https://www.metergraph.dev/) helps teams understand and optimize
8
+ agentic AI applications. This open-source, zero-runtime-dependency package
9
+ provides function-level LLM cost attribution for OpenAI, Anthropic, and Gemini
10
+ clients plus provider-independent Vercel AI SDK language models. Paid
11
+ Metergraph builds on that attribution with experimentation and optimization
12
+ across models, prompts, tools, retrieval, context, batching, and caching. This
13
+ package captures and attributes usage; it does not run experiments or optimize
14
+ your application.
15
+
16
+ The package runs on Node 18+, including AWS Lambda. Worker-style `waitUntil` hooks are present but are not part of the v1
6
17
  public-package qualification contract.
7
18
 
8
19
  Metergraph supports OpenAI JavaScript SDK majors 4 through 7. The current
@@ -176,6 +187,21 @@ inference while iterating a wrapped `client.messages.batches.results()` result.
176
187
  Consume results inside `route()` so the asynchronous batch retains its product
177
188
  route. Job-management polls are deliberately not counted as model calls.
178
189
 
190
+ OpenAI Responses created with `background: true` are recorded once, when a
191
+ wrapped `client.responses.retrieve()` or `cancel()` first returns a terminal
192
+ status (`completed`, `failed`, `cancelled` or `incomplete`), with that
193
+ response's usage and output. A `retrieve(id, { stream: true })` or
194
+ `responses.stream({ response_id })` resume is observed through its terminal
195
+ `response.*` event when the stream is iterated directly; `tee()` and
196
+ `toReadableStream()` copies are not observed. Polls that still report
197
+ `queued` or `in_progress` add no rows, and latency runs from `create` to the
198
+ observed terminal response. A background response whose terminal status the
199
+ process never observes is recorded at `shutdown()` with status `abandoned`
200
+ and unknown usage, never as a completed call with zero tokens. Only retrieves
201
+ made through the same wrapped client in the same process are observed; a
202
+ client derived with `withOptions()` or polling from a different process leaves
203
+ the call to be recorded as `abandoned`.
204
+
179
205
  ## Batch-first execution (opt-in)
180
206
 
181
207
  `batchFirst()` is a separate, explicitly opt-in code path from `wrap()`/capture: submit one request through a provider's Batch API, wait up to a caller-chosen deadline, and fall back to exactly one direct call if the batch hasn't finished in time.
@@ -220,7 +246,7 @@ codebase you want instrumented:
220
246
 
221
247
  ```text
222
248
  Instrument this codebase's LLM API costs with the `metergraph` npm package
223
- (https://github.com/PioneerSquareLabs/metergraphsdk): npm install metergraph,
249
+ (https://github.com/metergraph/metergraphsdk): npm install metergraph,
224
250
  then wrap every new OpenAI(), new Anthropic(), and new GoogleGenAI()
225
251
  construction in place, e.g. const client = mg.wrap(new OpenAI()) after
226
252
  import * as mg from "metergraph". wrap() returns the same client and
package/dist/capture.d.ts CHANGED
@@ -44,6 +44,7 @@ export declare class CaptureRuntime {
44
44
  ttftMs?: number;
45
45
  responseText?: string;
46
46
  responseChunks?: unknown[];
47
+ evidenceChunks?: unknown[];
47
48
  }): void;
48
49
  }
49
50
  export {};
package/dist/capture.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CaptureRuntime = exports.DEFAULT_TEXT_MAX_BYTES = void 0;
4
4
  exports.chunkText = chunkText;
5
+ const model_evidence_js_1 = require("./model-evidence.js");
5
6
  const node_crypto_1 = require("node:crypto");
6
7
  const context_js_1 = require("./context.js");
7
8
  const gateway_js_1 = require("./gateway.js");
@@ -773,6 +774,8 @@ class CaptureRuntime {
773
774
  status_code: statusCode,
774
775
  finish_reason: finishReason,
775
776
  finish_reason_raw: finishReasonRaw,
777
+ ...(0, model_evidence_js_1.modelEvidence)({ response, error: extra.error, refusalSignal: state.context.refusalSignal,
778
+ stream_chunks: extra.evidenceChunks ?? extra.responseChunks, stream_complete: extra.stream === true && extra.error === undefined && extra.status !== "error" && extra.status !== "abandoned" }),
776
779
  session_id: state.context.sessionId,
777
780
  conversation_id: state.context.sessionId,
778
781
  trace_id: state.traceId,
package/dist/context.d.ts CHANGED
@@ -7,6 +7,7 @@ export interface CaptureContext {
7
7
  unitName?: string;
8
8
  unitCount?: number;
9
9
  captureText?: boolean;
10
+ refusalSignal?: boolean;
10
11
  funcName?: string;
11
12
  traceId?: string;
12
13
  traceName?: string;
@@ -24,6 +25,8 @@ export interface TraceOptions {
24
25
  captureText?: boolean;
25
26
  }
26
27
  export interface ContextOptions {
28
+ /** Scoped observation; an explicit native refusal takes precedence. */
29
+ refusalSignal?: boolean;
27
30
  sessionId?: string;
28
31
  tags?: Record<string, unknown>;
29
32
  }
package/dist/context.js CHANGED
@@ -31,6 +31,7 @@ function withContext(options, fn) {
31
31
  const child = {
32
32
  ...parent,
33
33
  sessionId: options.sessionId ?? parent.sessionId,
34
+ refusalSignal: options.refusalSignal ?? parent.refusalSignal,
34
35
  tags: { ...parent.tags, ...normalizeTags(options.tags ?? {}) },
35
36
  };
36
37
  return storage.run(child, fn);
package/dist/index.js CHANGED
@@ -93,7 +93,7 @@ function init(options = {}) {
93
93
  initialized = true;
94
94
  if (!repoConfig && !warnedNoRepository) {
95
95
  warnedNoRepository = true;
96
- console.warn("Metergraph repository identity is not configured; set init({ repository: \"owner/repository\" }), METERGRAPH_REPOSITORY, or provide .metergraph/config.json. Continuing with legacy ingestion.");
96
+ console.warn("Metergraph is capturing calls normally. Repository identity is optional and not set, so traces are not linked to a source repository. To link them, commit .metergraph/config.json containing {\"repository\": \"owner/name\"}, set METERGRAPH_REPOSITORY=owner/name, pass init({ repository: \"owner/name\" }), or run `metergraph setup` in the project.");
97
97
  }
98
98
  sessionManager = repoConfig
99
99
  ? new session_js_1.SessionManager(token, ingestUrl, repoConfig.repository, version_js_1.SDK_VERSION)
@@ -179,6 +179,14 @@ async function flush(timeoutMs = 3_000) {
179
179
  return transport?.flush(timeoutMs) ?? true;
180
180
  }
181
181
  async function shutdown() {
182
+ // Background responses whose final result was never retrieved are recorded
183
+ // as abandoned before the transport drains, never as zero usage.
184
+ try {
185
+ (0, wrap_js_1.finishBackgroundCalls)();
186
+ }
187
+ catch {
188
+ // fail-open
189
+ }
182
190
  config?.stop();
183
191
  config = undefined;
184
192
  await transport?.shutdown();
@@ -0,0 +1,15 @@
1
+ export declare function modelEvidence(input: {
2
+ response?: unknown;
3
+ error?: unknown;
4
+ stream_chunks?: unknown[];
5
+ stream_complete?: boolean;
6
+ refusalSignal?: boolean;
7
+ }): {
8
+ otel?: {
9
+ finish_reasons: string[];
10
+ } | undefined;
11
+ http_status_code: number | null;
12
+ error_code: string | null;
13
+ refusal_signal: boolean | null;
14
+ response_received: boolean | null;
15
+ };
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.modelEvidence = modelEvidence;
4
+ /** Content-free native facts; receivers own outcome classification. */
5
+ function get(value, key) {
6
+ return value && typeof value === "object" ? value[key] : undefined;
7
+ }
8
+ function items(value) { return Array.isArray(value) ? value : []; }
9
+ function text(value) { return typeof value === "string" && value.trim().length > 0 && value.length <= 256; }
10
+ function inspect(value) {
11
+ const reasons = [], coverage = [];
12
+ let positive = false, received = false;
13
+ const reason = (raw) => { if (text(raw))
14
+ reasons.push(raw); };
15
+ reason(get(value, "finish_reason"));
16
+ reason(get(value, "stop_reason"));
17
+ const camelFinish = get(value, "finishReason");
18
+ reason(get(camelFinish, "raw") ?? get(camelFinish, "unified") ?? camelFinish);
19
+ if (["refusal", "response.refusal.delta", "response.refusal.done"].includes(String(get(value, "type"))))
20
+ positive = true;
21
+ for (const part of [get(value, "part"), get(value, "content_block")])
22
+ positive ||= get(part, "type") === "refusal";
23
+ const delta = get(value, "delta");
24
+ reason(get(delta, "stop_reason"));
25
+ positive ||= Boolean(get(delta, "refusal"));
26
+ const choices = get(value, "choices");
27
+ if (Array.isArray(choices)) {
28
+ received = true;
29
+ for (const choice of choices) {
30
+ const finish = get(choice, "finish_reason"), message = get(choice, "message");
31
+ reason(finish);
32
+ positive ||= Boolean(get(message, "refusal")) || Boolean(get(get(choice, "delta"), "refusal")) || items(get(message, "content")).some(part => get(part, "type") === "refusal");
33
+ coverage.push(message != null && text(finish) && (get(message, "content") != null || get(message, "tool_calls") != null || typeof message === "object" && "refusal" in message));
34
+ }
35
+ }
36
+ const content = get(value, "content");
37
+ if (Array.isArray(content)) {
38
+ positive ||= content.some(part => get(part, "type") === "refusal");
39
+ if (text(get(value, "stop_reason"))) {
40
+ received = true;
41
+ coverage.push(content.length > 0 && content.every(part => ["text", "thinking", "redacted_thinking", "tool_use", "refusal"].includes(String(get(part, "type")))));
42
+ }
43
+ }
44
+ const output = get(value, "output");
45
+ if (Array.isArray(output)) {
46
+ received = true;
47
+ for (const item of output) {
48
+ const parts = items(get(item, "content"));
49
+ positive ||= get(item, "type") === "refusal" || parts.some(part => get(part, "type") === "refusal");
50
+ coverage.push(["completed", "incomplete"].includes(String(get(value, "status"))) && (get(item, "type") === "message" && parts.length > 0 && parts.every(part => ["output_text", "refusal"].includes(String(get(part, "type")))) ||
51
+ ["function_call", "reasoning"].includes(String(get(item, "type")))));
52
+ }
53
+ }
54
+ reason(get(get(value, "incomplete_details"), "reason"));
55
+ const feedback = get(value, "promptFeedback") ?? get(value, "prompt_feedback");
56
+ if (feedback != null) {
57
+ received = true;
58
+ reason(get(feedback, "blockReason") ?? get(feedback, "block_reason"));
59
+ }
60
+ const candidates = get(value, "candidates");
61
+ if (Array.isArray(candidates)) {
62
+ received = true;
63
+ for (const candidate of candidates) {
64
+ const finish = get(candidate, "finishReason") ?? get(candidate, "finish_reason");
65
+ reason(finish);
66
+ const parts = items(get(get(candidate, "content"), "parts"));
67
+ positive ||= parts.some(part => get(part, "type") === "refusal");
68
+ coverage.push(text(finish) && parts.length > 0);
69
+ }
70
+ }
71
+ return { positive, complete: coverage.length > 0 && coverage.every(Boolean), received, reasons };
72
+ }
73
+ function modelEvidence(input) {
74
+ const { response, error } = input;
75
+ const raw = get(error, "status_code") ?? get(error, "status") ?? get(error, "statusCode")
76
+ ?? get(get(error, "response"), "status_code") ?? get(response, "status_code");
77
+ const status = typeof raw === "number" && Number.isInteger(raw) && raw >= 100 && raw <= 599 ? raw : null;
78
+ let payload = get(error, "error") ?? get(error, "body") ?? error;
79
+ payload = get(payload, "error") ?? payload;
80
+ const code = get(payload, "code") ?? get(error, "code");
81
+ const safeInspect = (value) => {
82
+ try {
83
+ return inspect(value);
84
+ }
85
+ catch {
86
+ return { positive: false, complete: false, received: false, reasons: [] };
87
+ }
88
+ };
89
+ const native = safeInspect(response);
90
+ for (const chunk of input.stream_chunks ?? []) {
91
+ for (const value of [chunk, get(chunk, "response")]) {
92
+ const inspected = safeInspect(value);
93
+ native.positive ||= inspected.positive;
94
+ native.received ||= inspected.received;
95
+ native.reasons.push(...inspected.reasons);
96
+ }
97
+ }
98
+ const signal = native.positive ? true : typeof input.refusalSignal === "boolean" ? input.refusalSignal :
99
+ native.complete && (input.stream_chunks === undefined || input.stream_complete) ? false : null;
100
+ return {
101
+ http_status_code: status, error_code: text(code) ? code : null,
102
+ refusal_signal: signal, response_received: native.received || native.positive ? true : null,
103
+ ...(native.reasons.length ? { otel: { finish_reasons: native.reasons } } : {}),
104
+ };
105
+ }
package/dist/template.js CHANGED
@@ -82,10 +82,21 @@ function normalized(value) {
82
82
  }
83
83
  if (typeof value !== "string")
84
84
  return value;
85
+ // Every pattern here must run in time linear in the text: a request can
86
+ // carry megabytes in one string (an inline image) and this runs inside the
87
+ // wrapped call. The email local part is capped at 64 characters, the most
88
+ // RFC 5321 allows, and the domain commits to its first dot instead of
89
+ // retrying from every dot. It matches the same strings as the former
90
+ // `[^\s@]+@[^\s@]+\.[^\s@]+\b`, which rescanned a run with no whitespace
91
+ // or "@" from every word boundary and was quadratic on a base64 image.
92
+ // Inline images differ on every call, so for fingerprinting they are a URL.
93
+ // The data URL's media type is bounded and may not hold ":", which a media
94
+ // type never does, so a "data:" that is not a data URL fails within a few
95
+ // characters instead of scanning the rest of the string from every "data:".
85
96
  return value
86
97
  .replace(/\b[0-9a-f]{8}-[0-9a-f-]{27,}\b/gi, "<uuid>")
87
- .replace(/\b[^\s@]+@[^\s@]+\.[^\s@]+\b/g, "<email>")
88
- .replace(/\bhttps?:\/\/\S+/g, "<url>")
98
+ .replace(/\b[^\s@]{1,64}@[^\s@][^\s@.]*\.[^\s@]+\b/g, "<email>")
99
+ .replace(/\b(?:https?:\/\/|data:[^\s,:]{0,255};base64,)\S+/g, "<url>")
89
100
  .replace(/\b[A-Za-z0-9_-]{24,}\b/g, "<token>")
90
101
  .replace(/(^|[^A-Za-z])[-+]?\d+(?:\.\d+)?(?=$|[^A-Za-z])/g, "$1<n>")
91
102
  .replace(/\s+/g, " ")
package/dist/vercel-ai.js CHANGED
@@ -81,10 +81,12 @@ function wrapStreamResult(result, capture, state, started) {
81
81
  let finishPart;
82
82
  let streamError;
83
83
  const content = [];
84
+ const evidenceChunks = [];
84
85
  const responseMetadata = {};
85
86
  // Telemetry inspection of one part. Reads part fields, so callers run it
86
87
  // fail-open; a fault must not block delivery or become a stream error.
87
88
  const observe = (part) => {
89
+ evidenceChunks.push(part);
88
90
  if (firstOutputAt === undefined && outputChunk(part))
89
91
  firstOutputAt = performance.now();
90
92
  const delta = (0, capture_js_1.chunkText)(part);
@@ -137,6 +139,7 @@ function wrapStreamResult(result, capture, state, started) {
137
139
  status,
138
140
  stream: true,
139
141
  responseText: text,
142
+ evidenceChunks,
140
143
  ttftMs: firstOutputAt === undefined ? undefined : Math.round(firstOutputAt - started),
141
144
  });
142
145
  };
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.6.10";
1
+ export declare const SDK_VERSION = "0.6.13";
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SDK_VERSION = void 0;
4
- exports.SDK_VERSION = "0.6.10";
4
+ exports.SDK_VERSION = "0.6.13";
package/dist/wrap.d.ts CHANGED
@@ -3,6 +3,8 @@ type AnyRecord = Record<PropertyKey, any>;
3
3
  export declare function setCaptureRuntime(value?: CaptureRuntime): void;
4
4
  /** @internal Used by optional framework adapters without adding runtime dependencies. */
5
5
  export declare function getCaptureRuntime(): CaptureRuntime | undefined;
6
+ /** Record every held background call whose final result was never observed. */
7
+ export declare function finishBackgroundCalls(status?: string): number;
6
8
  export interface Seam {
7
9
  path: string;
8
10
  method: string;
package/dist/wrap.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.wrapClient = exports.SEAM_TABLES = exports.GOOGLE_SEAMS = exports.ANTHROPIC_SEAMS = exports.OPENAI_SEAMS = void 0;
4
4
  exports.setCaptureRuntime = setCaptureRuntime;
5
5
  exports.getCaptureRuntime = getCaptureRuntime;
6
+ exports.finishBackgroundCalls = finishBackgroundCalls;
6
7
  exports.wrap = wrap;
7
8
  const capture_js_1 = require("./capture.js");
8
9
  const context_js_1 = require("./context.js");
@@ -405,6 +406,153 @@ function preserveProviderPromise(target, complete, fail) {
405
406
  },
406
407
  });
407
408
  }
409
+ // Background Responses ({ background: true }) return a queued or in-progress
410
+ // response from create(); output and usage arrive on a later retrieve() or
411
+ // cancel(). The capture is held until the client observes a terminal status,
412
+ // then recorded once from that response. A held call the client never sees
413
+ // finish is recorded as "abandoned" at shutdown (or when the bound is
414
+ // exceeded), so it is never stored as a completed call with zero usage.
415
+ const BACKGROUND_PENDING = new Set(["queued", "in_progress"]);
416
+ const BACKGROUND_TERMINAL = new Set(["completed", "failed", "cancelled", "incomplete"]);
417
+ const BACKGROUND_MAX_PENDING = 1024;
418
+ const backgroundCalls = new Map();
419
+ function shouldHoldBackground(endpoint, request, response) {
420
+ try {
421
+ return (endpoint === "responses" || endpoint === "responses.parse")
422
+ && BACKGROUND_PENDING.has(get(response, "status"))
423
+ && (request.background === true || get(response, "background") === true)
424
+ && typeof get(response, "id") === "string"
425
+ && get(response, "id") !== "";
426
+ }
427
+ catch {
428
+ return false;
429
+ }
430
+ }
431
+ function holdBackground(capture, state, response) {
432
+ const id = get(response, "id");
433
+ backgroundCalls.delete(id);
434
+ backgroundCalls.set(id, { capture, state, last: response });
435
+ while (backgroundCalls.size > BACKGROUND_MAX_PENDING) {
436
+ const [oldest, held] = backgroundCalls.entries().next().value;
437
+ backgroundCalls.delete(oldest);
438
+ finishCapture(held.capture, held.state, held.last, { status: "abandoned" });
439
+ }
440
+ }
441
+ function observeBackground(response) {
442
+ try {
443
+ const id = get(response, "id");
444
+ if (typeof id !== "string")
445
+ return;
446
+ const held = backgroundCalls.get(id);
447
+ if (!held)
448
+ return;
449
+ const status = get(response, "status");
450
+ if (BACKGROUND_PENDING.has(status)) {
451
+ held.last = response;
452
+ return;
453
+ }
454
+ if (!BACKGROUND_TERMINAL.has(status))
455
+ return;
456
+ backgroundCalls.delete(id);
457
+ finishCapture(held.capture, held.state, response);
458
+ }
459
+ catch {
460
+ // Observation is telemetry-only and fail-open.
461
+ }
462
+ }
463
+ function observeBackgroundEvent(event) {
464
+ try {
465
+ const type = get(event, "type");
466
+ if (typeof type === "string" && type.startsWith("response.")) {
467
+ const response = get(event, "response");
468
+ if (response)
469
+ observeBackground(response);
470
+ }
471
+ }
472
+ catch {
473
+ // fail-open
474
+ }
475
+ }
476
+ // Pass a resumed background stream through unchanged, observing its response
477
+ // events so the terminal one finishes the held call.
478
+ function observedBackgroundStream(stream) {
479
+ return new Proxy(stream, {
480
+ get(target, property, receiver) {
481
+ if (property === Symbol.asyncIterator) {
482
+ return async function* () {
483
+ for await (const event of target) {
484
+ observeBackgroundEvent(event);
485
+ yield event;
486
+ }
487
+ };
488
+ }
489
+ const value = Reflect.get(target, property, receiver);
490
+ return typeof value === "function" ? value.bind(target) : value;
491
+ },
492
+ });
493
+ }
494
+ /** Record every held background call whose final result was never observed. */
495
+ function finishBackgroundCalls(status = "abandoned") {
496
+ const held = [...backgroundCalls.values()];
497
+ backgroundCalls.clear();
498
+ for (const call of held)
499
+ finishCapture(call.capture, call.state, call.last, { status });
500
+ return held.length;
501
+ }
502
+ function patchBackgroundObserver(owner, method) {
503
+ if (!owner || typeof owner[method] !== "function")
504
+ return false;
505
+ if (owner[method].__metergraph__)
506
+ return true;
507
+ const original = owner[method];
508
+ const wrapped = function (...args) {
509
+ const result = original.apply(owner, args);
510
+ // retrieve(id, { stream: true }) resumes a background response as a stream.
511
+ let streamed = false;
512
+ try {
513
+ streamed = get(args[1], "stream") === true;
514
+ }
515
+ catch {
516
+ // fail-open
517
+ }
518
+ const observe = (value) => {
519
+ if (streamed) {
520
+ try {
521
+ return value && value[Symbol.asyncIterator] ? observedBackgroundStream(value) : value;
522
+ }
523
+ catch {
524
+ return value;
525
+ }
526
+ }
527
+ observeBackground(value);
528
+ return value;
529
+ };
530
+ if (result && typeof result.then === "function") {
531
+ return preserveProviderPromise(result, observe, (error) => {
532
+ throw error;
533
+ });
534
+ }
535
+ return observe(result);
536
+ };
537
+ wrapped.__metergraph__ = true;
538
+ owner[method] = wrapped;
539
+ return true;
540
+ }
541
+ function applyBackgroundObservers(client) {
542
+ let patched = 0;
543
+ for (const path of ["responses", "beta.responses"]) {
544
+ let owner;
545
+ try {
546
+ owner = resolveSeam(client, path);
547
+ }
548
+ catch {
549
+ continue;
550
+ }
551
+ for (const method of ["retrieve", "cancel"])
552
+ patched += Number(patchBackgroundObserver(owner, method));
553
+ }
554
+ return patched;
555
+ }
408
556
  function patch(owner, method, provider, endpoint, gatewayName) {
409
557
  if (!owner || typeof owner[method] !== "function")
410
558
  return false;
@@ -433,6 +581,12 @@ function patch(owner, method, provider, endpoint, gatewayName) {
433
581
  return original.apply(owner, args);
434
582
  }
435
583
  const incoming = requestFrom(args);
584
+ if (endpoint === "responses.stream" && incoming.response_id != null) {
585
+ // Resuming an existing (background) response is not a new model call:
586
+ // it retrieves with stream: true, and the retrieve observer records the
587
+ // held create once from its terminal event.
588
+ return original.apply(owner, args);
589
+ }
436
590
  const patchUsage = typeof process === "undefined"
437
591
  || process.env.METERGRAPH_PATCH_STREAM_USAGE !== "0";
438
592
  let injectedUsage = false;
@@ -482,7 +636,12 @@ function patch(owner, method, provider, endpoint, gatewayName) {
482
636
  }
483
637
  if (!settled) {
484
638
  settled = true;
485
- finishCapture(capture, state, response);
639
+ if (shouldHoldBackground(endpoint, request, response)) {
640
+ holdBackground(capture, state, response);
641
+ }
642
+ else {
643
+ finishCapture(capture, state, response);
644
+ }
486
645
  }
487
646
  return response;
488
647
  };
@@ -613,7 +772,8 @@ function wrap(client, providerOrOptions) {
613
772
  const name = provider ?? detectProvider(client);
614
773
  const gatewayName = overrideGateway ?? (name === "openai" ? (0, gateway_js_1.detectGateway)(client) : undefined);
615
774
  const patched = applySeams(client, name, gatewayName);
616
- const patchedCount = patched.length + applyBatchExtras(client, name);
775
+ const patchedCount = patched.length + applyBatchExtras(client, name)
776
+ + (name === "openai" ? applyBackgroundObservers(client) : 0);
617
777
  const label = gatewayName ? `${gatewayName} gateway via ${name}` : name;
618
778
  if (!patchedCount) {
619
779
  console.warn(`Metergraph found no supported methods on ${label} client`);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "metergraph",
3
- "version": "0.6.10",
4
- "description": "Fire-and-forget LLM spend capture for Metergraph",
3
+ "version": "0.6.13",
4
+ "description": "Zero-dependency TypeScript SDK for function-level LLM cost attribution across major LLM providers and frameworks, including OpenAI, Anthropic, Gemini, and Vercel AI SDK.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.mjs",
@@ -29,17 +29,29 @@
29
29
  "node": ">=18"
30
30
  },
31
31
  "license": "Apache-2.0",
32
- "author": "Pioneer Square Labs",
32
+ "author": "Metergraph",
33
33
  "homepage": "https://www.metergraph.dev/",
34
34
  "repository": {
35
35
  "type": "git",
36
- "url": "git+https://github.com/PioneerSquareLabs/metergraphsdk.git",
36
+ "url": "git+https://github.com/metergraph/metergraphsdk.git",
37
37
  "directory": "typescript"
38
38
  },
39
39
  "bugs": {
40
- "url": "https://github.com/PioneerSquareLabs/metergraphsdk/issues"
40
+ "url": "https://github.com/metergraph/metergraphsdk/issues"
41
41
  },
42
- "keywords": ["llm", "observability", "openai", "anthropic", "gemini", "vercel-ai-sdk", "cost-tracking"],
42
+ "keywords": [
43
+ "llm",
44
+ "llm-cost",
45
+ "llm-observability",
46
+ "cost-attribution",
47
+ "ai-agents",
48
+ "openai",
49
+ "anthropic",
50
+ "gemini",
51
+ "vercel-ai-sdk",
52
+ "opentelemetry",
53
+ "self-hosted"
54
+ ],
43
55
  "dependencies": {},
44
56
  "devDependencies": {
45
57
  "@ai-sdk/anthropic": "^4.0.39",