margin-meter 0.2.0 → 0.3.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/dist/index.js CHANGED
@@ -22,18 +22,64 @@
22
22
  * client cannot spoof another project's economics.
23
23
  */
24
24
  import { extractUsage, StreamUsageAccumulator, } from "./providers.js";
25
+ import { BATCH_PATH, Batcher, SHUTDOWN_TIMEOUT_MS, } from "./batching.js";
26
+ // The Node analogue of Python's `contextvars`: it carries a value across the
27
+ // async/await chain of the callback it runs, so a call metered several awaits
28
+ // deep inside `stage(...)` still sees the enclosing step. `node:async_hooks` is
29
+ // a Node builtin (stable since 16; this package requires node>=18) and is
30
+ // present in Bun and the edge runtimes too. It is the ONE thing `stage`/`span`
31
+ // need that a browser bundle would not have — and those primitives are the whole
32
+ // reason to reach for it — so a caller instrumenting server-side agent code (the
33
+ // only place an LLM key belongs) always has it.
34
+ import { AsyncLocalStorage } from "node:async_hooks";
25
35
  export * from "./providers.js";
26
36
  export * from "./instrument.js";
37
+ export * from "./batching.js";
27
38
  // Namespaced, not flattened: `BEDROCK` means two different things here — the
28
39
  // provider that bills for the model and the path the request took — and merging
29
40
  // them into one barrel would collide the names and blur the distinction the
30
41
  // substrate dimension exists to draw. `substrate.BEDROCK` reads as the path.
31
42
  export * as substrate from "./substrate.js";
43
+ // Namespaced: an eval adapter reuses common verb names (`recordResults`,
44
+ // `outcomeInput`), so `promptfoo.recordResults(...)` keeps the framework it
45
+ // bridges legible at the call site — the Python SDK's `margin_meter.promptfoo`
46
+ // twin (`docs/INTEGRATION_LADDER.md` rung 2).
47
+ export * as promptfoo from "./promptfoo.js";
48
+ // The second eval adapter (rung 2), same namespaced shape — `braintrust.recordResults(...)`.
49
+ export * as braintrust from "./braintrust.js";
50
+ // The third eval adapter (rung 2), same namespaced shape — `langsmith.recordResults(...)`.
51
+ export * as langsmith from "./langsmith.js";
52
+ // The test-runner adapter (rung 2/6): one vitest/jest JSON file, every test an
53
+ // outcome — `vitest.recordResults(...)`. The pytest plugin's TS twin.
54
+ export * as vitest from "./vitest.js";
32
55
  export const CALLS_PATH = "/api/ingest/calls";
33
56
  export const OUTCOMES_PATH = "/api/ingest/outcomes";
34
57
  export const KEY_HEADER = "X-Margin-Key";
35
- export const DEFAULT_INGEST_URL = "http://127.0.0.1:8000";
58
+ // ⛔ No default ingest URL, on purpose. It used to be `http://127.0.0.1:8000`, so a
59
+ // meter given a key and no URL POSTed to the caller's own laptop and dropped every row
60
+ // (a real authorized run on 2026-09-15 spent money and landed nothing that way). An
61
+ // unset URL is refused as `no_url` at once, like `no_key`, never guessed.
36
62
  export const DEFAULT_TIMEOUT_MS = 10_000;
63
+ /** One batched request's byte ceiling, and the retry policy behind it. Full
64
+ * reasoning in `docs/reference/SDK_BATCHING.md`; the short version:
65
+ *
66
+ * - 1 MB is ~7x headroom over a worst-case 1500-byte row at the default 100
67
+ * records, and far under any gateway limit. Vercel accepts 100 MB bodies;
68
+ * that is a ceiling, not a target.
69
+ * - 3 attempts with FULL jitter rather than plain exponential, because every
70
+ * buffered client backs off on the same schedule and un-jittered retries
71
+ * re-synchronise into a herd aimed at the endpoint that just failed.
72
+ * - Duplicates from an at-least-once retry are free: every record carries an
73
+ * `event_id` and the server is idempotent on `(source, event_id)`.
74
+ */
75
+ export const MAX_BATCH_BYTES = 1_000_000;
76
+ export const RETRY_ATTEMPTS = 3;
77
+ export const RETRY_BASE_MS = 1_000;
78
+ export const RETRY_CAP_MS = 30_000;
79
+ /** Statuses worth resending. Everything else (401, 422, 400) fails identically
80
+ * next time, so retrying is a hot loop that never drains — and against a bad key
81
+ * it would hammer us forever. */
82
+ const RETRYABLE_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);
37
83
  /** A fresh idempotency key per emit. Uses the platform crypto UUID (Node 16.7+,
38
84
  * modern browsers); falls back to a random-hex id where crypto is absent, which
39
85
  * is still unique enough to key a single call's dedup. */
@@ -45,6 +91,88 @@ function newEventId() {
45
91
  Math.random().toString(16).slice(2) +
46
92
  Math.random().toString(16).slice(2));
47
93
  }
