metergraph 0.6.0 → 0.6.3

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
@@ -13,31 +13,39 @@ active; later explicit calls are ignored and produce one generic warning
13
13
  without option names, token values, or other secrets.
14
14
 
15
15
  ```ts
16
- import { init, wrap, route, trace, modelFor, recordOutcome, setSession } from "metergraph";
16
+ import { init, wrap, route, trace, modelFor, recordOutcome, withSession } from "metergraph";
17
17
  import OpenAI from "openai";
18
18
 
19
19
  init({ repository: "owner/repository" });
20
20
  // new Anthropic() and new GoogleGenAI({}) wrap the same way.
21
21
  const client = wrap(new OpenAI());
22
- setSession("ticket-123");
23
22
 
24
23
  let model = "gpt-4.1-mini";
25
- await trace("ticket-workflow", () =>
26
- route("ticket-classifier", async () => {
27
- model = modelFor("ticket-classifier", { default: model });
28
- await client.chat.completions.create({ model, messages: [] });
29
- }, { unit: "answer" })
30
- );
31
-
32
- recordOutcome("ticket-classifier", {
33
- model,
34
- taskCompleted: true,
35
- feedbackScore: 1,
36
- turnsToResolution: 2,
37
- escalated: false,
24
+ await withSession("ticket-123", async () => {
25
+ await trace("ticket-workflow", () =>
26
+ route("ticket-classifier", async () => {
27
+ model = modelFor("ticket-classifier", { default: model });
28
+ await client.chat.completions.create({ model, messages: [] });
29
+ }, { unit: "answer" })
30
+ );
31
+
32
+ recordOutcome("ticket-classifier", {
33
+ model,
34
+ taskCompleted: true,
35
+ feedbackScore: 1,
36
+ turnsToResolution: 2,
37
+ escalated: false,
38
+ });
38
39
  });
39
40
  ```
40
41
 
42
+ Use `withContext({ sessionId, tags }, fn)`, `withSession(sessionId, fn)`, or
43
+ `withTags(tags, fn)` for request and job identity. These callback scopes follow
44
+ Node's asynchronous execution and isolate concurrent jobs. Legacy
45
+ `setSession()` and `setTags()` remain available inside an active Metergraph
46
+ scope, but warn and do nothing when called outside one. Use `setDefaultTags()`
47
+ only for deliberate process-wide tags; sessions are always execution-scoped.
48
+
41
49
  ## Vercel AI SDK
42
50
 
43
51
  Use Metergraph as language-model middleware. It records each actual provider
@@ -121,12 +129,13 @@ identity, it warns once and continues capture without repository attribution.
121
129
  Metergraph captures the scrubbed provider request and a
122
130
  normalized response envelope, including assistant content and tool calls, by
123
131
  default. Provider credentials and transport headers are removed. Request and
124
- response are each limited to 100 KiB of UTF-8 with an explicit truncation
125
- marker. Set `METERGRAPH_CAPTURE_TEXT=0`, initialize with
126
- `captureText: false`, or set `captureText: false` on an individual `route()` or
127
- `trace()` to opt out for sensitive operations. The public open-source server
128
- still discards content; hosted workspaces retain it under their metadata
129
- retention period.
132
+ response are each limited to 1 MiB of UTF-8 by default with an explicit
133
+ truncation marker. Set `METERGRAPH_TEXT_MAX_BYTES` or initialize with
134
+ `textMaxBytes` to raise the per-field limit. Set `METERGRAPH_CAPTURE_TEXT=0`,
135
+ initialize with `captureText: false`, or set `captureText: false` on an
136
+ individual `route()` or `trace()` to opt out for sensitive operations. The
137
+ public open-source server still discards content; hosted workspaces retain it
138
+ under their metadata retention period.
130
139
 
131
140
  `trace(name, fn, { traceId, parentSpanId, captureText })` groups calls into a
132
141
  logical trace using `AsyncLocalStorage`. Nested traces reuse the active trace
@@ -134,7 +143,7 @@ unless given a different trace ID. Calls outside a trace become one-span
134
143
  traces. Manual IDs can join work across process boundaries; automatic W3C HTTP
135
144
  propagation is not included.
136
145
 
