metergraph 0.6.5 → 0.6.9

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
@@ -5,6 +5,10 @@ provider-independent Vercel AI SDK language models on Node 18+, including AWS
5
5
  Lambda. Worker-style `waitUntil` hooks are present but are not part of the v1
6
6
  public-package qualification contract.
7
7
 
8
+ Metergraph supports OpenAI JavaScript SDK majors 4 through 7. The current
9
+ major is tested in normal CI; the oldest supported major is qualified with a
10
+ manually triggered compatibility workflow.
11
+
8
12
  Initialize Metergraph once, then wrap each provider client. `init()` reads the
9
13
  token and other omitted options from the environment.
10
14
 
package/dist/capture.js CHANGED
@@ -6,6 +6,7 @@ const node_crypto_1 = require("node:crypto");
6
6
  const context_js_1 = require("./context.js");
7
7
  const gateway_js_1 = require("./gateway.js");
8
8
  const template_js_1 = require("./template.js");
9
+ const tool_definitions_js_1 = require("./tool-definitions.js");
9
10
  const version_js_1 = require("./version.js");
10
11
  exports.DEFAULT_TEXT_MAX_BYTES = 1024 * 1024;
11
12
  function get(value, key) {
@@ -73,9 +74,18 @@ function usage(response) {
73
74
  : fallback ?? provider[key],
74
75
  ]));
75
76
  }
77
+ // Only a non-empty string is reply text. On an OpenAI Responses body `text` is
78
+ // the text *config*, and a function-call-only reply lives in `output`.
79
+ function directText(response) {
80
+ const outputText = get(response, "output_text");
81
+ if (typeof outputText === "string" && outputText)
82
+ return outputText;
83
+ const text = get(response, "text");
84
+ return typeof text === "string" ? text : undefined;
85
+ }
76
86
  function responseText(response) {
77
- const direct = get(response, "output_text") ?? get(response, "text");
78
- if (typeof direct === "string")
87
+ const direct = directText(response);
88
+ if (direct !== undefined)
79
89
  return direct;
80
90
  const message = get(first(get(response, "choices")), "message");
81
91
  const content = get(message, "content");
@@ -169,7 +179,7 @@ function toolArgument(value) {
169
179
  return value;
170
180
  }
171
181
  }
172
- return (0, template_js_1.scrub)(value);
182
+ return value;
173
183
  }
174
184
  function toolEvents(request, response, streamChunks = []) {
175
185
  const calls = new Map();
@@ -340,7 +350,7 @@ function toolEvents(request, response, streamChunks = []) {
340
350
  arguments: input && typeof input === "object"
341
351
  && Object.keys(input).length === 0
342
352
  ? ""
343
- : JSON.stringify((0, template_js_1.scrub)(input ?? {})),
353
+ : JSON.stringify(input ?? {}),
344
354
  });
345
355
  }
346
356
  }