94
+ // --------------------------------------------------------------------------- //
95
+ // The chain — `stage()` and `span()` (MAR-899, the TS twin of the Python SDK).
96
+ // --------------------------------------------------------------------------- //
97
+ // The wire fields (`spanId` / `parentSpanId` / `taskClass`) have always been on
98
+ // `RecordCallInput`, but a TS user had to thread the ids through their own code by
99
+ // hand — so `margin_stage_plan`, the per-step model/effort advice, worked out of
100
+ // the box for a Python customer and needed manual plumbing for a TS one. That is a
101
+ // real asymmetry on the integration path we describe to design partners as two
102
+ // plugs. These two blocks close it: wrap a step and every call it makes, however
103
+ // many awaits deep, records under one node with the right label — no ids by hand.
104
+ //
105
+ // Honesty, identical to the Python side: `stage`/`span` RE-LABEL and LINK only.
106
+ // Tokens, cost and the outcome are never touched, so a call inside one prices
107
+ // byte-for-byte the same as one before this existed.
108
+ /** A 32-hex span id, the shape of Python's `uuid4().hex` (no dashes). Uses the
109
+ * platform crypto UUID where present, a random-hex id otherwise — either is
110
+ * unique enough to key one run's tree. */
111
+ function newSpanId() {
112
+ const c = globalThis.crypto;
113
+ if (c?.randomUUID)
114
+ return c.randomUUID().replace(/-/g, "");
115
+ return (Math.random().toString(16).slice(2) +
116
+ Math.random().toString(16).slice(2) +
117
+ Date.now().toString(16))
118
+ .replace(/[^0-9a-f]/g, "")
119
+ .slice(0, 32)
120
+ .padEnd(32, "0");
121
+ }
122
+ const _spanStore = new AsyncLocalStorage();
123
+ const _stageStore = new AsyncLocalStorage();
124
+ export function stage(operation, optsOrFn, maybeFn) {
125
+ const opts = typeof optsOrFn === "function" ? {} : optsOrFn;
126
+ const fn = (typeof optsOrFn === "function" ? optsOrFn : maybeFn);
127
+ const parent = _spanStore.getStore();
128
+ const ctx = {
129
+ spanId: newSpanId(),
130
+ parentSpanId: opts.parentSpanId ?? parent?.spanId,
131
+ };
132
+ const override = {
133
+ operation,
134
+ sessionId: opts.sessionId,
135
+ taskClass: opts.taskClass,
136
+ };
137
+ return _stageStore.run(override, () => _spanStore.run(ctx, () => fn(ctx.spanId)));
138
+ }
139
+ /** The active `(operation, sessionId, taskClass)` step override, or `undefined`
140
+ * outside any `stage`. */
141
+ export function currentStage() {
142
+ return _stageStore.getStore();
143
+ }
144
+ /** Mark every metered call inside `fn` as one node of an agent tree — the tree the
145
+ * Money Map decomposes to ask what a BRANCH cost, which a flat list of calls
146
+ * sharing a `sessionId` cannot answer. Nesting is what builds the tree; returns
147
+ * whatever `fn` returns.
148
+ *
149
+ * ```ts
150
+ * await span({ pattern: "panel", branchWidth: 3, stoppingRule: "majority of 3" }, () =>
151
+ * Promise.all(candidates.map((c) => judge(c))), // each judge nests its own node
152
+ * );
153
+ * ```
154
+ *
155
+ * `stage()` is the primitive to reach for on a plain pipeline step; `span()` adds
156
+ * the orchestration shape when a block fans out. This is the TS twin of
157
+ * `margin_meter.span`. */
158
+ export function span(opts, fn) {
159
+ const parent = _spanStore.getStore();
160
+ const ctx = {
161
+ spanId: opts.spanId ?? newSpanId(),
162
+ parentSpanId: opts.parentSpanId ?? parent?.spanId,
163
+ pattern: opts.pattern,
164
+ branchWidth: opts.branchWidth,
165
+ stoppingRule: opts.stoppingRule,
166
+ };
167
+ return _spanStore.run(ctx, () => fn(ctx.spanId));
168
+ }
169
+ /** The active `(spanId, parentSpanId)`, or `undefined` outside any span/stage. */
170
+ export function currentSpan() {
171
+ const ctx = _spanStore.getStore();
172
+ return ctx === undefined
173
+ ? undefined
174
+ : { spanId: ctx.spanId, parentSpanId: ctx.parentSpanId };
175
+ }
48
176
  /** Raised (only in strict mode) when a row is rejected by the ingest API. */
