metergraph 0.1.0
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 +79 -0
- package/dist/capture.d.ts +40 -0
- package/dist/capture.js +191 -0
- package/dist/config.d.ts +26 -0
- package/dist/config.js +69 -0
- package/dist/context.d.ts +20 -0
- package/dist/context.js +40 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.js +138 -0
- package/dist/template.d.ts +2 -0
- package/dist/template.js +41 -0
- package/dist/track.d.ts +4 -0
- package/dist/track.js +11 -0
- package/dist/transport.d.ts +35 -0
- package/dist/transport.js +145 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/dist/wrap.d.ts +6 -0
- package/dist/wrap.js +350 -0
- package/package.json +38 -0
package/README.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# metergraph (TypeScript)
|
|
2
|
+
|
|
3
|
+
Zero-runtime-dependency capture for OpenAI, Anthropic, and Gemini clients on
|
|
4
|
+
Node 18+, including AWS Lambda. Worker-style `waitUntil` hooks are present but
|
|
5
|
+
are not part of the v1 public-package qualification contract.
|
|
6
|
+
|
|
7
|
+
`wrap()` initializes capture from the environment, so setup is one line per
|
|
8
|
+
client; call `init(...)` before the first `wrap()` only to pass options in
|
|
9
|
+
code.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { wrap, route, modelFor, recordOutcome, setSession } from "metergraph";
|
|
13
|
+
import OpenAI from "openai";
|
|
14
|
+
|
|
15
|
+
// new Anthropic() and new GoogleGenAI({}) wrap the same way.
|
|
16
|
+
const client = wrap(new OpenAI());
|
|
17
|
+
setSession("ticket-123");
|
|
18
|
+
|
|
19
|
+
let model = "gpt-4.1-mini";
|
|
20
|
+
await route("ticket-classifier", async () => {
|
|
21
|
+
model = modelFor("ticket-classifier", model);
|
|
22
|
+
await client.chat.completions.create({ model, messages: [] });
|
|
23
|
+
}, { unit: "answer", captureText: true });
|
|
24
|
+
|
|
25
|
+
recordOutcome("ticket-classifier", {
|
|
26
|
+
model,
|
|
27
|
+
taskCompleted: true,
|
|
28
|
+
feedbackScore: 1,
|
|
29
|
+
turnsToResolution: 2,
|
|
30
|
+
escalated: false,
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Set `METERGRAPH_APP_TOKEN`; `METERGRAPH_INGEST_URL` is only needed to override
|
|
35
|
+
the hosted HTTPS endpoint. Content is metadata-only by default; set
|
|
36
|
+
`METERGRAPH_CAPTURE_TEXT=1` globally or `captureText: true` on an individual
|
|
37
|
+
route to opt in. Actual wire batches never exceed 512 KiB after optional gzip.
|
|
38
|
+
Long-running Node processes use an unref'd
|
|
39
|
+
background timer. On Workers or Vercel, call
|
|
40
|
+
`bindWaitUntil(ctx)` once per request. On Lambda, use `wrapHandler(handler)`
|
|
41
|
+
or `await flush()` before returning.
|
|
42
|
+
|
|
43
|
+
`recordOutcome` uses the same bounded asynchronous channel and sends no prompt
|
|
44
|
+
or output content. A stable session ID and the model actually used let a
|
|
45
|
+
session-sticky canary compare task completion and optional feedback,
|
|
46
|
+
turn-count, escalation, abandonment, edit-distance, and regeneration signals.
|
|
47
|
+
|
|
48
|
+
OpenAI Batch API output JSONL is captured per inference when the `Response`
|
|
49
|
+
from a wrapped `client.files.content()` is consumed with `text()`,
|
|
50
|
+
`arrayBuffer()`, or `blob()`. Anthropic message batches are captured per
|
|
51
|
+
inference while iterating a wrapped `client.messages.batches.results()` result.
|
|
52
|
+
Consume results inside `route()` so the asynchronous batch retains its product
|
|
53
|
+
route. Job-management polls are deliberately not counted as model calls.
|
|
54
|
+
|
|
55
|
+
## Set up with an AI coding agent
|
|
56
|
+
|
|
57
|
+
Paste this into Claude Code, Codex, Cursor, or any coding agent inside the
|
|
58
|
+
codebase you want instrumented:
|
|
59
|
+
|
|
60
|
+
```text
|
|
61
|
+
Instrument this codebase's LLM API costs with the `metergraph` npm package
|
|
62
|
+
(https://github.com/PioneerSquareLabs/metergraphsdk): npm install metergraph,
|
|
63
|
+
then wrap every new OpenAI(), new Anthropic(), and new GoogleGenAI()
|
|
64
|
+
construction in place, e.g. const client = mg.wrap(new OpenAI()) after
|
|
65
|
+
import * as mg from "metergraph". wrap() returns the same client and
|
|
66
|
+
initializes itself from the environment: METERGRAPH_APP_TOKEN is required
|
|
67
|
+
(capture is silently off without it) and METERGRAPH_INGEST_URL is only for
|
|
68
|
+
self-hosted servers. Add both to .env.example, and never commit a real token.
|
|
69
|
+
Capture is metadata-only (tokens, latency, model, no prompt/completion
|
|
70
|
+
content) and fail-open, so do not change call sites, arguments, or error
|
|
71
|
+
handling; async and streaming work unchanged. Wrap each function that calls a
|
|
72
|
+
wrapped client with mg.track("stable.name", fn), because stack-based
|
|
73
|
+
attribution is unreliable under bundlers. On serverless (Lambda / Workers /
|
|
74
|
+
Vercel), ensure delivery before the runtime freezes: mg.wrapHandler(handler),
|
|
75
|
+
or mg.bindWaitUntil(ctx) once per request, or await mg.flush() before
|
|
76
|
+
returning; long-running servers need nothing extra. When done, list every
|
|
77
|
+
client you wrapped and flag LLM calls made outside the official openai /
|
|
78
|
+
@anthropic-ai/sdk / @google/genai SDKs, since those are not captured.
|
|
79
|
+
```
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type CaptureContext } from "./context.js";
|
|
2
|
+
import type { Transport } from "./transport.js";
|
|
3
|
+
export interface RuntimeOptions {
|
|
4
|
+
captureText: boolean;
|
|
5
|
+
redact?: (text: string, kind: "request" | "response") => string;
|
|
6
|
+
appRoot: string;
|
|
7
|
+
skipFrames: string[];
|
|
8
|
+
environment?: string;
|
|
9
|
+
textMaxBytes: number;
|
|
10
|
+
}
|
|
11
|
+
interface Frame {
|
|
12
|
+
m: string;
|
|
13
|
+
f: string;
|
|
14
|
+
l: number;
|
|
15
|
+
}
|
|
16
|
+
interface CallState {
|
|
17
|
+
provider: string;
|
|
18
|
+
endpoint: string;
|
|
19
|
+
request: Record<string, unknown>;
|
|
20
|
+
context: CaptureContext;
|
|
21
|
+
started: number;
|
|
22
|
+
ts: string;
|
|
23
|
+
frames: Frame[];
|
|
24
|
+
done: boolean;
|
|
25
|
+
}
|
|
26
|
+
export declare function chunkText(chunk: unknown): string | undefined;
|
|
27
|
+
export declare class CaptureRuntime {
|
|
28
|
+
readonly transport: Transport;
|
|
29
|
+
readonly options: RuntimeOptions;
|
|
30
|
+
constructor(transport: Transport, options: RuntimeOptions);
|
|
31
|
+
start(provider: string, endpoint: string, request: Record<string, unknown>, stack?: string, context?: CaptureContext): CallState;
|
|
32
|
+
finish(state: CallState, response?: unknown, extra?: {
|
|
33
|
+
error?: unknown;
|
|
34
|
+
status?: string;
|
|
35
|
+
stream?: boolean;
|
|
36
|
+
ttftMs?: number;
|
|
37
|
+
responseText?: string;
|
|
38
|
+
}): void;
|
|
39
|
+
}
|
|
40
|
+
export {};
|
package/dist/capture.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { contextSnapshot } from "./context.js";
|
|
2
|
+
import { scrub, templateHash } from "./template.js";
|
|
3
|
+
import { SDK_VERSION } from "./version.js";
|
|
4
|
+
function get(value, key) {
|
|
5
|
+
return value && typeof value === "object" ? value[key] : undefined;
|
|
6
|
+
}
|
|
7
|
+
function first(value) {
|
|
8
|
+
return Array.isArray(value) ? value[0] : undefined;
|
|
9
|
+
}
|
|
10
|
+
function number(value) {
|
|
11
|
+
const parsed = Number(value);
|
|
12
|
+
return value == null || !Number.isFinite(parsed) ? undefined : parsed;
|
|
13
|
+
}
|
|
14
|
+
function usage(response) {
|
|
15
|
+
const value = get(response, "usage") ?? get(response, "usage_metadata") ?? get(response, "usageMetadata");
|
|
16
|
+
const prompt = get(value, "prompt_tokens_details") ?? get(value, "input_tokens_details")
|
|
17
|
+
?? get(value, "promptTokensDetails") ?? get(value, "inputTokensDetails");
|
|
18
|
+
const completion = get(value, "completion_tokens_details") ?? get(value, "output_tokens_details")
|
|
19
|
+
?? get(value, "completionTokensDetails") ?? get(value, "outputTokensDetails");
|
|
20
|
+
const cacheCreation = get(value, "cache_creation") ?? get(value, "cacheCreation");
|
|
21
|
+
return {
|
|
22
|
+
input_tokens: number(get(value, "prompt_tokens") ?? get(value, "input_tokens") ?? get(value, "promptTokenCount")),
|
|
23
|
+
output_tokens: number(get(value, "completion_tokens") ?? get(value, "output_tokens") ?? get(value, "candidatesTokenCount")),
|
|
24
|
+
cache_read_tokens: number(get(value, "cache_read_input_tokens") ?? get(prompt, "cached_tokens") ?? get(value, "cachedContentTokenCount")),
|
|
25
|
+
cache_write_tokens: number(get(value, "cache_creation_input_tokens")
|
|
26
|
+
?? get(prompt, "cache_write_tokens") ?? get(value, "cacheCreationInputTokens")
|
|
27
|
+
?? get(prompt, "cacheWriteTokens")),
|
|
28
|
+
cache_write_5m_tokens: number(get(cacheCreation, "ephemeral_5m_input_tokens")
|
|
29
|
+
?? get(cacheCreation, "ephemeral5mInputTokens")),
|
|
30
|
+
cache_write_1h_tokens: number(get(cacheCreation, "ephemeral_1h_input_tokens")
|
|
31
|
+
?? get(cacheCreation, "ephemeral1hInputTokens")),
|
|
32
|
+
reasoning_tokens: number(get(completion, "reasoning_tokens") ?? get(value, "thoughtsTokenCount")),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function responseText(response) {
|
|
36
|
+
const direct = get(response, "output_text") ?? get(response, "text");
|
|
37
|
+
if (typeof direct === "string")
|
|
38
|
+
return direct;
|
|
39
|
+
const message = get(first(get(response, "choices")), "message");
|
|
40
|
+
const content = get(message, "content");
|
|
41
|
+
if (typeof content === "string")
|
|
42
|
+
return content;
|
|
43
|
+
const blocks = get(response, "content");
|
|
44
|
+
if (Array.isArray(blocks)) {
|
|
45
|
+
const joined = blocks.map((block) => get(block, "text")).filter((item) => typeof item === "string").join("");
|
|
46
|
+
if (joined)
|
|
47
|
+
return joined;
|
|
48
|
+
}
|
|
49
|
+
const outputs = get(response, "output");
|
|
50
|
+
if (Array.isArray(outputs)) {
|
|
51
|
+
const joined = outputs.flatMap((output) => {
|
|
52
|
+
const content = get(output, "content");
|
|
53
|
+
if (!Array.isArray(content))
|
|
54
|
+
return [];
|
|
55
|
+
return content.map((block) => get(block, "text") ?? get(block, "output_text"));
|
|
56
|
+
}).filter((item) => typeof item === "string").join("");
|
|
57
|
+
if (joined)
|
|
58
|
+
return joined;
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
export function chunkText(chunk) {
|
|
63
|
+
const delta = get(first(get(chunk, "choices")), "delta") ?? get(chunk, "delta");
|
|
64
|
+
const text = get(delta, "content") ?? get(delta, "text") ?? get(chunk, "text");
|
|
65
|
+
return typeof text === "string" ? text : undefined;
|
|
66
|
+
}
|
|
67
|
+
function stopReason(response) {
|
|
68
|
+
const value = get(response, "stop_reason") ?? get(response, "status") ?? get(first(get(response, "choices")), "finish_reason");
|
|
69
|
+
return value == null ? undefined : String(value);
|
|
70
|
+
}
|
|
71
|
+
function toolNames(request) {
|
|
72
|
+
if (!Array.isArray(request.tools))
|
|
73
|
+
return undefined;
|
|
74
|
+
const names = request.tools.flatMap((tool) => {
|
|
75
|
+
const name = get(get(tool, "function"), "name") ?? get(tool, "name");
|
|
76
|
+
return name ? [{ name: String(name) }] : [];
|
|
77
|
+
});
|
|
78
|
+
return names.length ? names : undefined;
|
|
79
|
+
}
|
|
80
|
+
const SDK_DIR = (() => {
|
|
81
|
+
try {
|
|
82
|
+
return new URL(".", import.meta.url).pathname;
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return "metergraph-sdk-dir-unavailable";
|
|
86
|
+
}
|
|
87
|
+
})();
|
|
88
|
+
function frames(stack, appRoot, skip) {
|
|
89
|
+
if (!stack)
|
|
90
|
+
return [];
|
|
91
|
+
const result = [];
|
|
92
|
+
for (const line of stack.split("\n").slice(1)) {
|
|
93
|
+
const match = line.match(/^\s*at\s+(?:(.*?)\s+\()?(.+?):(\d+):\d+\)?$/);
|
|
94
|
+
if (!match)
|
|
95
|
+
continue;
|
|
96
|
+
const [, fn = "<anonymous>", file, lineNo] = match;
|
|
97
|
+
if (!file || !lineNo || !file.includes(appRoot))
|
|
98
|
+
continue;
|
|
99
|
+
if (["node_modules", "node:internal", SDK_DIR, ...skip].some((value) => file.includes(value)))
|
|
100
|
+
continue;
|
|
101
|
+
result.push({
|
|
102
|
+
m: file.slice(file.indexOf(appRoot) + appRoot.length).replace(/^\//, ""),
|
|
103
|
+
f: fn,
|
|
104
|
+
l: Number(lineNo),
|
|
105
|
+
});
|
|
106
|
+
if (result.length === 5)
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
return result;
|
|
110
|
+
}
|
|
111
|
+
export class CaptureRuntime {
|
|
112
|
+
transport;
|
|
113
|
+
options;
|
|
114
|
+
constructor(transport, options) {
|
|
115
|
+
this.transport = transport;
|
|
116
|
+
this.options = options;
|
|
117
|
+
}
|
|
118
|
+
start(provider, endpoint, request, stack, context = contextSnapshot()) {
|
|
119
|
+
return {
|
|
120
|
+
provider,
|
|
121
|
+
endpoint,
|
|
122
|
+
request,
|
|
123
|
+
context,
|
|
124
|
+
started: performance.now(),
|
|
125
|
+
ts: new Date().toISOString(),
|
|
126
|
+
frames: frames(stack, this.options.appRoot, this.options.skipFrames),
|
|
127
|
+
done: false,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
finish(state, response, extra = {}) {
|
|
131
|
+
if (state.done)
|
|
132
|
+
return;
|
|
133
|
+
state.done = true;
|
|
134
|
+
const captureText = state.context.captureText ?? this.options.captureText;
|
|
135
|
+
const text = (value, kind) => {
|
|
136
|
+
if (!captureText || value == null)
|
|
137
|
+
return { value: undefined, truncated: false };
|
|
138
|
+
try {
|
|
139
|
+
value = this.options.redact ? this.options.redact(value, kind) : value;
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return { value: "<redaction-failed>", truncated: false };
|
|
143
|
+
}
|
|
144
|
+
const bytes = new TextEncoder().encode(value);
|
|
145
|
+
if (bytes.byteLength <= this.options.textMaxBytes)
|
|
146
|
+
return { value, truncated: false };
|
|
147
|
+
const clipped = new TextDecoder().decode(bytes.slice(0, this.options.textMaxBytes - 24));
|
|
148
|
+
return { value: `${clipped}\n<metergraph:truncated>`, truncated: true };
|
|
149
|
+
};
|
|
150
|
+
const request = text(JSON.stringify(scrub(state.request)), "request");
|
|
151
|
+
const output = text(extra.responseText ?? responseText(response), "response");
|
|
152
|
+
const firstFrame = state.frames[0];
|
|
153
|
+
this.transport.enqueue({
|
|
154
|
+
ts: state.ts,
|
|
155
|
+
route: state.context.route,
|
|
156
|
+
provider: state.provider,
|
|
157
|
+
model: state.request.model,
|
|
158
|
+
...usage(response),
|
|
159
|
+
latency_ms: Math.round(performance.now() - state.started),
|
|
160
|
+
status: extra.status ?? (extra.error ? "error" : stopReason(response) ?? "success"),
|
|
161
|
+
session_id: state.context.sessionId,
|
|
162
|
+
template_hash: templateHash(state.request),
|
|
163
|
+
unit_name: state.context.unitName,
|
|
164
|
+
unit_count: state.context.unitCount,
|
|
165
|
+
tool_calls: toolNames(state.request),
|
|
166
|
+
endpoint: state.endpoint,
|
|
167
|
+
request_id: get(response, "_request_id") ?? get(response, "response_id") ?? get(response, "id"),
|
|
168
|
+
batch: state.request.batch === true,
|
|
169
|
+
batch_custom_id: state.request.batch_custom_id,
|
|
170
|
+
// Explicit positive consent stamp; the worker never infers opt-in from
|
|
171
|
+
// content fields that happen to be present.
|
|
172
|
+
content_opted_in: captureText,
|
|
173
|
+
request_json: request.value,
|
|
174
|
+
response_text: output.value,
|
|
175
|
+
text_truncated: request.truncated || output.truncated,
|
|
176
|
+
stream: extra.stream ?? false,
|
|
177
|
+
ttft_ms: extra.ttftMs,
|
|
178
|
+
func: state.context.funcName
|
|
179
|
+
?? (firstFrame ? `${firstFrame.m}:${firstFrame.f}:${firstFrame.l}` : undefined),
|
|
180
|
+
module: firstFrame?.m,
|
|
181
|
+
frames_json: state.frames,
|
|
182
|
+
tags: state.context.tags,
|
|
183
|
+
environment: this.options.environment,
|
|
184
|
+
error: Boolean(extra.error),
|
|
185
|
+
error_type: extra.error instanceof Error ? extra.error.name : undefined,
|
|
186
|
+
sdk: "js",
|
|
187
|
+
sdk_version: SDK_VERSION,
|
|
188
|
+
runtime: typeof process === "undefined" ? "edge" : `node-${process.versions.node}`,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface RouteConfig {
|
|
2
|
+
version?: number;
|
|
3
|
+
enabled?: boolean;
|
|
4
|
+
incumbent_model?: string;
|
|
5
|
+
challenger_model?: string;
|
|
6
|
+
model?: string;
|
|
7
|
+
traffic_percent?: number;
|
|
8
|
+
percentage?: number;
|
|
9
|
+
allocation?: number;
|
|
10
|
+
salt?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function chooseModel(route: string, fallback: string, sessionKey: string | undefined, config: RouteConfig | undefined): string;
|
|
13
|
+
export declare class ConfigPoller {
|
|
14
|
+
private readonly token;
|
|
15
|
+
private readonly baseUrl;
|
|
16
|
+
private readonly pollMs;
|
|
17
|
+
private readonly hardTtlMs;
|
|
18
|
+
private etag?;
|
|
19
|
+
private routes;
|
|
20
|
+
private lastSuccess;
|
|
21
|
+
private timer?;
|
|
22
|
+
constructor(token: string, baseUrl: string, pollMs?: number, hardTtlMs?: number);
|
|
23
|
+
poll(): Promise<boolean>;
|
|
24
|
+
modelFor(route: string, fallback: string, sessionKey?: string): string;
|
|
25
|
+
stop(): void;
|
|
26
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
function bucket(value) {
|
|
2
|
+
let hash = 0xcbf29ce484222325n;
|
|
3
|
+
for (const byte of new TextEncoder().encode(value)) {
|
|
4
|
+
hash ^= BigInt(byte);
|
|
5
|
+
hash = BigInt.asUintN(64, hash * 0x100000001b3n);
|
|
6
|
+
}
|
|
7
|
+
return Number(hash) / 2 ** 64 * 100;
|
|
8
|
+
}
|
|
9
|
+
export function chooseModel(route, fallback, sessionKey, config) {
|
|
10
|
+
if (!config || config.enabled === false)
|
|
11
|
+
return fallback;
|
|
12
|
+
const incumbent = config.incumbent_model ?? fallback;
|
|
13
|
+
const challenger = config.challenger_model ?? config.model;
|
|
14
|
+
if (!challenger || !sessionKey)
|
|
15
|
+
return incumbent;
|
|
16
|
+
const percentage = Math.max(0, Math.min(100, Number(config.traffic_percent ?? config.percentage ?? config.allocation ?? 0)));
|
|
17
|
+
const seed = `${route}:${config.version ?? ""}:${config.salt ?? ""}:${sessionKey}`;
|
|
18
|
+
return bucket(seed) < percentage ? challenger : incumbent;
|
|
19
|
+
}
|
|
20
|
+
export class ConfigPoller {
|
|
21
|
+
token;
|
|
22
|
+
baseUrl;
|
|
23
|
+
pollMs;
|
|
24
|
+
hardTtlMs;
|
|
25
|
+
etag;
|
|
26
|
+
routes = {};
|
|
27
|
+
lastSuccess = 0;
|
|
28
|
+
timer;
|
|
29
|
+
constructor(token, baseUrl, pollMs = 30_000, hardTtlMs = 120_000) {
|
|
30
|
+
this.token = token;
|
|
31
|
+
this.baseUrl = baseUrl;
|
|
32
|
+
this.pollMs = pollMs;
|
|
33
|
+
this.hardTtlMs = hardTtlMs;
|
|
34
|
+
void this.poll();
|
|
35
|
+
this.timer = setInterval(() => void this.poll(), Math.max(1_000, pollMs));
|
|
36
|
+
this.timer.unref?.();
|
|
37
|
+
}
|
|
38
|
+
async poll() {
|
|
39
|
+
try {
|
|
40
|
+
const headers = { Authorization: `Bearer ${this.token}` };
|
|
41
|
+
if (this.etag)
|
|
42
|
+
headers["If-None-Match"] = this.etag;
|
|
43
|
+
const response = await fetch(`${this.baseUrl.replace(/\/$/, "")}/v1/config`, { headers });
|
|
44
|
+
if (response.status === 304) {
|
|
45
|
+
this.lastSuccess = Date.now();
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
if (!response.ok)
|
|
49
|
+
return false;
|
|
50
|
+
const body = await response.json();
|
|
51
|
+
this.routes = body.routes ?? {};
|
|
52
|
+
this.etag = response.headers.get("etag") ?? undefined;
|
|
53
|
+
this.lastSuccess = Date.now();
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
modelFor(route, fallback, sessionKey) {
|
|
61
|
+
if (!this.lastSuccess || Date.now() - this.lastSuccess > this.hardTtlMs)
|
|
62
|
+
return fallback;
|
|
63
|
+
return chooseModel(route, fallback, sessionKey, this.routes[route]);
|
|
64
|
+
}
|
|
65
|
+
stop() {
|
|
66
|
+
if (this.timer)
|
|
67
|
+
clearInterval(this.timer);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface CaptureContext {
|
|
2
|
+
route?: string;
|
|
3
|
+
sessionId?: string;
|
|
4
|
+
tags: Record<string, string>;
|
|
5
|
+
unitName?: string;
|
|
6
|
+
unitCount?: number;
|
|
7
|
+
captureText?: boolean;
|
|
8
|
+
funcName?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface RouteOptions {
|
|
11
|
+
unit?: string;
|
|
12
|
+
unitCount?: number;
|
|
13
|
+
tags?: Record<string, unknown>;
|
|
14
|
+
captureText?: boolean;
|
|
15
|
+
}
|
|
16
|
+
export declare function contextSnapshot(): CaptureContext;
|
|
17
|
+
export declare function runWithContext<T>(context: CaptureContext, fn: () => T): T;
|
|
18
|
+
export declare function route<T>(name: string, fn: () => T | Promise<T>, options?: RouteOptions): Promise<T>;
|
|
19
|
+
export declare function setSession(sessionId?: string): void;
|
|
20
|
+
export declare function setTags(tags: Record<string, unknown>): void;
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
const storage = new AsyncLocalStorage();
|
|
3
|
+
let ambient = { tags: {} };
|
|
4
|
+
export function contextSnapshot() {
|
|
5
|
+
const value = storage.getStore() ?? ambient;
|
|
6
|
+
return { ...value, tags: { ...value.tags } };
|
|
7
|
+
}
|
|
8
|
+
export function runWithContext(context, fn) {
|
|
9
|
+
return storage.run(context, fn);
|
|
10
|
+
}
|
|
11
|
+
export async function route(name, fn, options = {}) {
|
|
12
|
+
const parent = contextSnapshot();
|
|
13
|
+
const child = {
|
|
14
|
+
...parent,
|
|
15
|
+
route: name,
|
|
16
|
+
tags: {
|
|
17
|
+
...parent.tags,
|
|
18
|
+
...Object.fromEntries(Object.entries(options.tags ?? {}).map(([key, value]) => [key, String(value)])),
|
|
19
|
+
},
|
|
20
|
+
unitName: options.unit ?? parent.unitName,
|
|
21
|
+
unitCount: options.unit ? (options.unitCount ?? 1) : parent.unitCount,
|
|
22
|
+
captureText: options.captureText ?? parent.captureText,
|
|
23
|
+
};
|
|
24
|
+
return storage.run(child, fn);
|
|
25
|
+
}
|
|
26
|
+
export function setSession(sessionId) {
|
|
27
|
+
const store = storage.getStore();
|
|
28
|
+
if (store)
|
|
29
|
+
store.sessionId = sessionId;
|
|
30
|
+
else
|
|
31
|
+
ambient = { ...ambient, sessionId };
|
|
32
|
+
}
|
|
33
|
+
export function setTags(tags) {
|
|
34
|
+
const normalized = Object.fromEntries(Object.entries(tags).map(([key, value]) => [key, String(value)]));
|
|
35
|
+
const store = storage.getStore();
|
|
36
|
+
if (store)
|
|
37
|
+
store.tags = { ...store.tags, ...normalized };
|
|
38
|
+
else
|
|
39
|
+
ambient = { ...ambient, tags: { ...ambient.tags, ...normalized } };
|
|
40
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { route, setSession, setTags, type RouteOptions } from "./context.js";
|
|
2
|
+
import { track } from "./track.js";
|
|
3
|
+
import { type TransportMode, type WaitUntil } from "./transport.js";
|
|
4
|
+
export interface MetergraphOptions {
|
|
5
|
+
token?: string;
|
|
6
|
+
ingestUrl?: string;
|
|
7
|
+
captureText?: boolean;
|
|
8
|
+
redact?: (text: string, kind: "request" | "response") => string;
|
|
9
|
+
appRoot?: string;
|
|
10
|
+
skipFrames?: string[];
|
|
11
|
+
environment?: string;
|
|
12
|
+
disabled?: boolean;
|
|
13
|
+
transport?: TransportMode;
|
|
14
|
+
queueSize?: number;
|
|
15
|
+
batchSize?: number;
|
|
16
|
+
flushMs?: number;
|
|
17
|
+
configPollMs?: number;
|
|
18
|
+
configHardTtlMs?: number;
|
|
19
|
+
}
|
|
20
|
+
export interface OutcomeOptions {
|
|
21
|
+
model: string;
|
|
22
|
+
taskCompleted: boolean;
|
|
23
|
+
sessionKey?: string;
|
|
24
|
+
feedbackScore?: number;
|
|
25
|
+
turnsToResolution?: number;
|
|
26
|
+
escalated?: boolean;
|
|
27
|
+
abandoned?: boolean;
|
|
28
|
+
editDistanceRatio?: number;
|
|
29
|
+
regenerationCount?: number;
|
|
30
|
+
eventId?: string;
|
|
31
|
+
}
|
|
32
|
+
export declare const DEFAULT_INGEST_URL = "https://d2xus7mp8zdv6t.cloudfront.net";
|
|
33
|
+
export declare function init(options?: MetergraphOptions): void;
|
|
34
|
+
export declare function modelFor(routeName: string, fallback: string, sessionKey?: string): string;
|
|
35
|
+
export declare function recordOutcome(routeName: string, options: OutcomeOptions): boolean;
|
|
36
|
+
export declare function bindWaitUntil(value: {
|
|
37
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
38
|
+
} | WaitUntil): void;
|
|
39
|
+
export declare function flush(timeoutMs?: number): Promise<boolean>;
|
|
40
|
+
export declare function shutdown(): Promise<void>;
|
|
41
|
+
export declare function wrapHandler<TArgs extends unknown[], TResult>(handler: (...args: TArgs) => TResult | Promise<TResult>): (...args: TArgs) => Promise<TResult>;
|
|
42
|
+
/**
|
|
43
|
+
* Wrap an OpenAI, Anthropic, or Google client for capture.
|
|
44
|
+
*
|
|
45
|
+
* Calls init() automatically, so with env-var configuration this is the
|
|
46
|
+
* only setup line needed. Call init(...) first to pass options in code.
|
|
47
|
+
*/
|
|
48
|
+
export declare function wrap<T extends Record<PropertyKey, any>>(client: T, provider?: "openai" | "anthropic" | "google"): T;
|
|
49
|
+
export declare const wrapClient: typeof wrap;
|
|
50
|
+
export { route, setSession, setTags, track };
|
|
51
|
+
export type { RouteOptions, TransportMode };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { CaptureRuntime } from "./capture.js";
|
|
2
|
+
import { ConfigPoller } from "./config.js";
|
|
3
|
+
import { contextSnapshot, route, setSession, setTags, } from "./context.js";
|
|
4
|
+
import { track } from "./track.js";
|
|
5
|
+
import { Transport } from "./transport.js";
|
|
6
|
+
import { setCaptureRuntime, wrap as wrapProvider } from "./wrap.js";
|
|
7
|
+
let initialized = false;
|
|
8
|
+
let warnedNoToken = false;
|
|
9
|
+
let transport;
|
|
10
|
+
let config;
|
|
11
|
+
export const DEFAULT_INGEST_URL = "https://d2xus7mp8zdv6t.cloudfront.net";
|
|
12
|
+
function env(name) {
|
|
13
|
+
return typeof process === "undefined" ? undefined : process.env[name];
|
|
14
|
+
}
|
|
15
|
+
function envBool(name, fallback) {
|
|
16
|
+
const value = env(name);
|
|
17
|
+
return value === undefined
|
|
18
|
+
? fallback
|
|
19
|
+
: !["0", "false", "no", "off"].includes(value.toLowerCase());
|
|
20
|
+
}
|
|
21
|
+
export function init(options = {}) {
|
|
22
|
+
if (initialized)
|
|
23
|
+
return;
|
|
24
|
+
if (env("METERGRAPH_DISABLED") === "1" || options.disabled) {
|
|
25
|
+
initialized = true;
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const token = options.token ?? env("METERGRAPH_APP_TOKEN");
|
|
29
|
+
const ingestUrl = options.ingestUrl ?? env("METERGRAPH_INGEST_URL") ?? DEFAULT_INGEST_URL;
|
|
30
|
+
if (!token || !ingestUrl) {
|
|
31
|
+
// Stay uninitialized so a later init() that supplies a token succeeds.
|
|
32
|
+
if (!warnedNoToken) {
|
|
33
|
+
warnedNoToken = true;
|
|
34
|
+
console.warn("Metergraph capture disabled: token and ingest URL are required");
|
|
35
|
+
}
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
initialized = true;
|
|
39
|
+
try {
|
|
40
|
+
transport = new Transport(token, ingestUrl, {
|
|
41
|
+
queueSize: options.queueSize ?? Number(env("METERGRAPH_QUEUE_SIZE") ?? 2_000),
|
|
42
|
+
batchSize: options.batchSize ?? Number(env("METERGRAPH_BATCH_SIZE") ?? 100),
|
|
43
|
+
flushMs: options.flushMs ?? Number(env("METERGRAPH_FLUSH_MS") ?? 5_000),
|
|
44
|
+
mode: options.transport ?? "auto",
|
|
45
|
+
});
|
|
46
|
+
setCaptureRuntime(new CaptureRuntime(transport, {
|
|
47
|
+
captureText: options.captureText ?? envBool("METERGRAPH_CAPTURE_TEXT", false),
|
|
48
|
+
redact: options.redact,
|
|
49
|
+
appRoot: options.appRoot ?? (typeof process === "undefined" ? "" : process.cwd()),
|
|
50
|
+
skipFrames: options.skipFrames ?? [],
|
|
51
|
+
environment: options.environment ?? env("METERGRAPH_ENV"),
|
|
52
|
+
textMaxBytes: Number(env("METERGRAPH_TEXT_MAX_BYTES") ?? 100_000),
|
|
53
|
+
}));
|
|
54
|
+
config = new ConfigPoller(token, ingestUrl, options.configPollMs, options.configHardTtlMs);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
transport = undefined;
|
|
58
|
+
config = undefined;
|
|
59
|
+
setCaptureRuntime();
|
|
60
|
+
console.warn("Metergraph initialization failed; application is running uninstrumented");
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export function modelFor(routeName, fallback, sessionKey) {
|
|
64
|
+
return config?.modelFor(routeName, fallback, sessionKey ?? contextSnapshot().sessionId) ?? fallback;
|
|
65
|
+
}
|
|
66
|
+
export function recordOutcome(routeName, options) {
|
|
67
|
+
const routeNameClean = String(routeName).trim().slice(0, 512);
|
|
68
|
+
const model = String(options.model).trim().slice(0, 512);
|
|
69
|
+
const sessionKey = String(options.sessionKey ?? contextSnapshot().sessionId ?? "").trim().slice(0, 512);
|
|
70
|
+
const randomId = globalThis.crypto?.randomUUID?.()
|
|
71
|
+
?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
72
|
+
const eventId = String(options.eventId ?? randomId).trim().slice(0, 128);
|
|
73
|
+
const integerIn = (value, minimum) => value === undefined
|
|
74
|
+
|| (Number.isInteger(value) && value >= minimum && value <= 1_000_000);
|
|
75
|
+
if (!transport || !routeNameClean || !model || !sessionKey || !eventId
|
|
76
|
+
|| typeof options.taskCompleted !== "boolean"
|
|
77
|
+
|| (options.feedbackScore !== undefined
|
|
78
|
+
&& (!Number.isFinite(options.feedbackScore) || options.feedbackScore < -1 || options.feedbackScore > 1))
|
|
79
|
+
|| !integerIn(options.turnsToResolution, 1)
|
|
80
|
+
|| !integerIn(options.regenerationCount, 0)
|
|
81
|
+
|| (options.editDistanceRatio !== undefined
|
|
82
|
+
&& (!Number.isFinite(options.editDistanceRatio)
|
|
83
|
+
|| options.editDistanceRatio < 0 || options.editDistanceRatio > 1))
|
|
84
|
+
|| (options.escalated !== undefined && typeof options.escalated !== "boolean")
|
|
85
|
+
|| (options.abandoned !== undefined && typeof options.abandoned !== "boolean")) {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
return transport.enqueue({
|
|
89
|
+
event_type: "outcome",
|
|
90
|
+
event_id: eventId,
|
|
91
|
+
ts: new Date().toISOString(),
|
|
92
|
+
route: routeNameClean,
|
|
93
|
+
session_id: sessionKey,
|
|
94
|
+
model,
|
|
95
|
+
task_completed: options.taskCompleted,
|
|
96
|
+
feedback_score: options.feedbackScore,
|
|
97
|
+
turns_to_resolution: options.turnsToResolution,
|
|
98
|
+
escalated: options.escalated,
|
|
99
|
+
abandoned: options.abandoned,
|
|
100
|
+
edit_distance_ratio: options.editDistanceRatio,
|
|
101
|
+
regeneration_count: options.regenerationCount,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
export function bindWaitUntil(value) {
|
|
105
|
+
transport?.bindWaitUntil(value);
|
|
106
|
+
}
|
|
107
|
+
export async function flush(timeoutMs = 3_000) {
|
|
108
|
+
return transport?.flush(timeoutMs) ?? true;
|
|
109
|
+
}
|
|
110
|
+
export async function shutdown() {
|
|
111
|
+
config?.stop();
|
|
112
|
+
config = undefined;
|
|
113
|
+
await transport?.shutdown();
|
|
114
|
+
transport = undefined;
|
|
115
|
+
setCaptureRuntime();
|
|
116
|
+
}
|
|
117
|
+
export function wrapHandler(handler) {
|
|
118
|
+
return async (...args) => {
|
|
119
|
+
try {
|
|
120
|
+
return await handler(...args);
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
await flush();
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Wrap an OpenAI, Anthropic, or Google client for capture.
|
|
129
|
+
*
|
|
130
|
+
* Calls init() automatically, so with env-var configuration this is the
|
|
131
|
+
* only setup line needed. Call init(...) first to pass options in code.
|
|
132
|
+
*/
|
|
133
|
+
export function wrap(client, provider) {
|
|
134
|
+
init();
|
|
135
|
+
return wrapProvider(client, provider);
|
|
136
|
+
}
|
|
137
|
+
export const wrapClient = wrap;
|
|
138
|
+
export { route, setSession, setTags, track };
|
package/dist/template.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const sensitive = new Set(["api_key", "apikey", "authorization", "headers", "token", "secret"]);
|
|
2
|
+
export function scrub(value) {
|
|
3
|
+
if (Array.isArray(value))
|
|
4
|
+
return value.map(scrub);
|
|
5
|
+
if (value && typeof value === "object") {
|
|
6
|
+
return Object.fromEntries(Object.entries(value)
|
|
7
|
+
.filter(([key]) => !sensitive.has(key.toLowerCase()))
|
|
8
|
+
.map(([key, item]) => [key, scrub(item)]));
|
|
9
|
+
}
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
function normalized(value) {
|
|
13
|
+
if (Array.isArray(value))
|
|
14
|
+
return value.map(normalized);
|
|
15
|
+
if (value && typeof value === "object") {
|
|
16
|
+
return Object.fromEntries(Object.entries(value)
|
|
17
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
18
|
+
.map(([key, item]) => [key, normalized(item)]));
|
|
19
|
+
}
|
|
20
|
+
if (typeof value !== "string")
|
|
21
|
+
return value;
|
|
22
|
+
return value
|
|
23
|
+
.replace(/\b[0-9a-f]{8}-[0-9a-f-]{27,}\b/gi, "<uuid>")
|
|
24
|
+
.replace(/\b[^\s@]+@[^\s@]+\.[^\s@]+\b/g, "<email>")
|
|
25
|
+
.replace(/\bhttps?:\/\/\S+/g, "<url>")
|
|
26
|
+
.replace(/\b[A-Za-z0-9_-]{24,}\b/g, "<token>")
|
|
27
|
+
.replace(/(^|[^A-Za-z])[-+]?\d+(?:\.\d+)?(?=$|[^A-Za-z])/g, "$1<n>")
|
|
28
|
+
.replace(/\s+/g, " ")
|
|
29
|
+
.trim();
|
|
30
|
+
}
|
|
31
|
+
function fnv1a(value) {
|
|
32
|
+
let hash = 0xcbf29ce484222325n;
|
|
33
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
34
|
+
hash ^= BigInt(value.charCodeAt(index));
|
|
35
|
+
hash = BigInt.asUintN(64, hash * 0x100000001b3n);
|
|
36
|
+
}
|
|
37
|
+
return hash.toString(16).padStart(16, "0");
|
|
38
|
+
}
|
|
39
|
+
export function templateHash(request) {
|
|
40
|
+
return fnv1a(JSON.stringify(normalized(scrub(request))));
|
|
41
|
+
}
|
package/dist/track.d.ts
ADDED
package/dist/track.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { contextSnapshot, runWithContext } from "./context.js";
|
|
2
|
+
export function track(nameOrFn, maybeFn) {
|
|
3
|
+
const fn = typeof nameOrFn === "string" ? maybeFn : nameOrFn;
|
|
4
|
+
if (typeof fn !== "function")
|
|
5
|
+
throw new TypeError("track requires a function");
|
|
6
|
+
const funcName = typeof nameOrFn === "string" ? nameOrFn : fn.name || "<anonymous>";
|
|
7
|
+
const wrapped = function (...args) {
|
|
8
|
+
return runWithContext({ ...contextSnapshot(), funcName }, () => fn.apply(this, args));
|
|
9
|
+
};
|
|
10
|
+
return wrapped;
|
|
11
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export type TransportMode = "auto" | "background" | "buffered";
|
|
2
|
+
export type WaitUntil = (promise: Promise<unknown>) => void;
|
|
3
|
+
export declare const MAX_BATCH_BYTES: number;
|
|
4
|
+
export interface TransportOptions {
|
|
5
|
+
queueSize?: number;
|
|
6
|
+
batchSize?: number;
|
|
7
|
+
flushMs?: number;
|
|
8
|
+
mode?: TransportMode;
|
|
9
|
+
}
|
|
10
|
+
export declare class Transport {
|
|
11
|
+
private readonly token;
|
|
12
|
+
private readonly baseUrl;
|
|
13
|
+
private readonly queue;
|
|
14
|
+
private readonly mode;
|
|
15
|
+
private readonly queueSize;
|
|
16
|
+
private readonly batchSize;
|
|
17
|
+
private timer?;
|
|
18
|
+
private waitUntil?;
|
|
19
|
+
private scheduled;
|
|
20
|
+
private inFlight;
|
|
21
|
+
private fatal;
|
|
22
|
+
private dropped;
|
|
23
|
+
private errors;
|
|
24
|
+
private retryAt;
|
|
25
|
+
private backoffMs;
|
|
26
|
+
constructor(token: string, baseUrl: string, options?: TransportOptions);
|
|
27
|
+
bindWaitUntil(value: {
|
|
28
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
29
|
+
} | WaitUntil): void;
|
|
30
|
+
enqueue(row: Record<string, unknown>): boolean;
|
|
31
|
+
private schedule;
|
|
32
|
+
flush(timeoutMs?: number): Promise<boolean>;
|
|
33
|
+
private deliver;
|
|
34
|
+
shutdown(): Promise<void>;
|
|
35
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
export const MAX_BATCH_BYTES = 512 * 1024;
|
|
2
|
+
function detectedMode() {
|
|
3
|
+
const env = typeof process === "undefined" ? {} : process.env;
|
|
4
|
+
const agent = typeof navigator === "undefined" ? "" : navigator.userAgent;
|
|
5
|
+
return env?.AWS_LAMBDA_FUNCTION_NAME || env?.VERCEL || agent === "Cloudflare-Workers"
|
|
6
|
+
? "buffered"
|
|
7
|
+
: "background";
|
|
8
|
+
}
|
|
9
|
+
async function gzipBody(body) {
|
|
10
|
+
if (typeof CompressionStream === "undefined")
|
|
11
|
+
return body;
|
|
12
|
+
const source = new Blob([body]).stream();
|
|
13
|
+
return new Response(source.pipeThrough(new CompressionStream("gzip"))).arrayBuffer();
|
|
14
|
+
}
|
|
15
|
+
export class Transport {
|
|
16
|
+
token;
|
|
17
|
+
baseUrl;
|
|
18
|
+
queue = [];
|
|
19
|
+
mode;
|
|
20
|
+
queueSize;
|
|
21
|
+
batchSize;
|
|
22
|
+
timer;
|
|
23
|
+
waitUntil;
|
|
24
|
+
scheduled = false;
|
|
25
|
+
inFlight = Promise.resolve();
|
|
26
|
+
fatal = false;
|
|
27
|
+
dropped = 0;
|
|
28
|
+
errors = 0;
|
|
29
|
+
retryAt = 0;
|
|
30
|
+
backoffMs = 1_000;
|
|
31
|
+
constructor(token, baseUrl, options = {}) {
|
|
32
|
+
this.token = token;
|
|
33
|
+
this.baseUrl = baseUrl;
|
|
34
|
+
this.queueSize = Math.max(1, options.queueSize ?? 2_000);
|
|
35
|
+
this.batchSize = Math.max(1, Math.min(1_000, options.batchSize ?? 100));
|
|
36
|
+
this.mode = options.mode === "auto" || !options.mode ? detectedMode() : options.mode;
|
|
37
|
+
if (this.mode === "background") {
|
|
38
|
+
this.timer = setInterval(() => void this.flush(), Math.max(50, options.flushMs ?? 5_000));
|
|
39
|
+
this.timer.unref?.();
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
bindWaitUntil(value) {
|
|
43
|
+
this.waitUntil = typeof value === "function" ? value : value.waitUntil.bind(value);
|
|
44
|
+
}
|
|
45
|
+
enqueue(row) {
|
|
46
|
+
if (this.fatal || this.queue.length >= this.queueSize) {
|
|
47
|
+
this.dropped += 1;
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
this.queue.push(row);
|
|
51
|
+
if (this.queue.length >= this.batchSize)
|
|
52
|
+
this.schedule();
|
|
53
|
+
else if (this.mode === "buffered")
|
|
54
|
+
this.schedule();
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
schedule() {
|
|
58
|
+
if (this.scheduled)
|
|
59
|
+
return;
|
|
60
|
+
this.scheduled = true;
|
|
61
|
+
const work = Promise.resolve().then(async () => {
|
|
62
|
+
this.scheduled = false;
|
|
63
|
+
await this.flush();
|
|
64
|
+
});
|
|
65
|
+
if (this.waitUntil)
|
|
66
|
+
this.waitUntil(work);
|
|
67
|
+
else if (this.mode === "buffered")
|
|
68
|
+
void work;
|
|
69
|
+
}
|
|
70
|
+
async flush(timeoutMs = 3_000) {
|
|
71
|
+
const deadline = Date.now() + Math.max(0, timeoutMs);
|
|
72
|
+
const work = async () => {
|
|
73
|
+
while (this.queue.length && Date.now() < deadline) {
|
|
74
|
+
const batch = this.queue.splice(0, this.batchSize);
|
|
75
|
+
await this.deliver(batch);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
this.inFlight = this.inFlight.then(work, work);
|
|
79
|
+
await new Promise((resolve) => {
|
|
80
|
+
const timer = setTimeout(resolve, Math.max(0, deadline - Date.now()));
|
|
81
|
+
timer.unref?.();
|
|
82
|
+
void this.inFlight.finally(() => {
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
resolve();
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
return this.queue.length === 0;
|
|
88
|
+
}
|
|
89
|
+
async deliver(rows) {
|
|
90
|
+
if (this.fatal || Date.now() < this.retryAt) {
|
|
91
|
+
this.dropped += rows.length;
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const encoded = new TextEncoder().encode(JSON.stringify({
|
|
95
|
+
schema_version: 1,
|
|
96
|
+
rows,
|
|
97
|
+
meta: { dropped: this.dropped, transport_errors: this.errors },
|
|
98
|
+
}));
|
|
99
|
+
const raw = encoded.buffer.slice(encoded.byteOffset, encoded.byteOffset + encoded.byteLength);
|
|
100
|
+
const compressed = raw.byteLength > 32 * 1024;
|
|
101
|
+
const body = compressed ? await gzipBody(raw) : raw;
|
|
102
|
+
if (body.byteLength > MAX_BATCH_BYTES) {
|
|
103
|
+
if (rows.length === 1) {
|
|
104
|
+
this.dropped += 1;
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const midpoint = Math.floor(rows.length / 2);
|
|
108
|
+
await this.deliver(rows.slice(0, midpoint));
|
|
109
|
+
await this.deliver(rows.slice(midpoint));
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const response = await fetch(`${this.baseUrl.replace(/\/$/, "")}/v1/ingest`, {
|
|
114
|
+
method: "POST",
|
|
115
|
+
headers: {
|
|
116
|
+
Authorization: `Bearer ${this.token}`,
|
|
117
|
+
"Content-Type": "application/json",
|
|
118
|
+
...(compressed && body !== raw ? { "Content-Encoding": "gzip" } : {}),
|
|
119
|
+
},
|
|
120
|
+
body: new Blob([body], { type: "application/json" }),
|
|
121
|
+
keepalive: this.mode === "buffered" && body.byteLength <= 64 * 1024,
|
|
122
|
+
});
|
|
123
|
+
if (response.status === 401 || response.status === 403) {
|
|
124
|
+
this.fatal = true;
|
|
125
|
+
console.warn("Metergraph authentication failed; capture disabled for this process");
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (response.status !== 202)
|
|
129
|
+
throw new Error(`ingest returned ${response.status}`);
|
|
130
|
+
this.backoffMs = 1_000;
|
|
131
|
+
this.retryAt = 0;
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
this.errors += 1;
|
|
135
|
+
this.dropped += rows.length;
|
|
136
|
+
this.retryAt = Date.now() + this.backoffMs;
|
|
137
|
+
this.backoffMs = Math.min(this.backoffMs * 2, 60_000);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async shutdown() {
|
|
141
|
+
if (this.timer)
|
|
142
|
+
clearInterval(this.timer);
|
|
143
|
+
await this.flush();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const SDK_VERSION = "0.1.0";
|
package/dist/version.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const SDK_VERSION = "0.1.0";
|
package/dist/wrap.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type CaptureRuntime } from "./capture.js";
|
|
2
|
+
type AnyRecord = Record<PropertyKey, any>;
|
|
3
|
+
export declare function setCaptureRuntime(value?: CaptureRuntime): void;
|
|
4
|
+
export declare function wrap<T extends AnyRecord>(client: T, provider?: "openai" | "anthropic" | "google"): T;
|
|
5
|
+
export declare const wrapClient: typeof wrap;
|
|
6
|
+
export {};
|
package/dist/wrap.js
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import { chunkText } from "./capture.js";
|
|
2
|
+
import { contextSnapshot } from "./context.js";
|
|
3
|
+
let runtime;
|
|
4
|
+
const seenBatchItems = new Set();
|
|
5
|
+
export function setCaptureRuntime(value) {
|
|
6
|
+
runtime = value;
|
|
7
|
+
}
|
|
8
|
+
function requestFrom(args) {
|
|
9
|
+
const first = args[0];
|
|
10
|
+
return first && typeof first === "object" ? { ...first } : {};
|
|
11
|
+
}
|
|
12
|
+
function get(value, key) {
|
|
13
|
+
return value && typeof value === "object" ? value[key] : undefined;
|
|
14
|
+
}
|
|
15
|
+
function markBatchItem(key) {
|
|
16
|
+
if (seenBatchItems.has(key))
|
|
17
|
+
return false;
|
|
18
|
+
if (seenBatchItems.size >= 100_000)
|
|
19
|
+
seenBatchItems.clear();
|
|
20
|
+
seenBatchItems.add(key);
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
function captureOpenAIBatchItem(capture, item, sourceId, context, stack) {
|
|
24
|
+
const response = get(item, "response");
|
|
25
|
+
const error = get(item, "error");
|
|
26
|
+
if (response == null && error == null)
|
|
27
|
+
return;
|
|
28
|
+
const customId = String(get(item, "custom_id") ?? "");
|
|
29
|
+
const itemId = String(get(item, "id") ?? customId);
|
|
30
|
+
const responseId = String(get(response, "request_id") ?? itemId);
|
|
31
|
+
if (!markBatchItem(`openai:${sourceId}:${itemId}:${responseId}`))
|
|
32
|
+
return;
|
|
33
|
+
const body = get(response, "body") ?? {};
|
|
34
|
+
const normalized = body && typeof body === "object"
|
|
35
|
+
? { ...body, _request_id: responseId }
|
|
36
|
+
: body;
|
|
37
|
+
const request = {
|
|
38
|
+
model: get(body, "model"),
|
|
39
|
+
batch: true,
|
|
40
|
+
service_tier: "batch",
|
|
41
|
+
batch_custom_id: customId || undefined,
|
|
42
|
+
batch_item_id: itemId || undefined,
|
|
43
|
+
};
|
|
44
|
+
const endpoint = get(body, "object") === "response"
|
|
45
|
+
? "batch.responses"
|
|
46
|
+
: "batch.chat.completions";
|
|
47
|
+
const state = capture.start("openai", endpoint, request, stack, context);
|
|
48
|
+
const statusCode = Number(get(response, "status_code"));
|
|
49
|
+
capture.finish(state, normalized, {
|
|
50
|
+
status: error != null || (Number.isFinite(statusCode) && statusCode >= 400)
|
|
51
|
+
? "error"
|
|
52
|
+
: undefined,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
function captureOpenAIBatchContent(capture, content, sourceId, context, stack) {
|
|
56
|
+
try {
|
|
57
|
+
for (const line of content.split(/\r?\n/)) {
|
|
58
|
+
if (!line.trim())
|
|
59
|
+
continue;
|
|
60
|
+
try {
|
|
61
|
+
const item = JSON.parse(line);
|
|
62
|
+
if (item && typeof item === "object" && "custom_id" in item
|
|
63
|
+
&& ("response" in item || "error" in item)) {
|
|
64
|
+
captureOpenAIBatchItem(capture, item, sourceId, context, stack);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch { /* a non-batch JSONL line is ignored */ }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
catch { /* capture cannot break file consumption */ }
|
|
71
|
+
}
|
|
72
|
+
function wrapOpenAIFileResponse(response, capture, sourceId, context, stack) {
|
|
73
|
+
if (!response || typeof response !== "object")
|
|
74
|
+
return response;
|
|
75
|
+
return new Proxy(response, {
|
|
76
|
+
get(target, property) {
|
|
77
|
+
if (property === "text" && typeof target.text === "function") {
|
|
78
|
+
return async () => {
|
|
79
|
+
const text = await target.text();
|
|
80
|
+
captureOpenAIBatchContent(capture, text, sourceId, context, stack);
|
|
81
|
+
return text;
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
if (property === "arrayBuffer" && typeof target.arrayBuffer === "function") {
|
|
85
|
+
return async () => {
|
|
86
|
+
const value = await target.arrayBuffer();
|
|
87
|
+
captureOpenAIBatchContent(capture, new TextDecoder().decode(value), sourceId, context, stack);
|
|
88
|
+
return value;
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
if (property === "blob" && typeof target.blob === "function") {
|
|
92
|
+
return async () => {
|
|
93
|
+
const value = await target.blob();
|
|
94
|
+
captureOpenAIBatchContent(capture, await value.text(), sourceId, context, stack);
|
|
95
|
+
return value;
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
const value = Reflect.get(target, property, target);
|
|
99
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
function captureAnthropicBatchItem(capture, item, batchId, context, stack) {
|
|
104
|
+
const result = get(item, "result");
|
|
105
|
+
const resultType = String(get(result, "type") ?? "");
|
|
106
|
+
const customId = String(get(item, "custom_id") ?? "");
|
|
107
|
+
if (!resultType || !markBatchItem(`anthropic:${batchId}:${customId}:${resultType}`))
|
|
108
|
+
return;
|
|
109
|
+
const message = get(result, "message") ?? {};
|
|
110
|
+
const state = capture.start("anthropic", "batch.messages", {
|
|
111
|
+
model: get(message, "model"),
|
|
112
|
+
batch: true,
|
|
113
|
+
service_tier: "batch",
|
|
114
|
+
batch_custom_id: customId || undefined,
|
|
115
|
+
batch_id: batchId || undefined,
|
|
116
|
+
}, stack, context);
|
|
117
|
+
capture.finish(state, message, {
|
|
118
|
+
status: resultType === "succeeded" ? undefined : "error",
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
function wrapAnthropicBatchResults(result, capture, batchId, context, stack) {
|
|
122
|
+
if (!result || typeof result[Symbol.asyncIterator] !== "function")
|
|
123
|
+
return result;
|
|
124
|
+
return new Proxy(result, {
|
|
125
|
+
get(target, property, receiver) {
|
|
126
|
+
if (property === Symbol.asyncIterator) {
|
|
127
|
+
return async function* () {
|
|
128
|
+
for await (const item of target) {
|
|
129
|
+
try {
|
|
130
|
+
captureAnthropicBatchItem(capture, item, batchId, context, stack);
|
|
131
|
+
}
|
|
132
|
+
catch { /* capture cannot break result iteration */ }
|
|
133
|
+
yield item;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
const value = Reflect.get(target, property, receiver);
|
|
138
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
function patchOpenAIBatchContent(owner, method) {
|
|
143
|
+
if (!owner || typeof owner[method] !== "function")
|
|
144
|
+
return false;
|
|
145
|
+
if (owner[method].__metergraph_batch__)
|
|
146
|
+
return true;
|
|
147
|
+
const original = owner[method];
|
|
148
|
+
const wrapped = function (...args) {
|
|
149
|
+
const capture = runtime;
|
|
150
|
+
if (!capture)
|
|
151
|
+
return original.apply(owner, args);
|
|
152
|
+
const sourceId = String(args[0] ?? "unknown");
|
|
153
|
+
const context = contextSnapshot();
|
|
154
|
+
const stack = new Error().stack;
|
|
155
|
+
const result = original.apply(owner, args);
|
|
156
|
+
if (result && typeof result.then === "function") {
|
|
157
|
+
return result.then((response) => (wrapOpenAIFileResponse(response, capture, sourceId, context, stack)));
|
|
158
|
+
}
|
|
159
|
+
return wrapOpenAIFileResponse(result, capture, sourceId, context, stack);
|
|
160
|
+
};
|
|
161
|
+
wrapped.__metergraph_batch__ = true;
|
|
162
|
+
owner[method] = wrapped;
|
|
163
|
+
return true;
|
|
164
|
+
}
|
|
165
|
+
function patchAnthropicBatchResults(owner) {
|
|
166
|
+
if (!owner || typeof owner.results !== "function")
|
|
167
|
+
return false;
|
|
168
|
+
if (owner.results.__metergraph_batch__)
|
|
169
|
+
return true;
|
|
170
|
+
const original = owner.results;
|
|
171
|
+
const wrapped = function (...args) {
|
|
172
|
+
const capture = runtime;
|
|
173
|
+
if (!capture)
|
|
174
|
+
return original.apply(owner, args);
|
|
175
|
+
const batchId = String(args[0] ?? "unknown");
|
|
176
|
+
const context = contextSnapshot();
|
|
177
|
+
const stack = new Error().stack;
|
|
178
|
+
const result = original.apply(owner, args);
|
|
179
|
+
if (result && typeof result.then === "function") {
|
|
180
|
+
return result.then((resolved) => (wrapAnthropicBatchResults(resolved, capture, batchId, context, stack)));
|
|
181
|
+
}
|
|
182
|
+
return wrapAnthropicBatchResults(result, capture, batchId, context, stack);
|
|
183
|
+
};
|
|
184
|
+
wrapped.__metergraph_batch__ = true;
|
|
185
|
+
owner.results = wrapped;
|
|
186
|
+
return true;
|
|
187
|
+
}
|
|
188
|
+
function streamProxy(stream, state, capture) {
|
|
189
|
+
let last;
|
|
190
|
+
let ttftMs;
|
|
191
|
+
const parts = [];
|
|
192
|
+
const observe = (chunk) => {
|
|
193
|
+
last = chunk;
|
|
194
|
+
const text = chunkText(chunk);
|
|
195
|
+
if (text) {
|
|
196
|
+
ttftMs ??= Math.round(performance.now() - state.started);
|
|
197
|
+
parts.push(text);
|
|
198
|
+
}
|
|
199
|
+
return chunk;
|
|
200
|
+
};
|
|
201
|
+
const finish = (response = last, error, status) => {
|
|
202
|
+
capture.finish(state, response, {
|
|
203
|
+
error,
|
|
204
|
+
status,
|
|
205
|
+
stream: true,
|
|
206
|
+
ttftMs,
|
|
207
|
+
responseText: parts.join("") || undefined,
|
|
208
|
+
});
|
|
209
|
+
};
|
|
210
|
+
if (typeof stream.on === "function") {
|
|
211
|
+
stream.on("error", (error) => finish(last, error));
|
|
212
|
+
}
|
|
213
|
+
return new Proxy(stream, {
|
|
214
|
+
get(target, property, receiver) {
|
|
215
|
+
if (property === Symbol.asyncIterator && typeof target[Symbol.asyncIterator] === "function") {
|
|
216
|
+
return async function* () {
|
|
217
|
+
try {
|
|
218
|
+
for await (const chunk of target) {
|
|
219
|
+
const value = observe(chunk);
|
|
220
|
+
const usageOnly = state.provider === "openai"
|
|
221
|
+
&& state.endpoint === "chat.completions"
|
|
222
|
+
&& Array.isArray(chunk?.choices)
|
|
223
|
+
&& chunk.choices.length === 0
|
|
224
|
+
&& chunk.usage != null;
|
|
225
|
+
if (!usageOnly)
|
|
226
|
+
yield value;
|
|
227
|
+
}
|
|
228
|
+
let final = last;
|
|
229
|
+
if (typeof target.finalMessage === "function") {
|
|
230
|
+
try {
|
|
231
|
+
final = await target.finalMessage();
|
|
232
|
+
}
|
|
233
|
+
catch { /* captured by stream error */ }
|
|
234
|
+
}
|
|
235
|
+
finish(final);
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
finish(last, error);
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
if (property === "finalMessage" && typeof target.finalMessage === "function") {
|
|
244
|
+
return async (...args) => {
|
|
245
|
+
try {
|
|
246
|
+
const final = await target.finalMessage(...args);
|
|
247
|
+
finish(final);
|
|
248
|
+
return final;
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
finish(last, error);
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
if (property === "close" || property === "abort") {
|
|
257
|
+
const original = Reflect.get(target, property, receiver);
|
|
258
|
+
if (typeof original !== "function")
|
|
259
|
+
return original;
|
|
260
|
+
return (...args) => {
|
|
261
|
+
try {
|
|
262
|
+
return original.apply(target, args);
|
|
263
|
+
}
|
|
264
|
+
finally {
|
|
265
|
+
finish(last, undefined, "abandoned");
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
const value = Reflect.get(target, property, receiver);
|
|
270
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
function patch(owner, method, provider, endpoint) {
|
|
275
|
+
if (!owner || typeof owner[method] !== "function")
|
|
276
|
+
return false;
|
|
277
|
+
if (owner[method].__metergraph__)
|
|
278
|
+
return true;
|
|
279
|
+
const original = owner[method];
|
|
280
|
+
const wrapped = function (...args) {
|
|
281
|
+
const capture = runtime;
|
|
282
|
+
if (!capture)
|
|
283
|
+
return original.apply(owner, args);
|
|
284
|
+
const incoming = requestFrom(args);
|
|
285
|
+
const patchUsage = typeof process === "undefined"
|
|
286
|
+
|| process.env.METERGRAPH_PATCH_STREAM_USAGE !== "0";
|
|
287
|
+
if (provider === "openai"
|
|
288
|
+
&& endpoint === "chat.completions"
|
|
289
|
+
&& incoming.stream === true
|
|
290
|
+
&& incoming.stream_options == null
|
|
291
|
+
&& patchUsage) {
|
|
292
|
+
args = [{ ...incoming, stream_options: { include_usage: true } }, ...args.slice(1)];
|
|
293
|
+
}
|
|
294
|
+
const state = capture.start(provider, endpoint, requestFrom(args), new Error().stack);
|
|
295
|
+
let result;
|
|
296
|
+
try {
|
|
297
|
+
result = original.apply(owner, args);
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
capture.finish(state, undefined, { error });
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
const complete = (response) => {
|
|
304
|
+
const request = requestFrom(args);
|
|
305
|
+
const streaming = endpoint.endsWith(".stream") || request.stream === true;
|
|
306
|
+
if (streaming && response && (response[Symbol.asyncIterator] || response.finalMessage)) {
|
|
307
|
+
return streamProxy(response, state, capture);
|
|
308
|
+
}
|
|
309
|
+
capture.finish(state, response);
|
|
310
|
+
return response;
|
|
311
|
+
};
|
|
312
|
+
if (result && typeof result.then === "function") {
|
|
313
|
+
return result.then(complete, (error) => {
|
|
314
|
+
capture.finish(state, undefined, { error });
|
|
315
|
+
throw error;
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
return complete(result);
|
|
319
|
+
};
|
|
320
|
+
wrapped.__metergraph__ = true;
|
|
321
|
+
owner[method] = wrapped;
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
export function wrap(client, provider) {
|
|
325
|
+
const name = provider ?? (client.models?.generateContent
|
|
326
|
+
? "google"
|
|
327
|
+
: client.chat || client.responses ? "openai" : "anthropic");
|
|
328
|
+
let patched = 0;
|
|
329
|
+
if (name === "google") {
|
|
330
|
+
patched += Number(patch(client.models, "generateContent", name, "models.generate_content"));
|
|
331
|
+
patched += Number(patch(client.models, "generateContentStream", name, "models.generate_content.stream"));
|
|
332
|
+
}
|
|
333
|
+
patched += Number(patch(client.chat?.completions, "create", name, "chat.completions"));
|
|
334
|
+
patched += Number(patch(client.responses, "create", name, "responses"));
|
|
335
|
+
patched += Number(patch(client.responses, "stream", name, "responses.stream"));
|
|
336
|
+
patched += Number(patch(client.messages, "create", name, "messages"));
|
|
337
|
+
patched += Number(patch(client.messages, "stream", name, "messages.stream"));
|
|
338
|
+
if (name === "openai") {
|
|
339
|
+
patched += Number(patchOpenAIBatchContent(client.files, "content"));
|
|
340
|
+
patched += Number(patchOpenAIBatchContent(client.files, "retrieveContent"));
|
|
341
|
+
}
|
|
342
|
+
else if (name === "anthropic") {
|
|
343
|
+
patched += Number(patchAnthropicBatchResults(client.messages?.batches));
|
|
344
|
+
patched += Number(patchAnthropicBatchResults(client.beta?.messages?.batches));
|
|
345
|
+
}
|
|
346
|
+
if (!patched)
|
|
347
|
+
console.warn(`Metergraph found no supported methods on ${name} client`);
|
|
348
|
+
return client;
|
|
349
|
+
}
|
|
350
|
+
export const wrapClient = wrap;
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "metergraph",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Fire-and-forget LLM spend capture for Metergraph",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": ["dist", "README.md"],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsc -p tsconfig.json",
|
|
17
|
+
"test": "npm run build && node --test test/*.test.mjs"
|
|
18
|
+
},
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=18"
|
|
21
|
+
},
|
|
22
|
+
"license": "Apache-2.0",
|
|
23
|
+
"dependencies": {},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@types/node": "^24.0.0",
|
|
26
|
+
"typescript": "^5.8.0"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"@anthropic-ai/sdk": ">=0.30",
|
|
30
|
+
"@google/genai": ">=1",
|
|
31
|
+
"openai": ">=4"
|
|
32
|
+
},
|
|
33
|
+
"peerDependenciesMeta": {
|
|
34
|
+
"openai": {"optional": true},
|
|
35
|
+
"@anthropic-ai/sdk": {"optional": true},
|
|
36
|
+
"@google/genai": {"optional": true}
|
|
37
|
+
}
|
|
38
|
+
}
|