@@ -368,33 +378,195 @@ function toolEvents(request, response, streamChunks = []) {
368
378
  function responseContent(response, aggregate) {
369
379
  if (aggregate !== undefined)
370
380
  return aggregate;
371
- const direct = get(response, "output_text") ?? get(response, "text");
381
+ const direct = directText(response);
372
382
  if (direct !== undefined)
373
- return (0, template_js_1.scrub)(direct);
383
+ return direct;
374
384
  const message = get(first(get(response, "choices")), "message");
375
385
  const content = get(message, "content");
376
386
  if (content !== undefined)
377
- return (0, template_js_1.scrub)(content);
387
+ return content;
378
388
  const parsed = get(message, "parsed");
379
389
  if (parsed !== undefined)
380
- return (0, template_js_1.scrub)(parsed);
390
+ return parsed;
381
391
  const normalizedText = responseText(response);
382
392
  if (normalizedText !== undefined)
383
393
  return normalizedText;
384
394
  const blocks = get(response, "content");
385
395
  if (blocks !== undefined)
386
- return (0, template_js_1.scrub)(blocks);
396
+ return blocks;
387
397
  const output = get(response, "output");
388
398
  if (output !== undefined)
389
- return (0, template_js_1.scrub)(output);
399
+ return output;
390
400
  const candidates = get(response, "candidates");
391
- return candidates === undefined ? undefined : (0, template_js_1.scrub)(candidates);
401
+ return candidates;
402
+ }
403
+ // Restrict tool-only detection to direct Anthropic response shapes.
404
+ const ANTHROPIC_ENDPOINTS = new Set(["messages", "messages.stream"]);
405
+ // Extra block fields would be lost when represented only by the canonical event.
406
+ const TOOL_BLOCK_KEYS = new Set(["type", "id", "name", "input", "caller"]);
407
+ function plainMapping(value) {
408
+ if (typeof value !== "object" || value === null || Array.isArray(value))
409
+ return undefined;
410
+ const out = {};
411
+ for (const [key, item] of Object.entries(value)) {
412
+ if (item === undefined)
413
+ continue;
414
+ out[key] = item;
415
+ }
416
+ return out;
392
417
  }
393
- function responseEnvelope(response, aggregate, tools, error, status) {
418
+ function representableToolBlock(block) {
419
+ const mapping = plainMapping(block);
420
+ if (!mapping || mapping.type !== "tool_use")
421
+ return undefined;
422
+ if (Object.keys(mapping).some((key) => !TOOL_BLOCK_KEYS.has(key)))
423
+ return undefined;
424
+ const caller = mapping.caller;
425
+ if (caller !== undefined && caller !== null) {
426
+ const declared = plainMapping(caller);
427
+ if (!declared)
428
+ return undefined;
429
+ const meaningful = Object.entries(declared).filter(([, value]) => value !== null);
430
+ if (meaningful.length !== 1 || meaningful[0][0] !== "type" || meaningful[0][1] !== "direct") {
431
+ return undefined;
432
+ }
433
+ }
434
+ return mapping;
435
+ }
436
+ /** Check that every reply block has one equivalent event. */
437
+ function matchedEvents(blocks, events, compareArguments = true) {
438
+ const ids = blocks.map((block) => block.id);
439
+ if (ids.some((id) => typeof id !== "string" || !id))
440
+ return false;
441
+ if (new Set(ids).size !== ids.length)
442
+ return false;
443
+ for (const block of blocks) {
444
+ const matches = (events ?? []).filter((event) => event.call_id === block.id);
445
+ if (matches.length !== 1)
446
+ return false;
447
+ const event = matches[0];
448
+ if (event.name !== block.name)
449
+ return false;
450
+ // Streamed arguments are validated after delta accumulation.
451
+ if (compareArguments && !(0, tool_definitions_js_1.jsonEqual)(event.arguments, toolArgument(block.input))) {
452
+ return false;
453
+ }
454
+ }
455
+ return true;
456
+ }
457
+ function argumentsEqual(accumulated, eventArguments) {
458
+ try {
459
+ const expected = accumulated.trim() ? JSON.parse(accumulated) : {};
460
+ let actual = eventArguments;
461
+ if (typeof actual === "string")
462
+ actual = actual.trim() ? JSON.parse(actual) : {};
463
+ else if (actual === undefined || actual === null)
464
+ actual = {};
465
+ return (0, tool_definitions_js_1.jsonEqual)(expected, actual);
466
+ }
467
+ catch {
468
+ return false;
469
+ }
470
+ }
471
+ /** Check whether a completed Anthropic stream contains only tool calls. */
472
+ function streamToolOnly(chunks, events) {
473
+ const started = new Map();
474
+ const args = new Map();
475
+ const stopped = new Set();
476
+ const stopReasons = [];
477
+ let sawMessageStop = false;
478
+ for (const chunk of chunks) {
479
+ if (chunkText(chunk))
480
+ return false;
481
+ const kind = get(chunk, "type");
482
+ const delta = get(chunk, "delta");
483
+ if (typeof delta === "string" && String(kind).includes("reasoning"))
484
+ return false;
485
+ if (get(delta, "thinking") || get(delta, "reasoning"))
486
+ return false;
487
+ if (kind === "content_block_start") {
488
+ const mapping = representableToolBlock(get(chunk, "content_block"));
489
+ if (!mapping)
490
+ return false;
491
+ const key = String(get(chunk, "index") ?? started.size);
492
+ started.set(key, mapping);
493
+ const initial = mapping.input;
494
+ const empty = initial === undefined || initial === null
495
+ || (typeof initial === "object" && Object.keys(initial).length === 0);
496
+ args.set(key, empty ? "" : JSON.stringify(initial));
497
+ }
498
+ else if (kind === "content_block_delta") {
499
+ if (get(delta, "type") !== "input_json_delta")
500
+ return false;
501
+ const key = String(get(chunk, "index") ?? "0");
502
+ args.set(key, (args.get(key) ?? "") + String(get(delta, "partial_json") ?? ""));
503
+ }
504
+ else if (kind === "content_block_stop") {
505
+ stopped.add(String(get(chunk, "index") ?? "0"));
506
+ }
507
+ else if (kind === "message_delta") {
508
+ const reason = get(delta, "stop_reason");
509
+ if (reason !== undefined && reason !== null)
510
+ stopReasons.push(String(reason));
511
+ }
512
+ else if (kind === "message_stop") {
513
+ sawMessageStop = true;
514
+ }
515
+ }
516
+ if (!started.size || !sawMessageStop)
517
+ return false;
518
+ for (const key of started.keys())
519
+ if (!stopped.has(key))
520
+ return false;
521
+ if (stopReasons.some((reason) => reason !== "tool_use"))
522
+ return false;
523
+ const blocks = [...started.values()];
524
+ if (!matchedEvents(blocks, events, false))
525
+ return false;
526
+ for (const [key, mapping] of started) {
527
+ const matches = (events ?? []).filter((event) => event.call_id === mapping.id);
528
+ if (matches.length !== 1 || !argumentsEqual(args.get(key) ?? "", matches[0].arguments)) {
529
+ return false;
530
+ }
531
+ }
532
+ return true;
533
+ }
534
+ /** Check for a losslessly represented Anthropic tool-only reply. */
535
+ function anthropicToolOnly(response, options) {
536
+ if (!options.completed || options.aggregate !== undefined)
537
+ return false;
538
+ if (options.provider !== "anthropic" || !ANTHROPIC_ENDPOINTS.has(options.endpoint ?? "")) {
539
+ return false;
540
+ }
541
+ if (!options.events || !options.events.length)
542
+ return false;
543
+ const blocks = get(response, "content");
544
+ if (Array.isArray(blocks)) {
545
+ if (!blocks.length)
546
+ return false;
547
+ // Other stop reasons may indicate an unfinished tool call.
548
+ const reason = get(response, "stop_reason");
549
+ if (reason !== undefined && reason !== null && String(reason) !== "tool_use")
550
+ return false;
551
+ const mapped = blocks.map((block) => representableToolBlock(block));
552
+ if (mapped.some((block) => block === undefined))
553
+ return false;
554
+ return matchedEvents(mapped, options.events);
555
+ }
556
+ return streamToolOnly(options.chunks ?? [], options.events);
557
+ }
558
+ function responseEnvelope(response, aggregate, tools, error, status, recognition = {}) {
394
559
  const responseMetadata = get(response, "response");
560
+ let toolOnly = false;
561
+ try {
562
+ toolOnly = anthropicToolOnly(response, { ...recognition, aggregate });
563
+ }
564
+ catch {
565
+ toolOnly = false;
566
+ }
395
567
  const envelope = {
396
568
  role: "assistant",
397
- content: responseContent(response, aggregate),
569
+ content: toolOnly ? null : responseContent(response, aggregate),
398
570
  tool_calls: tools ?? [],
399
571
  finish_reason: stopReason(response),
400
572
  request_id: get(response, "_request_id") ?? get(response, "response_id")
@@ -409,6 +581,7 @@ function responseEnvelope(response, aggregate, tools, error, status) {
409
581
  message: error instanceof Error ? error.message : String(error),
410
582
  };
411
583
  }
584
+ // Explicit null distinguishes tool-only output from missing content data.
412
585
  return Object.fromEntries(Object.entries(envelope).filter(([, value]) => value !== undefined));
413
586
  }
414
587
  const SDK_DIR = (() => {
@@ -496,14 +669,68 @@ class CaptureRuntime {
496
669
  }
497
670
  return { value: `${clipped}${marker}`, truncated: true };
498
671
  };
499
- const request = text(JSON.stringify((0, template_js_1.scrub)(state.request)), "request");
500
- const fullTools = toolEvents((0, template_js_1.scrub)(state.request), response, extra.responseChunks);
672
+ const capturedRequest = (0, template_js_1.scrubRequest)(state.request);
673
+ const request = text(JSON.stringify(capturedRequest), "request");
674
+ // Tool definitions follow request text, redaction, and size controls.
675
+ let toolDefinitions;
676
+ let toolDefinitionsTruncated = false;
677
+ if (captureText) {
678
+ try {
679
+ const read = (0, tool_definitions_js_1.readDeclarations)(state.request, state.provider);
680
+ if (read) {
681
+ let records = read.declarations;
682
+ let fidelity = "verbatim";
683
+ const encoded = JSON.stringify(records);
684
+ if (this.options.redact) {
685
+ let parsed;
686
+ try {
687
+ parsed = JSON.parse(this.options.redact(encoded, "request"));
688
+ }
689
+ catch {
690
+ parsed = undefined;
691
+ }
692
+ if ((0, tool_definitions_js_1.validDeclarations)(parsed)) {
693
+ if (!(0, tool_definitions_js_1.jsonEqual)(parsed, records))
694
+ fidelity = "filtered";
695
+ records = parsed;
696
+ }
697
+ else {
698
+ records = [];
699
+ }
700
+ }
701
+ if (records.length) {
702
+ const envelope = (0, tool_definitions_js_1.toolDefinitionsEnvelope)(records, read.scope, fidelity);
703
+ const serialized = JSON.stringify(envelope);
704
+ if (new TextEncoder().encode(serialized).byteLength > this.options.textMaxBytes) {
705
+ toolDefinitionsTruncated = true;
706
+ }
707
+ else {
708
+ toolDefinitions = envelope;
709
+ }
710
+ }
711
+ }
712
+ }
713
+ catch {
714
+ toolDefinitions = undefined;
715
+ }
716
+ }
717
+ const fullTools = toolEvents(capturedRequest, response, extra.responseChunks);
501
718
  const status = extra.status ?? (extra.error ? "error" : stopReason(response) ?? "success");
502
719
  const { finishReason, finishReasonRaw } = finishReasonDetails(response);
503
720
  const statusCode = extra.error || extra.status === "error" || finishReason === "error"
504
721
  ? "error"
505
722
  : "unset";
506
- const output = text(JSON.stringify(responseEnvelope(response, extra.responseText, fullTools, extra.error, status)), "response");
723
+ const output = text(JSON.stringify(responseEnvelope(response, extra.responseText, fullTools, extra.error, status, {
724
+ provider: state.provider,
725
+ endpoint: state.endpoint,
726
+ events: fullTools,
727
+ chunks: extra.responseChunks,
728
+ completed: extra.error === undefined
729
+ && extra.status !== "error"
730
+ && extra.status !== "abandoned"
731
+ && statusCode !== "error"
732
+ && finishReason !== "error",
733
+ })), "response");
507
734
  let toolTruncated = false;
508
735
  let persistedTools;
509
736
  if (fullTools && captureText) {
@@ -536,6 +763,7 @@ class CaptureRuntime {
536
763
  this.transport.enqueue({
537
764
  ts: state.ts,
538
765
  route: state.context.route,
766
+ route_source: state.context.route ? state.context.routeSource : undefined,
539
767
  provider: state.provider,
540
768
  model: state.request.model,
541
769
  ...usage(response),
@@ -567,7 +795,10 @@ class CaptureRuntime {
567
795
  content_opted_in: captureText,
568
796
  request_json: request.value,
569
797
  response_text: output.value,
570
- text_truncated: request.truncated || output.truncated || toolTruncated,
798
+ text_truncated: request.truncated || output.truncated || toolTruncated
799
+ || toolDefinitionsTruncated,
800
+ // Absence distinguishes tool-free calls from invalid declarations.
801
+ ...(toolDefinitions ? { tool_definitions: toolDefinitions } : {}),
571
802
  stream: extra.stream ?? false,
572
803
  ttft_ms: extra.ttftMs,
573
804
  func: state.context.funcName
package/dist/context.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export interface CaptureContext {
2
2
  route?: string;
3
+ /** "explicit" when the developer named the route, "derived" when filled in. */
4
+ routeSource?: "explicit" | "derived";
3
5
  sessionId?: string;
4
6
  tags: Record<string, string>;
5
7
  unitName?: string;
package/dist/context.js CHANGED
@@ -49,6 +49,7 @@ async function route(name, fn, options = {}) {
49
49
  const child = {
50
50
  ...parent,
51
51
  route: name,
52
+ routeSource: "explicit",
52
53
  tags: {
53
54
  ...parent.tags,
54
55
  ...Object.fromEntries(Object.entries(options.tags ?? {}).map(([key, value]) => [key, String(value)])),
@@ -1,2 +1,11 @@
1
- export declare function scrub(value: unknown): unknown;
1
+ /**
2
+ * The provider request as captured, without its credentials.
3
+ *
4
+ * Credentials travel as request-level parameters and in header or query
5
+ * containers. `extra_body` is merged into the request body, so its keys are
6
+ * request-level too. Messages, tools and schemas are kept exactly as sent,
7
+ * even where a name matches a credential's (a tool parameter called `token`),
8
+ * because they are the request analysis replays.
9
+ */
10
+ export declare function scrubRequest(request: unknown): unknown;
2
11
  export declare function templateHash(request: Record<string, unknown>): string;
package/dist/template.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.scrub = scrub;
3
+ exports.scrubRequest = scrubRequest;
4
4
  exports.templateHash = templateHash;
5
5
  const sensitive = new Set([
6
6
  "api-key",
@@ -19,13 +19,56 @@ const sensitive = new Set([
19
19
  "token",
20
20
  "x-api-key",
21
21
  ]);
22
- function scrub(value) {
22
+ // Header and query containers carry transport credentials and nothing analysis
23
+ // reads, so they are dropped whole. Keys compare lower-cased, so camelCase
24
+ // client options match.
25
+ const transportContainers = new Set([
26
+ "default_headers",
27
+ "default_query",
28
+ "defaultheaders",
29
+ "defaultquery",
30
+ "extra_headers",
31
+ "extra_query",
32
+ "extraheaders",
33
+ "extraquery",
34
+ "headers",
35
+ "query",
36
+ ]);
37
+ function credentialKey(key) {
38
+ const lower = key.trim().toLowerCase();
39
+ return sensitive.has(lower) || transportContainers.has(lower);
40
+ }
41
+ function withoutCredentialKeys(value) {
42
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !credentialKey(key)));
43
+ }
44
+ /**
45
+ * The provider request as captured, without its credentials.
46
+ *
47
+ * Credentials travel as request-level parameters and in header or query
48
+ * containers. `extra_body` is merged into the request body, so its keys are
49
+ * request-level too. Messages, tools and schemas are kept exactly as sent,
50
+ * even where a name matches a credential's (a tool parameter called `token`),
51
+ * because they are the request analysis replays.
52
+ */
53
+ function scrubRequest(request) {
54
+ if (!request || typeof request !== "object" || Array.isArray(request))
55
+ return request;
56
+ const clean = withoutCredentialKeys(request);
57
+ for (const key of ["extra_body", "extraBody"]) {
58
+ const body = clean[key];
59
+ if (body && typeof body === "object" && !Array.isArray(body)) {
60
+ clean[key] = withoutCredentialKeys(body);
61
+ }
62
+ }
63
+ return clean;
64
+ }
65
+ function withoutCredentialNames(value) {
23
66
  if (Array.isArray(value))
24
- return value.map(scrub);
67
+ return value.map(withoutCredentialNames);
25
68
  if (value && typeof value === "object") {
26
69
  return Object.fromEntries(Object.entries(value)
27
70
  .filter(([key]) => !sensitive.has(key.trim().toLowerCase()))
28
- .map(([key, item]) => [key, scrub(item)]));
71
+ .map(([key, item]) => [key, withoutCredentialNames(item)]));
29
72
  }
30
73
  return value;
31
74
  }
@@ -56,6 +99,8 @@ function fnv1a(value) {
56
99
  }
57
100
  return hash.toString(16).padStart(16, "0");
58
101
  }
102
+ // Credential names are left out at every depth. This hash routes unnamed
103
+ // workloads, so its input must stay stable across SDK versions.
59
104
  function templateHash(request) {
60
- return fnv1a(JSON.stringify(normalized(scrub(request))));
105
+ return fnv1a(JSON.stringify(normalized(withoutCredentialNames(request))));
61
106
  }
@@ -0,0 +1,40 @@
1
+ /** Canonicalize request tool declarations without guessing provider semantics. */
2
+ export declare const TOOL_DEFINITIONS_VERSION = 1;
3
+ export interface ToolDeclaration {
4
+ index: number;
5
+ container: string;
6
+ kind: string;
7
+ dialect: string;
8
+ name: string | null;
9
+ description: string | null;
10
+ schema_key: string | null;
11
+ schema: Record<string, unknown> | null;
12
+ status: string;
13
+ provider_type?: string;
14
+ duplicate_of?: number;
15
+ }
16
+ export interface ToolDefinitions {
17
+ version: number;
18
+ fidelity: string;
19
+ scope: string;
20
+ declarations: ToolDeclaration[];
21
+ }
22
+ /**
23
+ * Semantic JSON equality: object key order ignored, array order kept, and
24
+ * booleans distinguished from numbers. `JSON.stringify` compares key insertion
25
+ * order, which would call two identical schemas different.
26
+ */
27
+ export declare function jsonEqual(left: unknown, right: unknown): boolean;
28
+ /** Return declarations and their single- or multi-container scope. */
29
+ export declare function readDeclarations(request: Record<string, unknown>, provider?: string): {
30
+ declarations: ToolDeclaration[];
31
+ scope: string;
32
+ } | undefined;
33
+ /**
34
+ * Whether a declarations array still matches the contract. Applied to the
35
+ * redaction hook's output, which is caller-supplied and may return anything.
36
+ * Total by construction: it answers for every input and never throws, so a
37
+ * hostile or broken hook costs the field and nothing else.
38
+ */
39
+ export declare function validDeclarations(value: unknown): value is ToolDeclaration[];
40
+ export declare function toolDefinitionsEnvelope(declarations: ToolDeclaration[], scope: string, fidelity: string): ToolDefinitions;
@@ -0,0 +1,402 @@
1
+ "use strict";
2
+ /** Canonicalize request tool declarations without guessing provider semantics. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.TOOL_DEFINITIONS_VERSION = void 0;
5
+ exports.jsonEqual = jsonEqual;
6
+ exports.readDeclarations = readDeclarations;
7
+ exports.validDeclarations = validDeclarations;
8
+ exports.toolDefinitionsEnvelope = toolDefinitionsEnvelope;
9
+ exports.TOOL_DEFINITIONS_VERSION = 1;
10
+ // Container order is part of the durable record contract.
11
+ const CONTAINERS = [
12
+ ["tools", ["tools"]],
13
+ ["config.tools", ["config", "tools"]],
14
+ ["extra_body.tools", ["extra_body", "tools"]],
15
+ ];
16
+ // Gemini schema-key precedence is part of the capture contract.
17
+ const SCHEMA_KEYS = ["parameters_json_schema", "parametersJsonSchema", "parameters"];
18
+ const GEMINI_NATIVE_TOOLS = new Set([
19
+ "google_search",
20
+ "google_search_retrieval",
21
+ "code_execution",
22
+ "url_context",
23
+ ]);
24
+ const IDENTITY_MAX_BYTES = 512;
25
+ const INDEX_MAX = 10_000;
26
+ const RECORD_KEYS = [
27
+ "index",
28
+ "container",
29
+ "kind",
30
+ "dialect",
31
+ "name",
32
+ "description",
33
+ "schema_key",
34
+ "schema",
35
+ "status",
36
+ ];
37
+ const OPTIONAL_RECORD_KEYS = ["provider_type", "duplicate_of"];
38
+ const KINDS = new Set(["function", "provider", "unknown"]);
39
+ // Keep this vocabulary aligned across SDK and OpenTelemetry implementations.
40
+ const OTEL_DIALECT = "otel";
41
+ const OTEL_CONTAINER = "gen_ai.tool.definitions";
42
+ const DIALECTS = new Set([
43
+ "anthropic",
44
+ "openai_chat",
45
+ "openai_responses",
46
+ "gemini",
47
+ "ai_sdk",
48
+ OTEL_DIALECT,
49
+ "unknown",
50
+ ]);
51
+ const STATUSES = new Set([
52
+ "declared",
53
+ "incomplete",
54
+ "malformed",
55
+ "unsupported",
56
+ "provider_tool",
57
+ "ambiguous",
58
+ ]);
59
+ const CONTAINER_NAMES = new Set([
60
+ ...CONTAINERS.map(([name]) => name),
61
+ OTEL_CONTAINER,
62
+ ]);
63
+ const SCHEMA_KEY_NAMES = new Set([...SCHEMA_KEYS, "input_schema", "inputSchema"]);
64
+ // OpenAI provider-native declarations do not identify Chat versus Responses.
65
+ const PROVIDER_DIALECTS = { anthropic: "anthropic", google: "gemini" };
66
+ function attribute(value, name) {
67
+ if (value == null || typeof value !== "object")
68
+ return undefined;
69
+ return value[name];
70
+ }
71
+ function has(value, name) {
72
+ if (value == null || typeof value !== "object")
73
+ return false;
74
+ return name in value
75
+ && value[name] !== undefined;
76
+ }
77
+ function isMapping(value) {
78
+ return typeof value === "object" && value !== null && !Array.isArray(value);
79
+ }
80
+ /** A declared identity string, or null when it is absent or unusable. */
81
+ function identity(value) {
82
+ if (typeof value !== "string")
83
+ return null;
84
+ return new TextEncoder().encode(value).byteLength <= IDENTITY_MAX_BYTES ? value : null;
85
+ }
86
+ /** JSON data, or undefined where a value cannot be represented as JSON. */
87
+ function jsonValue(value) {
88
+ if (value === null)
89
+ return null;
90
+ const kind = typeof value;
91
+ if (kind === "string" || kind === "boolean")
92
+ return value;
93
+ if (kind === "number")
94
+ return Number.isFinite(value) ? value : undefined;
95
+ if (kind === "bigint" || kind === "function" || kind === "symbol" || kind === "undefined") {
96
+ return undefined;
97
+ }
98
+ if (Array.isArray(value)) {
99
+ const items = [];
100
+ for (const item of value) {
101
+ const converted = jsonValue(item);
102
+ if (converted === undefined)
103
+ return undefined;
104
+ items.push(converted);
105
+ }
106
+ return items;
107
+ }
108
+ if (isMapping(value)) {
109
+ const entries = [];
110
+ for (const [key, item] of Object.entries(value)) {
111
+ if (item === undefined)
112
+ continue;
113
+ const converted = jsonValue(item);
114
+ if (converted === undefined)
115
+ return undefined;
116
+ entries.push([key, converted]);
117
+ }
118
+ // `Object.fromEntries` defines own properties, so a schema carrying a
119
+ // legal `__proto__` key keeps it instead of rewriting the clone's
120
+ // prototype and losing the declaration it claims to copy verbatim.
121
+ return Object.fromEntries(entries);
122
+ }
123
+ return undefined;
124
+ }
125
+ /**
126
+ * Semantic JSON equality: object key order ignored, array order kept, and
127
+ * booleans distinguished from numbers. `JSON.stringify` compares key insertion
128
+ * order, which would call two identical schemas different.
129
+ */
130
+ function jsonEqual(left, right) {
131
+ if (typeof left === "boolean" || typeof right === "boolean")
132
+ return left === right;
133
+ if (Array.isArray(left) || Array.isArray(right)) {
134
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {
135
+ return false;
136
+ }
137
+ return left.every((item, index) => jsonEqual(item, right[index]));
138
+ }
139
+ if (isMapping(left) || isMapping(right)) {
140
+ if (!isMapping(left) || !isMapping(right))
141
+ return false;
142
+ const leftKeys = Object.keys(left);
143
+ const rightKeys = Object.keys(right);
144
+ if (leftKeys.length !== rightKeys.length)
145
+ return false;
146
+ return leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && jsonEqual(left[key], right[key]));
147
+ }
148
+ return left === right;
149
+ }
150
+ function record(index, container, fields) {
151
+ const entry = {
152
+ index,
153
+ container,
154
+ kind: fields.kind,
155
+ dialect: fields.dialect,
156
+ name: identity(fields.name),
157
+ description: typeof fields.description === "string" ? fields.description : null,
158
+ schema_key: fields.schemaKey ?? null,
159
+ schema: (fields.schema ?? null),
160
+ status: fields.status,
161
+ };
162
+ const providerType = identity(fields.providerType);
163
+ if (providerType !== null)
164
+ entry.provider_type = providerType;
165
+ return entry;
166
+ }
167
+ function functionRecord(index, container, dialect, entry, schemaKeys) {
168
+ const name = attribute(entry, "name");
169
+ const description = attribute(entry, "description");
170
+ const converted = [];
171
+ for (const key of schemaKeys) {
172
+ if (!has(entry, key))
173
+ continue;
174
+ const value = jsonValue(attribute(entry, key));
175
+ if (value === undefined) {
176
+ // Unsupported schemas remain available in request_json.
177
+ return record(index, container, {
178
+ kind: "function", dialect, status: "unsupported", name, description,
179
+ });
180
+ }
181
+ converted.push([key, value]);
182
+ }
183
+ if (converted.length > 1) {
184
+ const [, first] = converted[0];
185
+ if (converted.slice(1).some(([, value]) => !jsonEqual(value, first))) {
186
+ // Conflicting schema keys make the effective schema unknowable.
187
+ return record(index, container, {
188
+ kind: "function", dialect, status: "ambiguous", name, description,
189
+ });
190
+ }
191
+ }
192
+ const [schemaKey, schema] = converted.length ? converted[0] : [null, null];
193
+ const nameMalformed = name !== undefined && name !== null && identity(name) === null;
194
+ const schemaMalformed = converted.length > 0 && !isMapping(schema);
195
+ if (nameMalformed || schemaMalformed) {
196
+ return record(index, container, {
197
+ kind: "function",
198
+ dialect,
199
+ status: "malformed",
200
+ name: nameMalformed ? null : name,
201
+ description,
202
+ schemaKey: schemaMalformed ? null : schemaKey,
203
+ schema: schemaMalformed ? null : schema,
204
+ });
205
+ }
206
+ if (name === undefined || name === null || converted.length === 0) {
207
+ return record(index, container, {
208
+ kind: "function",
209
+ dialect,
210
+ status: "incomplete",
211
+ name,
212
+ description,
213
+ schemaKey: schemaKey,
214
+ schema,
215
+ });
216
+ }
217
+ return record(index, container, {
218
+ kind: "function",
219
+ dialect,
220
+ status: "declared",
221
+ name,
222
+ description,
223
+ schemaKey: schemaKey,
224
+ schema,
225
+ });
226
+ }
227
+ /** Every record one container entry produces, in declaration order. */
228
+ function entryRecords(index, container, entry, provider) {
229
+ if (!isMapping(entry)) {
230
+ return [record(index, container, { kind: "unknown", dialect: "unknown", status: "unsupported" })];
231
+ }
232
+ const declarations = attribute(entry, "function_declarations")
233
+ ?? attribute(entry, "functionDeclarations");
234
+ if (Array.isArray(declarations)) {
235
+ const records = declarations.map((declaration, position) => functionRecord(index + position, container, "gemini", declaration, SCHEMA_KEYS));
236
+ return records.length
237
+ ? records
238
+ : [record(index, container, { kind: "unknown", dialect: "unknown", status: "unsupported" })];
239
+ }
240
+ const fn = attribute(entry, "function");
241
+ if (isMapping(fn)) {
242
+ return [functionRecord(index, container, "openai_chat", fn, ["parameters"])];
243
+ }
244
+ if (has(entry, "input_schema")) {
245
+ return [functionRecord(index, container, "anthropic", entry, ["input_schema"])];
246
+ }
247
+ if (has(entry, "inputSchema")) {
248
+ return [functionRecord(index, container, "ai_sdk", entry, ["inputSchema"])];
249
+ }
250
+ const declaredType = attribute(entry, "type");
251
+ if (declaredType === "function") {
252
+ // A nameless function is incomplete, not provider-native.
253
+ return [functionRecord(index, container, "openai_responses", entry, ["parameters"])];
254
+ }
255
+ if (typeof declaredType === "string") {
256
+ return [record(index, container, {
257
+ kind: "provider",
258
+ dialect: PROVIDER_DIALECTS[provider ?? ""] ?? "unknown",
259
+ status: "provider_tool",
260
+ name: attribute(entry, "name"),
261
+ providerType: declaredType,
262
+ })];
263
+ }
264
+ const keys = Object.keys(entry);
265
+ if (keys.length === 1) {
266
+ const key = keys[0];
267
+ if (GEMINI_NATIVE_TOOLS.has(key) && isMapping(entry[key])) {
268
+ return [record(index, container, {
269
+ kind: "provider", dialect: "gemini", status: "provider_tool", name: key,
270
+ })];
271
+ }
272
+ }
273
+ return [record(index, container, { kind: "unknown", dialect: "unknown", status: "unsupported" })];
274
+ }
275
+ function containerValue(request, path) {
276
+ let value = request;
277
+ for (const name of path) {
278
+ if (!has(value, name))
279
+ return [false, undefined];
280
+ value = attribute(value, name);
281
+ }
282
+ return [true, value];
283
+ }
284
+ /** Return declarations and their single- or multi-container scope. */
285
+ function readDeclarations(request, provider) {
286
+ const records = [];
287
+ let contributors = 0;
288
+ for (const [container, path] of CONTAINERS) {
289
+ const [present, value] = containerValue(request, path);
290
+ if (!present)
291
+ continue;
292
+ const before = records.length;
293
+ if (!Array.isArray(value)) {
294
+ // Preserve malformed presence rather than reporting no declarations.
295
+ records.push(record(records.length, container, {
296
+ kind: "unknown", dialect: "unknown", status: "unsupported",
297
+ }));
298
+ }
299
+ else {
300
+ for (const entry of value) {
301
+ records.push(...entryRecords(records.length, container, entry, provider));
302
+ }
303
+ }
304
+ if (records.length > before)
305
+ contributors += 1;
306
+ }
307
+ if (!records.length || records.length > INDEX_MAX)
308
+ return undefined;
309
+ const seen = new Map();
310
+ for (const entry of records) {
311
+ if (entry.name === null)
312
+ continue;
313
+ const first = seen.get(entry.name);
314
+ if (first === undefined)
315
+ seen.set(entry.name, entry.index);
316
+ else
317
+ entry.duplicate_of = first;
318
+ }
319
+ return { declarations: records, scope: contributors <= 1 ? "effective" : "inventory" };
320
+ }
321
+ const MAX_SCHEMA_DEPTH = 100;
322
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
323
+ /**
324
+ * Whether a value is JSON data the durable column can hold. `JSON.parse`
325
+ * accepts a lone surrogate, a hook can introduce `NaN`, and neither survives
326
+ * the durable write; depth is bounded so a deeply nested hook result cannot
327
+ * recurse this check off the stack.
328
+ */
329
+ function storable(value, depth = 0) {
330
+ if (depth > MAX_SCHEMA_DEPTH)
331
+ return false;
332
+ if (typeof value === "string") {
333
+ return !value.includes("\u0000") && !LONE_SURROGATE.test(value);
334
+ }
335
+ if (typeof value === "boolean" || value === null)
336
+ return true;
337
+ if (typeof value === "number")
338
+ return Number.isFinite(value);
339
+ if (Array.isArray(value))
340
+ return value.every((item) => storable(item, depth + 1));
341
+ if (isMapping(value)) {
342
+ return Object.entries(value).every(([key, item]) => storable(key, depth + 1) && storable(item, depth + 1));
343
+ }
344
+ return false;
345
+ }
346
+ /**
347
+ * Whether a declarations array still matches the contract. Applied to the
348
+ * redaction hook's output, which is caller-supplied and may return anything.
349
+ * Total by construction: it answers for every input and never throws, so a
350
+ * hostile or broken hook costs the field and nothing else.
351
+ */
352
+ function validDeclarations(value) {
353
+ if (!Array.isArray(value) || !value.length)
354
+ return false;
355
+ for (const entry of value) {
356
+ if (!isMapping(entry))
357
+ return false;
358
+ const keys = Object.keys(entry);
359
+ if (!RECORD_KEYS.every((key) => keys.includes(key)))
360
+ return false;
361
+ if (keys.some((key) => !RECORD_KEYS.includes(key) && !OPTIONAL_RECORD_KEYS.includes(key))) {
362
+ return false;
363
+ }
364
+ const index = entry.index;
365
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= INDEX_MAX) {
366
+ return false;
367
+ }
368
+ if ("duplicate_of" in entry) {
369
+ const duplicate = entry.duplicate_of;
370
+ if (typeof duplicate !== "number" || !Number.isInteger(duplicate)
371
+ || duplicate < 0 || duplicate >= INDEX_MAX)
372
+ return false;
373
+ }
374
+ if (typeof entry.kind !== "string" || !KINDS.has(entry.kind))
375
+ return false;
376
+ if (typeof entry.dialect !== "string" || !DIALECTS.has(entry.dialect))
377
+ return false;
378
+ if (typeof entry.status !== "string" || !STATUSES.has(entry.status))
379
+ return false;
380
+ if (typeof entry.container !== "string" || !CONTAINER_NAMES.has(entry.container))
381
+ return false;
382
+ if (entry.schema_key !== null
383
+ && (typeof entry.schema_key !== "string" || !SCHEMA_KEY_NAMES.has(entry.schema_key))) {
384
+ return false;
385
+ }
386
+ for (const key of ["name", "provider_type"]) {
387
+ const text = entry[key];
388
+ if (text !== undefined && text !== null && identity(text) === null)
389
+ return false;
390
+ }
391
+ if (entry.description !== null && typeof entry.description !== "string")
392
+ return false;
393
+ if (entry.schema !== null && !isMapping(entry.schema))
394
+ return false;
395
+ if (!storable(entry))
396
+ return false;
397
+ }
398
+ return true;
399
+ }
400
+ function toolDefinitionsEnvelope(declarations, scope, fidelity) {
401
+ return { version: exports.TOOL_DEFINITIONS_VERSION, fidelity, scope, declarations };
402
+ }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.6.5";
1
+ export declare const SDK_VERSION = "0.6.9";
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.5";
4
+ exports.SDK_VERSION = "0.6.9";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "metergraph",
3
- "version": "0.6.5",
3
+ "version": "0.6.9",
4
4
  "description": "Fire-and-forget LLM spend capture for Metergraph",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -21,6 +21,7 @@
21
21
  "prepublishOnly": "npm test && npm run test:package",
22
22
  "test": "npm run build && npm run test:types && npm run test:examples && node --test test/*.test.mjs",
23
23
  "test:examples": "tsc --noEmit --strict --skipLibCheck --target ES2022 --module NodeNext --moduleResolution NodeNext test/ai-sdk-factories.types.ts",
24
+ "test:openai-v4": "npm run build && node --test test/compatibility/openai-v4.test.mjs",
24
25
  "test:package": "npm run build && node --test test/package/packed-package.test.mjs",
25
26
  "test:types": "tsc --noEmit --strict --skipLibCheck --target ES2022 --module NodeNext --moduleResolution NodeNext test/ai-sdk-current.types.ts test/wrap-gateway.types.ts"
26
27
  },
@@ -55,7 +56,7 @@
55
56
  "@anthropic-ai/sdk": ">=0.30",
56
57
  "@google/genai": ">=1",
57
58
  "ai": ">=5 <8",
58
- "openai": ">=4"
59
+ "openai": ">=4 <8"
59
60
  },
60
61
  "peerDependenciesMeta": {
61
62
  "openai": {"optional": true},