49
177
  export class MarginIngestError extends Error {
50
178
  statusCode;
@@ -86,47 +214,406 @@ export class MarginMeter {
86
214
  apiKey;
87
215
  raiseOnError;
88
216
  transport;
217
+ attempted = 0;
218
+ delivered = 0;
219
+ droppedByReason = {};
220
+ attemptedByPath = {};
221
+ droppedByPath = {};
222
+ warnedOnDrop = false;
223
+ noUrl;
224
+ batcher;
225
+ exitFlush;
226
+ exitFlushArmed = false;
89
227
  constructor(options = {}) {
90
228
  const env = (typeof process !== "undefined" && process.env) || {};
91
- this.ingestUrl = options.ingestUrl || env.MARGIN_INGEST_URL || DEFAULT_INGEST_URL;
229
+ this.ingestUrl = options.ingestUrl || env.MARGIN_INGEST_URL || "";
230
+ // An injected transport already knows where it posts; only our own fetch needs a URL.
231
+ this.noUrl = !this.ingestUrl && !options.transport;
92
232
  this.apiKey = options.apiKey || env.MARGIN_INGEST_KEY;
93
233
  this.raiseOnError = options.raiseOnError ?? false;
94
234
  this.transport =
95
235
  options.transport ||
96
236
  new FetchTransport(this.ingestUrl, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
237
+ this.batcher = new Batcher((batch) => this.sendBatch(batch));
238
+ // ⭐ The shutdown flush. `beforeExit`, deliberately NOT a signal handler:
239
+ // installing SIGTERM/SIGINT from a library steals signal handling from a host
240
+ // that usually has its own graceful shutdown. It fires when the event loop
241
+ // empties — which the batcher's `unref`'d timer is careful not to prevent —
242
+ // and it is async-capable, unlike `exit`.
243
+ //
244
+ // ⛔ FLUSH, not close, and the difference is not cosmetic. `beforeExit` fires
245
+ // whenever the loop drains, which in a long-lived host happens between bursts
246
+ // of work rather than only at the end — closing there would wedge the meter
247
+ // for the rest of the process's life, and every later call would be dropped.
248
+ // Caught exactly that way: a test run went quiet for a tick and two subsequent
249
+ // rows were refused by a batcher that had "shut down" mid-suite. Flushing is
250
+ // idempotent and safe to fire any number of times; closing is an explicit,
251
+ // one-way act the host asks for with `await meter.close()`.
252
+ //
253
+ // ⚠️ A hard kill loses the buffer, bounded by the flush interval. Said plainly
254
+ // rather than glossed: no in-memory buffer survives SIGKILL, and pretending
255
+ // otherwise would be a fabricated guarantee.
256
+ //
257
+ // ⭐ BOUNDED, and registered LAZILY on the first buffered row (see `enqueue`).
258
+ // Registering in the constructor put one listener per meter on `process` for
259
+ // the process's lifetime, each pinning its meter and up to `maxQueue` records
260
+ // — Node warns at eleven, and the meter that never emits pays for a handler it
261
+ // will never need. `close()` removes it again.
262
+ this.exitFlush = () => {
263
+ void Promise.race([this.batcher.flush(), sleep(SHUTDOWN_TIMEOUT_MS)]);
264
+ };
265
+ }
266
+ /** Attach the process-exit flush, once, on the first row that will need it. */
267
+ armExitFlush() {
268
+ if (this.exitFlushArmed)
269
+ return;
270
+ if (typeof process === "undefined" || typeof process.on !== "function")
271
+ return;
272
+ this.exitFlushArmed = true;
273
+ process.on("beforeExit", this.exitFlush);
274
+ }
275
+ /** Record one emit attempt. Called at every exit point that knows its own
276
+ * outcome, BEFORE any `raiseOnError` throw, so a strict-mode failure is
277
+ * counted exactly like the fail-safe one it would otherwise have been. */
278
+ count(path, ok, reason) {
279
+ this.attempted += 1;
280
+ this.attemptedByPath[path] = (this.attemptedByPath[path] ?? 0) + 1;
281
+ if (ok) {
282
+ this.delivered += 1;
283
+ return;
284
+ }
285
+ const bucket = reason ?? "unknown";
286
+ this.droppedByReason[bucket] = (this.droppedByReason[bucket] ?? 0) + 1;
287
+ this.droppedByPath[path] = (this.droppedByPath[path] ?? 0) + 1;
288
+ if (!this.warnedOnDrop) {
289
+ this.warnedOnDrop = true;
290
+ // Once per meter, on the FIRST drop only, so a silent drop stops being
291
+ // silent without letting a flapping network flood the host's own logs.
292
+ // The RATE lives in deliveryStats(); this line exists to send someone there.
293
+ console.warn(`margin-meter: an emit was dropped (${bucket}) — this row is NOT in the ` +
294
+ `ledger. Metering is fail-safe, so the host call was unaffected. ` +
295
+ `Call meter.deliveryStats() for the running count.`);
296
+ }
97
297
  }
298
+ /** A snapshot of what this meter delivered against what it tried to.
299
+ * See {@link DeliveryStats}. */
300
+ deliveryStats() {
301
+ const dropped = this.attempted - this.delivered;
302
+ return {
303
+ attempted: this.attempted,
304
+ delivered: this.delivered,
305
+ dropped,
306
+ dropRate: this.attempted ? dropped / this.attempted : 0,
307
+ droppedByReason: { ...this.droppedByReason },
308
+ attemptedByPath: { ...this.attemptedByPath },
309
+ droppedByPath: { ...this.droppedByPath },
310
+ };
311
+ }
312
+ /**
313
+ * Route one built payload to the wire or the buffer.
314
+ *
315
+ * Buffering is the default and the whole point (`docs/reference/SDK_BATCHING.md`).
316
+ * Two cases deliberately stay immediate, and neither is a knob:
317
+ *
318
+ * - **Strict mode** (`raiseOnError`) means "throw at MY call site when this row
319
+ * is rejected", and a buffered emit has no call site left to throw at by the
320
+ * time the POST happens. The two are incompatible, so strict posts now.
321
+ * - **No key**, because buffering rows that can never be sent would fill the
322
+ * queue and then report `queue_full` — a diagnosis that sends the reader
323
+ * hunting for a network problem when the answer is a missing variable.
324
+ * A missing URL is the same case and is named `no_url`.
325
+ */
98
326
  async emit(path, payload) {
99
327
  if (!this.apiKey) {
100
328
  const error = "no ingest key (set MARGIN_INGEST_KEY or pass apiKey)";
329
+ this.count(path, false, "no_key");
101
330
  if (this.raiseOnError)
102
331
  throw new MarginConfigError(error);
103
- return { ok: false, statusCode: 0, error };
332
+ return { ok: false, statusCode: 0, error, reason: "no_key" };
333
+ }
334
+ if (this.noUrl) {
335
+ const error = "no ingest URL (set MARGIN_INGEST_URL=https://trymargin.io or pass ingestUrl)";
336
+ this.count(path, false, "no_url");
337
+ if (this.raiseOnError)
338
+ throw new MarginConfigError(error);
339
+ return { ok: false, statusCode: 0, error, reason: "no_url" };
340
+ }
341
+ if (!this.raiseOnError)
342
+ return this.enqueue(path, payload);
343
+ return await this.postNow(path, payload);
344
+ }
345
+ /** Hand one record to the buffer. Never blocks, never throws.
346
+ *
347
+ * `ok: true` here means ACCEPTED INTO THE BUFFER, not written to the ledger —
348
+ * the body says `queued` so nothing mistakes the two. What actually landed is
349
+ * `deliveryStats()`, which exists for exactly this question. */
350
+ enqueue(path, payload) {
351
+ if (this.batcher.submit({ path, payload })) {
352
+ this.armExitFlush();
353
+ return { ok: true, statusCode: 0, body: { queued: true } };
354
+ }
355
+ // Refused. Either our endpoint is unreachable and the buffer filled, or the
356
+ // meter was explicitly closed and is still being written to — opposite fixes,
357
+ // so they are counted apart rather than under one bucket. Dropping is correct
358
+ // in both cases (an unbounded buffer would OOM the customer's agent) but it is
359
+ // COUNTED, because a meter that silently stops metering is the one failure
360
+ // this product cannot have.
361
+ const reason = this.batcher.closed ? "meter_closed" : "queue_full";
362
+ const error = this.batcher.closed
363
+ ? "meter is closed — this row is NOT in the ledger"
364
+ : `meter buffer full (${this.batcher.maxQueue} records) — this row is NOT in the ledger`;
365
+ this.count(path, false, reason);
366
+ return { ok: false, statusCode: 0, error, reason };
367
+ }
368
+ /** Resolve once every buffered row has been delivered or counted as dropped.
369
+ *
370
+ * Call it before reading `deliveryStats()` if you need the counts to cover rows
371
+ * you have only just emitted — buffering separates an emit from its delivery
372
+ * in time by design. */
373
+ async flush() {
374
+ await this.batcher.flush();
375
+ }
376
+ /** Drain the buffer and stop the timer. Registered on `beforeExit`.
377
+ *
378
+ * Anything the timeout strands is COUNTED as dropped rather than abandoned: the
379
+ * records are handed back by `Batcher.close` precisely so the number is
380
+ * knowable. */
381
+ async close(timeoutMs = SHUTDOWN_TIMEOUT_MS) {
382
+ // Detached first so a meter the host closed explicitly does not also hold a
383
+ // process-exit listener (and a reference to itself) alive for the rest of the
384
+ // process.
385
+ if (this.exitFlushArmed && typeof process !== "undefined") {
386
+ process.off("beforeExit", this.exitFlush);
387
+ this.exitFlushArmed = false;
388
+ }
389
+ for (const record of await this.batcher.close(timeoutMs)) {
390
+ this.count(record.path, false, "shutdown_timeout");
104
391
  }
392
+ }
393
+ async postNow(path, payload) {
105
394
  let resp;
106
395
  try {
107
396
  resp = await this.transport.post(path, {
108
397
  json: payload,
109
- headers: { [KEY_HEADER]: this.apiKey },
398
+ headers: { [KEY_HEADER]: this.apiKey ?? "" },
110
399
  });
111
400
  }
112
401
  catch (e) {
113
402
  const error = `transport error: ${e.message}`;
403
+ this.count(path, false, "transport");
114
404
  if (this.raiseOnError)
115
405
  throw new MarginIngestError(0, e.message);
116
- return { ok: false, statusCode: 0, error };
406
+ return { ok: false, statusCode: 0, error, reason: "transport" };
117
407
  }
118
408
  if (resp.status === 200) {
119
409
  const body = (await resp.json());
410
+ this.count(path, true);
120
411
  return { ok: true, statusCode: 200, body };
121
412
  }
413
+ const reason = `http_${resp.status}`;
414
+ this.count(path, false, reason);
122
415
  const detail = await extractDetail(resp);
123
416
  if (this.raiseOnError)
124
417
  throw new MarginIngestError(resp.status, detail);
125
- return { ok: false, statusCode: resp.status, error: detail };
418
+ return { ok: false, statusCode: resp.status, error: detail, reason };
419
+ }
420
+ // --------------------------------------------------------------------- //
421
+ // Delivery — what happens off the caller's path
422
+ // --------------------------------------------------------------------- //
423
+ /** POST one buffered batch. Never rejects: it owns its own accounting.
424
+ *
425
+ * ⛔ The blanket `catch` is load-bearing, not defensive habit. `Batcher.flush`
426
+ * swallows a rejection to keep the drain going, so anything escaping here would
427
+ * vanish with the counters reading a clean sheet — an uncounted loss, which
428
+ * makes measured spend read CHEAPER than the bill. Scoped per chunk so records
429
+ * already accounted for in an earlier chunk are not counted twice. */
430
+ async sendBatch(records) {
431
+ for (const chunk of this.chunkByBytes(records)) {
432
+ try {
433
+ await this.deliverChunk(chunk);
434
+ }
435
+ catch (e) {
436
+ console.warn(`margin-meter: batch send failed unexpectedly: ${e.message}`);
437
+ for (const record of chunk)
438
+ this.count(record.path, false, "send_error");
439
+ }
440
+ }
441
+ }
442
+ /** Split a batch so no request exceeds {@link MAX_BATCH_BYTES}.
443
+ *
444
+ * ⛔ A single record over the cap on its own is DROPPED and counted as
445
+ * `oversize`. No split can send it, and keeping it would wedge the queue behind
446
+ * one poisoned row forever. It is a bug in the caller — every open-vocabulary
447
+ * field is already bounded server-side, so an honest row cannot come near a
448
+ * megabyte.
449
+ *
450
+ * ⛔ A payload that will not serialise is dropped and counted too, and that case
451
+ * is not exotic — a `BigInt` anywhere in the payload makes `JSON.stringify`
452
+ * throw. Unguarded, the throw escaped into the flush and the row vanished with
453
+ * the counters reading a clean sheet. */
454
+ chunkByBytes(records) {
455
+ const chunks = [];
456
+ let current = [];
457
+ let size = 0;
458
+ for (const record of records) {
459
+ let weight;
460
+ try {
461
+ weight = JSON.stringify(record.payload).length + 2;
462
+ }
463
+ catch {
464
+ this.count(record.path, false, "unserializable");
465
+ continue;
466
+ }
467
+ if (weight > MAX_BATCH_BYTES) {
468
+ this.count(record.path, false, "oversize");
469
+ continue;
470
+ }
471
+ if (current.length > 0 && size + weight > MAX_BATCH_BYTES) {
472
+ chunks.push(current);
473
+ current = [];
474
+ size = 0;
475
+ }
476
+ current.push(record);
477
+ size += weight;
478
+ }
479
+ if (current.length > 0)
480
+ chunks.push(current);
481
+ return chunks;
482
+ }
483
+ async deliverChunk(records) {
484
+ const calls = records.filter((r) => r.path === CALLS_PATH);
485
+ const outcomes = records.filter((r) => r.path === OUTCOMES_PATH);
486
+ const body = {};
487
+ if (calls.length > 0)
488
+ body.calls = calls.map((r) => r.payload);
489
+ if (outcomes.length > 0)
490
+ body.outcomes = outcomes.map((r) => r.payload);
491
+ if (calls.length === 0 && outcomes.length === 0)
492
+ return;
493
+ const { parsed, reason } = await this.postBatchWithRetry(body);
494
+ if (!parsed) {
495
+ // The request never succeeded. Every record in it is a loss, counted under
496
+ // the reason that caused it — and NOT re-queued: an unbounded retry queue is
497
+ // the OOM this design bounds, arriving by another door.
498
+ for (const record of records)
499
+ this.count(record.path, false, reason);
500
+ return;
501
+ }
502
+ for (const [key, group] of [
503
+ ["calls", calls],
504
+ ["outcomes", outcomes],
505
+ ]) {
506
+ const raw = parsed[key];
507
+ const results = Array.isArray(raw) ? raw : [];
508
+ group.forEach((record, index) => {
509
+ const outcome = results[index];
510
+ // ⚠️ Positional alignment is the contract, so a short or missing results
511
+ // array means we cannot say what happened to this row. Counted as a drop
512
+ // under its own reason rather than assumed delivered — assuming success is
513
+ // how an invisible loss starts.
514
+ if (!outcome || typeof outcome !== "object") {
515
+ this.count(record.path, false, "missing_result");
516
+ }
517
+ else if (outcome.ok) {
518
+ this.count(record.path, true);
519
+ }
520
+ else {
521
+ // ⭐ Split by the server's own `retryable` flag. A validation failure is
522
+ // the caller's bug (fix the payload) and a rate-cap refusal is our
523
+ // ceiling (the project is over its daily rows) — opposite fixes, and a
524
+ // reader who cannot tell them apart looks in the wrong place.
525
+ //
526
+ // ⛔ Neither is re-queued, including the retryable one: the cap is a
527
+ // 24-HOUR rolling window, so the server's honest `retry_after_seconds`
528
+ // can be hours. Holding the queue that long would stall every later row
529
+ // behind a wait the buffer cannot survive. The drop is made VISIBLE
530
+ // instead — `rate_limited` in deliveryStats() tells a customer their cap
531
+ // is the reason, and nothing else could.
532
+ this.count(record.path, false, outcome.retryable ? "rate_limited" : "rejected");
533
+ }
534
+ });
535
+ }
536
+ }
537
+ /** POST one batch, retrying the failures that clear with time. */
538
+ async postBatchWithRetry(body) {
539
+ let reason = "transport";
540
+ for (let attempt = 0; attempt < RETRY_ATTEMPTS; attempt += 1) {
541
+ let retryAfterMs;
542
+ try {
543
+ const resp = await this.transport.post(BATCH_PATH, {
544
+ json: body,
545
+ headers: { [KEY_HEADER]: this.apiKey ?? "" },
546
+ });
547
+ if (resp.status === 200) {
548
+ try {
549
+ return { parsed: (await resp.json()), reason: "" };
550
+ }
551
+ catch {
552
+ // A 200 whose body we cannot read tells us nothing about which rows
553
+ // landed. Retrying is safe (event_id dedup) and beats guessing.
554
+ reason = "unparseable_response";
555
+ }
556
+ }
557
+ else if (RETRYABLE_STATUS.has(resp.status)) {
558
+ reason = `http_${resp.status}`;
559
+ retryAfterMs = retryAfterMs_(resp);
560
+ }
561
+ else {
562
+ // 401/422/400: identical next time. Stop rather than loop.
563
+ return { reason: `http_${resp.status}` };
564
+ }
565
+ }
566
+ catch {
567
+ reason = "transport";
568
+ }
569
+ if (attempt + 1 >= RETRY_ATTEMPTS)
570
+ break;
571
+ await sleep(backoffMs(attempt, retryAfterMs));
572
+ }
573
+ return { reason };
126
574
  }
127
575
  /** Emit one measured LLM call. Cost is computed server-side when `costUsd`
128
576
  * is omitted. Never throws unless `raiseOnError`. */
129
577
  async recordCall(input) {
578
+ // Resolve the ambient step/tree BEFORE the payload, with the Python SDK's
579
+ // exact precedence — the two rules differ on purpose:
580
+ // • a `stage`'s operation/sessionId OVERRIDE what the call passed (that is
581
+ // how one run decomposes into named per-stage operations), while
582
+ // • its taskClass and every span field FILL only what the call left unset
583
+ // (an explicit `parentSpanId` is usually a branch reattached across a
584
+ // worker boundary — the ambient span must not overwrite it).
585
+ // Labels and links only: no cost/token/outcome field is touched here.
586
+ const stageOv = _stageStore.getStore();
587
+ const spanCtx = _spanStore.getStore();
588
+ let operation = input.operation;
589
+ let sessionId = input.sessionId;
590
+ let taskClass = input.taskClass;
591
+ if (stageOv !== undefined) {
592
+ if (stageOv.operation !== undefined)
593
+ operation = stageOv.operation;
594
+ if (stageOv.sessionId !== undefined)
595
+ sessionId = stageOv.sessionId;
596
+ if (stageOv.taskClass !== undefined && taskClass === undefined) {
597
+ taskClass = stageOv.taskClass;
598
+ }
599
+ }
600
+ let spanId = input.spanId;
601
+ let parentSpanId = input.parentSpanId;
602
+ let orchestrationPattern = input.orchestrationPattern;
603
+ let branchWidth = input.branchWidth;
604
+ let stoppingRule = input.stoppingRule;
605
+ if (spanCtx !== undefined) {
606
+ if (spanId === undefined)
607
+ spanId = spanCtx.spanId;
608
+ if (parentSpanId === undefined)
609
+ parentSpanId = spanCtx.parentSpanId;
610
+ if (orchestrationPattern === undefined)
611
+ orchestrationPattern = spanCtx.pattern;
612
+ if (branchWidth === undefined)
613
+ branchWidth = spanCtx.branchWidth;
614
+ if (stoppingRule === undefined)
615
+ stoppingRule = spanCtx.stoppingRule;
616
+ }
130
617
  const payload = {
131
618
  workflow_id: input.workflowId,
132
619
  provider: input.provider,
@@ -135,18 +622,30 @@ export class MarginMeter {
135
622
  output_tokens: input.outputTokens ?? 0,
136
623
  cache_read_tokens: input.cacheReadTokens ?? 0,
137
624
  cache_creation_tokens: input.cacheCreationTokens ?? 0,
138
- latency_ms: input.latencyMs ?? 0,
625
+ // ⛔ `?? null`, NOT `?? 0` (MAR-982). A caller who did not time the call must not
626
+ // have a zero invented for them — the server stores null as NULL, and nothing
627
+ // downstream can tell a substituted 0 from a real one.
628
+ latency_ms: input.latencyMs ?? null,
139
629
  status: input.status ?? "ok",
140
630
  is_retry: input.isRetry ?? false,
141
631
  is_simulated: input.isSimulated ?? false,
142
632
  event_id: input.eventId ?? newEventId(),
143
633
  };
144
- if (input.sessionId !== undefined)
145
- payload.session_id = input.sessionId;
634
+ if (sessionId !== undefined)
635
+ payload.session_id = sessionId;
146
636
  if (input.promptId !== undefined)
147
637
  payload.prompt_id = input.promptId;
148
- if (input.operation !== undefined)
149
- payload.operation = input.operation;
638
+ if (operation !== undefined)
639
+ payload.operation = operation;
640
+ // ⛔ CLAMPED to the server's column widths, matching the Python SDK and the in-repo meter.
641
+ // `ingest._require_str` RAISES rather than truncating, so an over-long label is a 422 for the
642
+ // whole row — and this client defaults to `raiseOnError=false`, so a caller setting e.g.
643
+ // environment="production-us-east-1-blue-green" (37 chars) would silently drop 100% of that
644
+ // service's metered spend. Truncating mislabels a row; raising loses it.
645
+ if (input.environment !== undefined)
646
+ payload.environment = input.environment.slice(0, 32);
647
+ if (input.team !== undefined)
648
+ payload.team = input.team.slice(0, 64);
150
649
  if (input.costUsd !== undefined)
151
650
  payload.cost_usd = input.costUsd;
152
651
  // Only send a non-default tier: a synchronous call omits it (the server
@@ -171,20 +670,35 @@ export class MarginMeter {
171
670
  // The agent-tree fields ride only when a call belongs to one, so a
172
671
  // single-agent call's wire is unchanged and an older server that predates them
173
672
  // is unaffected. They carry structure, never money — no cost branch reads them.
174
- if (input.spanId !== undefined)
175
- payload.span_id = input.spanId;
176
- if (input.parentSpanId !== undefined)
177
- payload.parent_span_id = input.parentSpanId;
178
- if (input.orchestrationPattern !== undefined) {
179
- payload.orchestration_pattern = input.orchestrationPattern;
673
+ if (spanId !== undefined)
674
+ payload.span_id = spanId;
675
+ if (parentSpanId !== undefined)
676
+ payload.parent_span_id = parentSpanId;
677
+ if (orchestrationPattern !== undefined) {
678
+ payload.orchestration_pattern = orchestrationPattern;
180
679
  }
181
- if (input.branchWidth !== undefined)
182
- payload.branch_width = input.branchWidth;
183
- if (input.stoppingRule !== undefined)
184
- payload.stopping_rule = input.stoppingRule;
680
+ if (branchWidth !== undefined)
681
+ payload.branch_width = branchWidth;
682
+ if (stoppingRule !== undefined)
683
+ payload.stopping_rule = stoppingRule;
185
684
  // The delivery path, sent only when it was actually determined.
186
685
  if (input.substrate !== undefined)
187
686
  payload.substrate = input.substrate;
687
+ // The unit of work this call served, sent only when the caller named it.
688
+ if (input.taskKey !== undefined)
689
+ payload.task_key = input.taskKey;
690
+ if (taskClass !== undefined)
691
+ payload.task_class = taskClass;
692
+ // WHICH AGENT SCAFFOLD drove the call (MAR-371). Clamped to the server's
693
+ // String(64) so an over-long harness costs the tail of the label, never the row
694
+ // (ingest._require_str raises on over-long, which would 422 the whole call).
695
+ if (input.harness !== undefined)
696
+ payload.harness = input.harness.slice(0, 64);
697
+ // WHY the generation ended, straight off the provider — a signal, never a
698
+ // billing verdict (MAR-209). Rides only when the provider reported one; absent
699
+ // it reads UNKNOWN server-side rather than a fabricated value. Never priced.
700
+ if (input.finishReason !== undefined)
701
+ payload.finish_reason = input.finishReason;
188
702
  return await this.emit(CALLS_PATH, payload);
189
703
  }
190
704
  /** Emit one outcome (a unit of productivity). `qualityMethod` records HOW the
@@ -200,8 +714,18 @@ export class MarginMeter {
200
714
  payload.quality_score = input.qualityScore;
201
715
  if (input.qualityMethod !== undefined)
202
716
  payload.quality_method = input.qualityMethod;
717
+ if (input.graderKind !== undefined)
718
+ payload.grader_kind = input.graderKind;
719
+ if (input.judgeModelId !== undefined)
720
+ payload.judge_model_id = input.judgeModelId;
721
+ if (input.graderConfidence !== undefined)
722
+ payload.grader_confidence = input.graderConfidence;
203
723
  if (input.link !== undefined)
204
724
  payload.link = input.link;
725
+ // Rides only when a value was actually supplied — absent is the first-class
726
+ // normal case (cost-per-outcome), never a defaulted 0 the customer did not send.
727
+ if (input.valueUsd !== undefined)
728
+ payload.value_usd = input.valueUsd;
205
729
  return await this.emit(OUTCOMES_PATH, payload);
206
730
  }
207
731
  /**
@@ -263,6 +787,7 @@ export class MarginMeter {
263
787
  cacheCreationTokens: usage.cacheCreationTokens,
264
788
  cacheCreation1hTokens: usage.cacheCreation1hTokens,
265
789
  reasoningTokens: usage.reasoningTokens,
790
+ costUsd: usage.billedCostUsd,
266
791
  latencyMs: input.latencyMs,
267
792
  status: input.status ?? "ok",
268
793
  isRetry: input.isRetry,
@@ -271,6 +796,10 @@ export class MarginMeter {
271
796
  operation: input.operation,
272
797
  isSimulated: input.isSimulated,
273
798
  substrate: input.substrate,
799
+ taskKey: input.taskKey,
800
+ // The provider's stop/finish reason, read verbatim off the response and
801
+ // forwarded as finish_reason (MAR-209). A signal, never a billing verdict.
802
+ finishReason: usage.stopReason,
274
803
  });
275
804
  }
276
805
  /**
@@ -300,6 +829,17 @@ export class MarginMeter {
300
829
  /* a resolver hiccup never breaks the wrapped call */
301
830
  }
302
831
  }
832
+ // The unit of work, resolved off the host's ambient context per call — never a
833
+ // constant, which would collapse a run into one task class.
834
+ let callTaskKey;
835
+ if (opts.resolveTaskKey) {
836
+ try {
837
+ callTaskKey = opts.resolveTaskKey();
838
+ }
839
+ catch {
840
+ /* a resolver hiccup reads as UNKNOWN, never breaks the wrapped call */
841
+ }
842
+ }
303
843
  // Ask OpenAI to include usage on a streamed call so the final chunk carries
304
844
  // the count the accumulator needs (only when this is an OpenAI chat patch).
305
845
  maybeInjectIncludeUsage(args, opts);
@@ -322,6 +862,7 @@ export class MarginMeter {
322
862
  operation: opts.operation,
323
863
  isSimulated: opts.isSimulated,
324
864
  substrate: opts.substrate,
865
+ taskKey: callTaskKey,
325
866
  });
326
867
  }
327
868
  catch {
@@ -333,7 +874,16 @@ export class MarginMeter {
333
874
  // response. Reading it here would throw and drop the call; instead hand back
334
875
  // a transparent proxy that meters ONCE as the host consumes the stream.
335
876
  if (isAsyncIterable(response)) {
336
- return meteredStream(response, meter, opts, callModel, start);
877
+ return meteredStream(response, meter, opts, callModel, callTaskKey, start);
878
+ }
879
+ // Bedrock's streaming commands resolve to a plain object whose event stream rides
880
+ // under `.stream` (ConverseStream) or `.body` (InvokeModelWithResponseStream), with
881
+ // the usage in its final event. Swap that field for the metered proxy (MAR-1518).
882
+ const nestedKey = opts.provider === "bedrock" ? bedrockStreamKey(response) : undefined;
883
+ if (nestedKey !== undefined) {
884
+ const r = response;
885
+ r[nestedKey] = meteredStream(r[nestedKey], meter, opts, callModel, callTaskKey, start);
886
+ return response;
337
887
  }
338
888
  const latencyMs = Math.round(now() - start);
339
889
  try {
@@ -348,6 +898,7 @@ export class MarginMeter {
348
898
  operation: opts.operation,
349
899
  isSimulated: opts.isSimulated,
350
900
  substrate: opts.substrate,
901
+ taskKey: callTaskKey,
351
902
  });
352
903
  }
353
904
  catch {
@@ -365,6 +916,19 @@ function isAsyncIterable(x) {
365
916
  (typeof x === "object" || typeof x === "function") &&
366
917
  typeof x[Symbol.asyncIterator] === "function");
367
918
  }
919
+ /** The field a Bedrock streaming response carries its event stream under, if any.
920
+ * A non-streaming `InvokeModel` body is a Uint8Array, not async-iterable, so it is
921
+ * never mistaken for one. */
922
+ function bedrockStreamKey(response) {
923
+ if (response == null || typeof response !== "object")
924
+ return undefined;
925
+ const r = response;
926
+ if (isAsyncIterable(r.stream))
927
+ return "stream";
928
+ if (isAsyncIterable(r.body))
929
+ return "body";
930
+ return undefined;
931
+ }
368
932
  /** When this wrapper is an OpenAI chat patch (`streamIncludeUsage`) AND the call
369
933
  * requests `stream: true`, add `stream_options.include_usage` so OpenAI emits its
370
934
  * usage on the final chunk. Clones the params object (never mutates the caller's),
@@ -402,7 +966,7 @@ function maybeInjectIncludeUsage(args, opts) {
402
966
  * delegates to the wrapped stream, so `for await (const c of stream)`, `.tee()`,
403
967
  * and the rest work unchanged. Fail-safe: a metering hiccup never breaks iteration.
404
968
  */
405
- function meteredStream(stream, meter, opts, callModel, start) {
969
+ function meteredStream(stream, meter, opts, callModel, callTaskKey, start) {
406
970
  const acc = new StreamUsageAccumulator(opts.provider, callModel);
407
971
  let finished = false;
408
972
  const finish = async () => {
@@ -426,6 +990,7 @@ function meteredStream(stream, meter, opts, callModel, start) {
426
990
  cacheCreationTokens: usage.cacheCreationTokens,
427
991
  cacheCreation1hTokens: usage.cacheCreation1hTokens,
428
992
  reasoningTokens: usage.reasoningTokens,
993
+ costUsd: usage.billedCostUsd,
429
994
  latencyMs,
430
995
  status: "ok",
431
996
  isRetry: opts.isRetry,
@@ -433,6 +998,11 @@ function meteredStream(stream, meter, opts, callModel, start) {
433
998
  operation: opts.operation,
434
999
  isSimulated: opts.isSimulated,
435
1000
  substrate: opts.substrate,
1001
+ taskKey: callTaskKey,
1002
+ // A streaming Anthropic message_delta carries stop_reason too (the
1003
+ // accumulator merges it) — forward it so a streamed Fable fallback records
1004
+ // its reason like a non-streamed one.
1005
+ finishReason: usage.stopReason,
436
1006
  });
437
1007
  }
438
1008
  catch {
@@ -515,4 +1085,39 @@ async function extractDetail(resp) {
515
1085
  function now() {
516
1086
  return typeof performance !== "undefined" ? performance.now() : Date.now();
517
1087
  }
1088
+ function sleep(ms) {
1089
+ return new Promise((resolve) => {
1090
+ const timer = setTimeout(resolve, ms);
1091
+ // Unref'd for the same reason the flush timer is: a backoff must never be the
1092
+ // thing keeping a short-lived script alive.
1093
+ if (typeof timer.unref === "function") {
1094
+ timer.unref();
1095
+ }
1096
+ });
1097
+ }
1098
+ /** The server's own `Retry-After`, in ms, when it sent one.
1099
+ *
1100
+ * The ingest API computes the real wait from its rolling window rather than
1101
+ * sending a round number, so honouring it beats any backoff we could calculate
1102
+ * blind — a client that guesses either hammers or overshoots, and overshooting
1103
+ * drops exactly the calls the SDK was installed to record. */
1104
+ export function retryAfterMs_(resp) {
1105
+ const headers = resp.headers;
1106
+ const raw = headers?.get?.("Retry-After") ?? undefined;
1107
+ if (raw === undefined || raw === null)
1108
+ return undefined;
1109
+ const seconds = Number(raw);
1110
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : undefined;
1111
+ }
1112
+ /** FULL jitter — `random(0, base * 2**attempt)`, capped, or the server's wait.
1113
+ *
1114
+ * Jittered rather than plain exponential because every buffered client backs off
1115
+ * on the same schedule: un-jittered retries re-synchronise into a thundering herd
1116
+ * aimed at the endpoint that just failed, which is how a brief blip becomes an
1117
+ * outage. */
1118
+ export function backoffMs(attempt, retryAfter) {
1119
+ if (retryAfter !== undefined)
1120
+ return Math.min(RETRY_CAP_MS, retryAfter);
1121
+ return Math.random() * Math.min(RETRY_CAP_MS, RETRY_BASE_MS * 2 ** attempt);
1122
+ }
518
1123
  //# sourceMappingURL=index.js.map