137
- Actual wire batches never exceed 512 KiB after optional gzip.
146
+ Actual wire batches never exceed 4 MiB after optional gzip.
138
147
  Long-running Node processes use an unref'd
139
148
  background timer. On Workers or Vercel, call
140
149
  `bindWaitUntil(ctx)` once per request. On Lambda, use `wrapHandler(handler)`
package/dist/capture.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type CaptureContext } from "./context.js";
2
2
  import type { Transport } from "./transport.js";
3
+ export declare const DEFAULT_TEXT_MAX_BYTES: number;
3
4
  export interface RuntimeOptions {
4
5
  captureText: boolean;
5
6
  redact?: (text: string, kind: "request" | "response") => string;
package/dist/capture.js CHANGED
@@ -1,11 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CaptureRuntime = void 0;
3
+ exports.CaptureRuntime = exports.DEFAULT_TEXT_MAX_BYTES = void 0;
4
4
  exports.chunkText = chunkText;
5
5
  const node_crypto_1 = require("node:crypto");
6
6
  const context_js_1 = require("./context.js");
7
7
  const template_js_1 = require("./template.js");
8
8
  const version_js_1 = require("./version.js");
9
+ exports.DEFAULT_TEXT_MAX_BYTES = 1024 * 1024;
9
10
  function get(value, key) {
10
11
  return value && typeof value === "object" ? value[key] : undefined;
11
12
  }
@@ -112,6 +113,43 @@ function stopReason(response) {
112
113
  const normalized = get(value, "unified") ?? get(value, "raw") ?? value;
113
114
  return normalized == null ? undefined : String(normalized);
114
115
  }
116
+ function normalizeFinishReason(value) {
117
+ const normalized = value.trim().toLowerCase().replace(/[\s_]+/g, "-");
118
+ if (["stop", "end-turn", "stop-sequence", "completed", "succeeded"].includes(normalized)) {
119
+ return "stop";
120
+ }
121
+ if (["length", "max-tokens", "max-output-tokens"].includes(normalized))
122
+ return "length";
123
+ if (["content-filter", "safety", "blocked"].includes(normalized))
124
+ return "content-filter";
125
+ if (["tool-calls", "tool-use", "function-call"].includes(normalized))
126
+ return "tool-calls";
127
+ if (["error", "failed"].includes(normalized))
128
+ return "error";
129
+ if (["other", "unknown"].includes(normalized))
130
+ return "other";
131
+ return normalized;
132
+ }
133
+ function finishReasonDetails(response) {
134
+ const responseStatus = get(response, "status");
135
+ const incompleteReason = responseStatus === "incomplete"
136
+ ? get(get(response, "incomplete_details"), "reason")
137
+ : undefined;
138
+ const value = get(response, "stop_reason") ?? incompleteReason ?? responseStatus
139
+ ?? get(response, "finishReason") ?? get(response, "finish_reason")
140
+ ?? get(first(get(response, "choices")), "finish_reason");
141
+ const unified = get(value, "unified");
142
+ const rawValue = get(value, "raw") ?? (unified === undefined ? value : undefined);
143
+ const source = unified ?? rawValue;
144
+ if (source == null)
145
+ return {};
146
+ const finishReason = normalizeFinishReason(String(source));
147
+ const raw = rawValue == null ? undefined : String(rawValue);
148
+ return {
149
+ finishReason,
150
+ finishReasonRaw: raw !== undefined && raw !== finishReason ? raw : undefined,
151
+ };
152
+ }
115
153
  function toolNames(request) {
116
154
  if (!Array.isArray(request.tools))
117
155
  return undefined;
@@ -460,6 +498,10 @@ class CaptureRuntime {
460
498
  const request = text(JSON.stringify((0, template_js_1.scrub)(state.request)), "request");
461
499
  const fullTools = toolEvents((0, template_js_1.scrub)(state.request), response, extra.responseChunks);
462
500
  const status = extra.status ?? (extra.error ? "error" : stopReason(response) ?? "success");
501
+ const { finishReason, finishReasonRaw } = finishReasonDetails(response);
502
+ const statusCode = extra.error || extra.status === "error" || finishReason === "error"
503
+ ? "error"
504
+ : "unset";
463
505
  const output = text(JSON.stringify(responseEnvelope(response, extra.responseText, fullTools, extra.error, status)), "response");
464
506
  let toolTruncated = false;
465
507
  let persistedTools;
@@ -498,6 +540,9 @@ class CaptureRuntime {
498
540
  ...usage(response),
499
541
  latency_ms: Math.round(performance.now() - state.started),
500
542
  status,
543
+ status_code: statusCode,
544
+ finish_reason: finishReason,
545
+ finish_reason_raw: finishReasonRaw,
501
546
  session_id: state.context.sessionId,
502
547
  conversation_id: state.context.sessionId,
503
548
  trace_id: state.traceId,
@@ -529,7 +574,7 @@ class CaptureRuntime {
529
574
  frames_json: state.frames,
530
575
  tags: state.context.tags,
531
576
  environment: this.options.environment,
532
- error: Boolean(extra.error),
577
+ error: statusCode === "error",
533
578
  error_type: extra.error instanceof Error ? extra.error.name : undefined,
534
579
  sdk: "js",
535
580
  sdk_version: version_js_1.SDK_VERSION,
package/dist/context.d.ts CHANGED
@@ -21,8 +21,16 @@ export interface TraceOptions {
21
21
  parentSpanId?: string;
22
22
  captureText?: boolean;
23
23
  }
24
+ export interface ContextOptions {
25
+ sessionId?: string;
26
+ tags?: Record<string, unknown>;
27
+ }
24
28
  export declare function contextSnapshot(): CaptureContext;
25
29
  export declare function runWithContext<T>(context: CaptureContext, fn: () => T): T;
30
+ export declare function withContext<T>(options: ContextOptions, fn: () => T): T;
31
+ export declare function withSession<T>(sessionId: string, fn: () => T): T;
32
+ export declare function withTags<T>(tags: Record<string, unknown>, fn: () => T): T;
33
+ export declare function setDefaultTags(tags: Record<string, unknown>): void;
26
34
  export declare function route<T>(name: string, fn: () => T | Promise<T>, options?: RouteOptions): Promise<T>;
27
35
  export declare function trace<T>(name: string, fn: () => T | Promise<T>, options?: TraceOptions): T | Promise<T>;
28
36
  export declare function setSession(sessionId?: string): void;
package/dist/context.js CHANGED
@@ -2,6 +2,10 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.contextSnapshot = contextSnapshot;
4
4
  exports.runWithContext = runWithContext;
5
+ exports.withContext = withContext;
6
+ exports.withSession = withSession;
7
+ exports.withTags = withTags;
8
+ exports.setDefaultTags = setDefaultTags;
5
9
  exports.route = route;
6
10
  exports.trace = trace;
7
11
  exports.setSession = setSession;
@@ -9,14 +13,37 @@ exports.setTags = setTags;
9
13
  const node_async_hooks_1 = require("node:async_hooks");
10
14
  const node_crypto_1 = require("node:crypto");
11
15
  const storage = new node_async_hooks_1.AsyncLocalStorage();
12
- let ambient = { tags: {} };
16
+ let defaultTags = {};
17
+ let warnedSessionOutsideScope = false;
18
+ let warnedTagsOutsideScope = false;
19
+ function normalizeTags(tags) {
20
+ return Object.fromEntries(Object.entries(tags).map(([key, value]) => [key, String(value)]));
21
+ }
13
22
  function contextSnapshot() {
14
- const value = storage.getStore() ?? ambient;
23
+ const value = storage.getStore() ?? { tags: defaultTags };
15
24
  return { ...value, tags: { ...value.tags } };
16
25
  }
17
26
  function runWithContext(context, fn) {
18
27
  return storage.run(context, fn);
19
28
  }
29
+ function withContext(options, fn) {
30
+ const parent = contextSnapshot();
31
+ const child = {
32
+ ...parent,
33
+ sessionId: options.sessionId ?? parent.sessionId,
34
+ tags: { ...parent.tags, ...normalizeTags(options.tags ?? {}) },
35
+ };
36
+ return storage.run(child, fn);
37
+ }
38
+ function withSession(sessionId, fn) {
39
+ return withContext({ sessionId }, fn);
40
+ }
41
+ function withTags(tags, fn) {
42
+ return withContext({ tags }, fn);
43
+ }
44
+ function setDefaultTags(tags) {
45
+ defaultTags = normalizeTags(tags);
46
+ }
20
47
  async function route(name, fn, options = {}) {
21
48
  const parent = contextSnapshot();
22
49
  const child = {
@@ -48,16 +75,23 @@ function trace(name, fn, options = {}) {
48
75
  }
49
76
  function setSession(sessionId) {
50
77
  const store = storage.getStore();
51
- if (store)
52
- store.sessionId = sessionId;
53
- else
54
- ambient = { ...ambient, sessionId };
78
+ if (!store) {
79
+ if (!warnedSessionOutsideScope) {
80
+ warnedSessionOutsideScope = true;
81
+ console.warn("Metergraph setSession() requires an active Metergraph context; use withSession() or withContext().");
82
+ }
83
+ return;
84
+ }
85
+ storage.enterWith({ ...store, sessionId, tags: { ...store.tags } });
55
86
  }
56
87
  function setTags(tags) {
57
- const normalized = Object.fromEntries(Object.entries(tags).map(([key, value]) => [key, String(value)]));
58
88
  const store = storage.getStore();
59
- if (store)
60
- store.tags = { ...store.tags, ...normalized };
61
- else
62
- ambient = { ...ambient, tags: { ...ambient.tags, ...normalized } };
89
+ if (!store) {
90
+ if (!warnedTagsOutsideScope) {
91
+ warnedTagsOutsideScope = true;
92
+ console.warn("Metergraph setTags() requires an active Metergraph context; use withTags() or withContext().");
93
+ }
94
+ return;
95
+ }
96
+ storage.enterWith({ ...store, tags: { ...store.tags, ...normalizeTags(tags) } });
63
97
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { route, setSession, setTags, trace, type RouteOptions, type TraceOptions } from "./context.js";
1
+ import { route, setDefaultTags, setSession, setTags, trace, withContext, withSession, withTags, type ContextOptions, type RouteOptions, type TraceOptions } from "./context.js";
2
2
  import { BatchFirstIneligibleError, batchFirst, type BatchFirstMetadata, type BatchFirstPolicy, type BatchFirstProvider, type BatchFirstRequest, type BatchFirstResult, type BatchFirstSource, type LateBatchInfo } from "./batch-first.js";
3
3
  import { track } from "./track.js";
4
4
  import { type TransportMode, type WaitUntil } from "./transport.js";
@@ -19,6 +19,7 @@ export interface MetergraphOptions {
19
19
  flushMs?: number;
20
20
  configPollMs?: number;
21
21
  configHardTtlMs?: number;
22
+ textMaxBytes?: number;
22
23
  }
23
24
  export type VercelAISDKMiddlewareOptions<TVersion extends VercelAISDKSpecificationVersion = "v3"> = MetergraphOptions & VercelAISDKCompatibilityOptions<TVersion>;
24
25
  export interface ModelForOptions {
@@ -62,8 +63,8 @@ export declare const wrapClient: typeof wrap;
62
63
  */
63
64
  export declare function vercelAISDKMiddleware(options: MetergraphOptions & VercelAISDKMiddlewareVersionOptions): VercelAISDKMiddleware<"v2">;
64
65
  export declare function vercelAISDKMiddleware<TVersion extends VercelAISDKSpecificationVersion = "v3">(options?: MetergraphOptions & VercelAISDKMiddlewareSpecificationOptions<TVersion>): VercelAISDKMiddleware<TVersion>;
65
- export { route, setSession, setTags, trace, track };
66
- export type { RouteOptions, TraceOptions, TransportMode, VercelAISDKMiddleware, VercelAISDKSpecificationVersion, };
66
+ export { route, setDefaultTags, setSession, setTags, trace, track, withContext, withSession, withTags, };
67
+ export type { ContextOptions, RouteOptions, TraceOptions, TransportMode, VercelAISDKMiddleware, VercelAISDKSpecificationVersion, };
67
68
  /**
68
69
  * Explicit, opt-in batch-first execution over a provider's Batch API —
69
70
  * never enabled by wrap()/capture defaults or by an environment variable.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BatchFirstIneligibleError = exports.batchFirst = exports.track = exports.trace = exports.setTags = exports.setSession = exports.route = exports.wrapClient = exports.DEFAULT_INGEST_URL = void 0;
3
+ exports.BatchFirstIneligibleError = exports.batchFirst = exports.withTags = exports.withSession = exports.withContext = exports.track = exports.trace = exports.setTags = exports.setSession = exports.setDefaultTags = exports.route = exports.wrapClient = exports.DEFAULT_INGEST_URL = void 0;
4
4
  exports.init = init;
5
5
  exports.modelFor = modelFor;
6
6
  exports.recordOutcome = recordOutcome;
@@ -14,9 +14,13 @@ const capture_js_1 = require("./capture.js");
14
14
  const config_js_1 = require("./config.js");
15
15
  const context_js_1 = require("./context.js");
16
16
  Object.defineProperty(exports, "route", { enumerable: true, get: function () { return context_js_1.route; } });
17
+ Object.defineProperty(exports, "setDefaultTags", { enumerable: true, get: function () { return context_js_1.setDefaultTags; } });
17
18
  Object.defineProperty(exports, "setSession", { enumerable: true, get: function () { return context_js_1.setSession; } });
18
19
  Object.defineProperty(exports, "setTags", { enumerable: true, get: function () { return context_js_1.setTags; } });
19
20
  Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return context_js_1.trace; } });
21
+ Object.defineProperty(exports, "withContext", { enumerable: true, get: function () { return context_js_1.withContext; } });
22
+ Object.defineProperty(exports, "withSession", { enumerable: true, get: function () { return context_js_1.withSession; } });
23
+ Object.defineProperty(exports, "withTags", { enumerable: true, get: function () { return context_js_1.withTags; } });
20
24
  const batch_first_js_1 = require("./batch-first.js");
21
25
  Object.defineProperty(exports, "BatchFirstIneligibleError", { enumerable: true, get: function () { return batch_first_js_1.BatchFirstIneligibleError; } });
22
26
  Object.defineProperty(exports, "batchFirst", { enumerable: true, get: function () { return batch_first_js_1.batchFirst; } });
@@ -94,6 +98,8 @@ function init(options = {}) {
94
98
  sessionManager = repoConfig
95
99
  ? new session_js_1.SessionManager(token, ingestUrl, repoConfig.repository, version_js_1.SDK_VERSION)
96
100
  : undefined;
101
+ const configuredTextMaxBytes = options.textMaxBytes
102
+ ?? Number(env("METERGRAPH_TEXT_MAX_BYTES") ?? capture_js_1.DEFAULT_TEXT_MAX_BYTES);
97
103
  transport = new transport_js_1.Transport(token, ingestUrl, {
98
104
  queueSize: options.queueSize ?? Number(env("METERGRAPH_QUEUE_SIZE") ?? 2_000),
99
105
  batchSize: options.batchSize ?? Number(env("METERGRAPH_BATCH_SIZE") ?? 100),
@@ -108,7 +114,9 @@ function init(options = {}) {
108
114
  repoRoot: repoConfig?.repoRoot,
109
115
  skipFrames: options.skipFrames ?? [],
110
116
  environment: options.environment ?? env("METERGRAPH_ENV"),
111
- textMaxBytes: Math.min(100 * 1024, Math.max(1, Number(env("METERGRAPH_TEXT_MAX_BYTES") ?? 100 * 1024))),
117
+ textMaxBytes: Number.isFinite(configuredTextMaxBytes)
118
+ ? Math.max(1, Math.floor(configuredTextMaxBytes))
119
+ : capture_js_1.DEFAULT_TEXT_MAX_BYTES,
112
120
  }));
113
121
  config = new config_js_1.ConfigPoller(token, ingestUrl, options.configPollMs, options.configHardTtlMs);
114
122
  }
package/dist/index.mjs CHANGED
@@ -10,11 +10,15 @@ const {
10
10
  modelFor,
11
11
  recordOutcome,
12
12
  route,
13
+ setDefaultTags,
13
14
  setSession,
14
15
  setTags,
15
16
  shutdown,
16
17
  trace,
17
18
  track,
19
+ withContext,
20
+ withSession,
21
+ withTags,
18
22
  vercelAISDKMiddleware,
19
23
  wrap,
20
24
  wrapClient,
@@ -31,11 +35,15 @@ export {
31
35
  modelFor,
32
36
  recordOutcome,
33
37
  route,
38
+ setDefaultTags,
34
39
  setSession,
35
40
  setTags,
36
41
  shutdown,
37
42
  trace,
38
43
  track,
44
+ withContext,
45
+ withSession,
46
+ withTags,
39
47
  vercelAISDKMiddleware,
40
48
  wrap,
41
49
  wrapClient,
@@ -5,18 +5,5 @@ export interface RepoConfig {
5
5
  repository: string;
6
6
  repoRoot: string;
7
7
  }
8
- /** Return 'owner/repo' from a GitHub SSH or HTTPS remote URL, or undefined
9
- * if the URL isn't a recognized GitHub origin. */
10
- export declare function normalizeGithubRemote(url: string): string | undefined;
11
- /** Walk upward from appRoot looking for .metergraph/config.json. Returns
12
- * undefined -- silently, the normal v1 state -- when nothing is found. */
8
+ /** Walk upward from appRoot looking for .metergraph/config.json. */
13
9
  export declare function discoverRepoConfig(appRoot: string): RepoConfig | undefined;
14
- /** Create .metergraph/config.json if -- and only if -- it doesn't already
15
- * exist. Uses O_CREAT|O_EXCL ("wx") for an atomic create-only-if-absent; a
16
- * concurrent writer (or a file that appeared between discovery and this
17
- * call) always wins over us, and we simply read back whatever is there. */
18
- export declare function writeConfigAtomically(repoRoot: string, repository: string): RepoConfig | undefined;
19
- /** Discover an existing repo config, or detect+write one once at the git top
20
- * level. Fail-open: any detection or write failure returns undefined
21
- * (app-token ingestion), never throws. */
22
- export declare function ensureRepoConfig(appRoot: string): RepoConfig | undefined;
@@ -1,44 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SUPPORTED_CONFIG_VERSION = exports.CONFIG_FILENAME = exports.CONFIG_DIRNAME = void 0;
4
- exports.normalizeGithubRemote = normalizeGithubRemote;
5
4
  exports.discoverRepoConfig = discoverRepoConfig;
6
- exports.writeConfigAtomically = writeConfigAtomically;
7
- exports.ensureRepoConfig = ensureRepoConfig;
8
- /**
9
- * SDK 0.4+ repository-aware ingestion: discover, detect, and write
10
- * .metergraph/config.json.
11
- *
12
- * Discovery is purely file-based (never shells out to git), so a committed
13
- * config is honored in production without needing a .git directory at all.
14
- * Detection + write only ever runs when discovery finds nothing: it shells
15
- * out to git to find the repo's top level and GitHub origin, then writes the
16
- * config there exactly once. An existing file is always authoritative and is
17
- * never overwritten. Every failure mode here is fail-open -- callers get
18
- * undefined and fall back to app-token ingestion, never a thrown error.
19
- */
5
+ /** Read-only discovery of repository identity configuration. */
20
6
  const node_fs_1 = require("node:fs");
21
7
  const node_path_1 = require("node:path");
22
8
  exports.CONFIG_DIRNAME = ".metergraph";
23
9
  exports.CONFIG_FILENAME = "config.json";
24
10
  exports.SUPPORTED_CONFIG_VERSION = 2;
25
11
  const MAX_WALK_UP = 64;
26
- const REMOTE_PATTERNS = [
27
- /^git@github\.com:([^/]+\/[^/]+?)(\.git)?\/?$/,
28
- /^https:\/\/github\.com\/([^/]+\/[^/]+?)(\.git)?\/?$/,
29
- /^ssh:\/\/git@github\.com\/([^/]+\/[^/]+?)(\.git)?\/?$/,
30
- ];
31
- /** Return 'owner/repo' from a GitHub SSH or HTTPS remote URL, or undefined
32
- * if the URL isn't a recognized GitHub origin. */
33
- function normalizeGithubRemote(url) {
34
- const trimmed = url.trim();
35
- for (const pattern of REMOTE_PATTERNS) {
36
- const match = pattern.exec(trimmed);
37
- if (match)
38
- return match[1];
39
- }
40
- return undefined;
41
- }
42
12
  function load(path, repoRoot) {
43
13
  let doc;
44
14
  try {
@@ -48,7 +18,10 @@ function load(path, repoRoot) {
48
18
  console.warn(`metergraph: found ${path} but could not read it: ${error instanceof Error ? error.message : String(error)}`);
49
19
  return undefined;
50
20
  }
51
- if (typeof doc !== "object" || doc === null || (doc.version ?? exports.SUPPORTED_CONFIG_VERSION) !== exports.SUPPORTED_CONFIG_VERSION) {
21
+ if (typeof doc !== "object"
22
+ || doc === null
23
+ || (doc.version ?? exports.SUPPORTED_CONFIG_VERSION)
24
+ !== exports.SUPPORTED_CONFIG_VERSION) {
52
25
  console.warn(`metergraph: ${path} has an unsupported schema version; ignoring (expected version ${exports.SUPPORTED_CONFIG_VERSION})`);
53
26
  return undefined;
54
27
  }
@@ -59,8 +32,7 @@ function load(path, repoRoot) {
59
32
  }
60
33
  return { repository, repoRoot };
61
34
  }
62
- /** Walk upward from appRoot looking for .metergraph/config.json. Returns
63
- * undefined -- silently, the normal v1 state -- when nothing is found. */
35
+ /** Walk upward from appRoot looking for .metergraph/config.json. */
64
36
  function discoverRepoConfig(appRoot) {
65
37
  let current;
66
38
  try {
@@ -76,7 +48,7 @@ function discoverRepoConfig(appRoot) {
76
48
  return load(candidate, current);
77
49
  }
78
50
  catch {
79
- // no config at this level; keep walking up
51
+ // No config at this level; keep walking upward.
80
52
  }
81
53
  const parent = (0, node_path_1.dirname)(current);
82
54
  if (parent === current)
@@ -85,137 +57,3 @@ function discoverRepoConfig(appRoot) {
85
57
  }
86
58
  return undefined;
87
59
  }
88
- function gitDirectory(repoRoot) {
89
- const marker = (0, node_path_1.join)(repoRoot, ".git");
90
- try {
91
- if ((0, node_fs_1.statSync)(marker).isDirectory())
92
- return marker;
93
- const match = /^gitdir:\s*(.+)$/m.exec((0, node_fs_1.readFileSync)(marker, "utf8"));
94
- const path = match?.[1];
95
- if (!path)
96
- return undefined;
97
- return (0, node_path_1.isAbsolute)(path) ? path : (0, node_path_1.resolve)(repoRoot, path);
98
- }
99
- catch {
100
- return undefined;
101
- }
102
- }
103
- function ownedByCurrentUser(path) {
104
- if (typeof process.getuid !== "function")
105
- return true;
106
- try {
107
- return (0, node_fs_1.statSync)(path).uid === process.getuid();
108
- }
109
- catch {
110
- return false;
111
- }
112
- }
113
- function gitTopLevel(appRoot) {
114
- try {
115
- let current = (0, node_fs_1.realpathSync)(appRoot);
116
- for (let i = 0; i < MAX_WALK_UP; i += 1) {
117
- const gitDir = gitDirectory(current);
118
- if (gitDir) {
119
- // Match Git's safe-directory default: never trust repository metadata
120
- // owned by another Unix user. Unsupported platforms retain v1's
121
- // existing fail-open behavior.
122
- return ownedByCurrentUser(current) && ownedByCurrentUser(gitDir)
123
- ? current
124
- : undefined;
125
- }
126
- const parent = (0, node_path_1.dirname)(current);
127
- if (parent === current)
128
- break;
129
- current = parent;
130
- }
131
- }
132
- catch {
133
- // Fall through to the normal v1 path.
134
- }
135
- return undefined;
136
- }
137
- function gitOriginUrl(repoRoot) {
138
- try {
139
- const gitDir = gitDirectory(repoRoot);
140
- if (!gitDir)
141
- return undefined;
142
- let commonDir = gitDir;
143
- try {
144
- const relative = (0, node_fs_1.readFileSync)((0, node_path_1.join)(gitDir, "commondir"), "utf8").trim();
145
- if (relative)
146
- commonDir = (0, node_path_1.resolve)(gitDir, relative);
147
- }
148
- catch {
149
- // Normal repositories keep config directly in .git.
150
- }
151
- const config = (0, node_fs_1.readFileSync)((0, node_path_1.join)(commonDir, "config"), "utf8");
152
- let inOrigin = false;
153
- for (const line of config.split(/\r?\n/)) {
154
- const section = /^\s*\[remote\s+"([^"]+)"\]\s*$/.exec(line);
155
- if (section) {
156
- inOrigin = section[1] === "origin";
157
- continue;
158
- }
159
- if (/^\s*\[/.test(line))
160
- inOrigin = false;
161
- if (inOrigin) {
162
- const url = /^\s*url\s*=\s*(.+?)\s*$/.exec(line);
163
- if (url)
164
- return url[1];
165
- }
166
- }
167
- }
168
- catch {
169
- // Missing or unreadable Git metadata is the normal production fallback.
170
- }
171
- return undefined;
172
- }
173
- /** Create .metergraph/config.json if -- and only if -- it doesn't already
174
- * exist. Uses O_CREAT|O_EXCL ("wx") for an atomic create-only-if-absent; a
175
- * concurrent writer (or a file that appeared between discovery and this
176
- * call) always wins over us, and we simply read back whatever is there. */
177
- function writeConfigAtomically(repoRoot, repository) {
178
- const configDir = (0, node_path_1.join)(repoRoot, exports.CONFIG_DIRNAME);
179
- const configPath = (0, node_path_1.join)(configDir, exports.CONFIG_FILENAME);
180
- const payload = `${JSON.stringify({ version: exports.SUPPORTED_CONFIG_VERSION, repository })}\n`;
181
- try {
182
- (0, node_fs_1.mkdirSync)(configDir, { recursive: true });
183
- const fd = (0, node_fs_1.openSync)(configPath, "wx", 0o644);
184
- try {
185
- (0, node_fs_1.writeSync)(fd, payload);
186
- }
187
- finally {
188
- (0, node_fs_1.closeSync)(fd);
189
- }
190
- }
191
- catch (error) {
192
- if (error.code !== "EEXIST") {
193
- console.warn(`metergraph: could not write ${configPath}: ${error instanceof Error ? error.message : String(error)}`);
194
- return undefined;
195
- }
196
- }
197
- return load(configPath, repoRoot);
198
- }
199
- /** Discover an existing repo config, or detect+write one once at the git top
200
- * level. Fail-open: any detection or write failure returns undefined
201
- * (app-token ingestion), never throws. */
202
- function ensureRepoConfig(appRoot) {
203
- const existing = discoverRepoConfig(appRoot);
204
- if (existing)
205
- return existing;
206
- try {
207
- const repoRoot = gitTopLevel(appRoot);
208
- if (!repoRoot)
209
- return undefined;
210
- const origin = gitOriginUrl(repoRoot);
211
- if (!origin)
212
- return undefined;
213
- const repository = normalizeGithubRemote(origin);
214
- if (!repository)
215
- return undefined;
216
- return writeConfigAtomically(repoRoot, repository);
217
- }
218
- catch {
219
- return undefined;
220
- }
221
- }
package/dist/transport.js CHANGED
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Transport = exports.MAX_BATCH_BYTES = void 0;
4
4
  const failure_log_js_1 = require("./failure-log.js");
5
- exports.MAX_BATCH_BYTES = 512 * 1024;
5
+ exports.MAX_BATCH_BYTES = 4 * 1024 * 1024;
6
6
  function detectedMode() {
7
7
  const env = typeof process === "undefined" ? {} : process.env;
8
8
  const agent = typeof navigator === "undefined" ? "" : navigator.userAgent;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.6.0";
1
+ export declare const SDK_VERSION = "0.6.3";
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.0";
4
+ exports.SDK_VERSION = "0.6.3";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "metergraph",
3
- "version": "0.6.0",
3
+ "version": "0.6.3",
4
4
  "description": "Fire-and-forget LLM spend capture for Metergraph",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",