@uselemma/tracing 7.13.1 → 7.15.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.
Files changed (99) hide show
  1. package/README.md +82 -26
  2. package/dist/client.d.ts +80 -10
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +278 -127
  5. package/dist/client.js.map +1 -1
  6. package/dist/coding-agent-backlog.d.ts +81 -0
  7. package/dist/coding-agent-backlog.d.ts.map +1 -0
  8. package/dist/coding-agent-backlog.js +239 -0
  9. package/dist/coding-agent-backlog.js.map +1 -0
  10. package/dist/coding-agent-delivery.d.ts +31 -0
  11. package/dist/coding-agent-delivery.d.ts.map +1 -0
  12. package/dist/coding-agent-delivery.js +97 -0
  13. package/dist/coding-agent-delivery.js.map +1 -0
  14. package/dist/coding-agent-queue.d.ts +74 -0
  15. package/dist/coding-agent-queue.d.ts.map +1 -0
  16. package/dist/coding-agent-queue.js +230 -0
  17. package/dist/coding-agent-queue.js.map +1 -0
  18. package/dist/coding-agent.d.ts +14 -0
  19. package/dist/coding-agent.d.ts.map +1 -1
  20. package/dist/coding-agent.js +52 -15
  21. package/dist/coding-agent.js.map +1 -1
  22. package/dist/debug-delivery.d.ts +0 -2
  23. package/dist/debug-delivery.d.ts.map +1 -1
  24. package/dist/debug-delivery.js +0 -19
  25. package/dist/debug-delivery.js.map +1 -1
  26. package/dist/debug-mode.d.ts.map +1 -1
  27. package/dist/debug-mode.js +4 -4
  28. package/dist/debug-mode.js.map +1 -1
  29. package/dist/delivery.d.ts +108 -0
  30. package/dist/delivery.d.ts.map +1 -0
  31. package/dist/delivery.js +266 -0
  32. package/dist/delivery.js.map +1 -0
  33. package/dist/dropped-traces.d.ts +16 -0
  34. package/dist/dropped-traces.d.ts.map +1 -0
  35. package/dist/dropped-traces.js +46 -0
  36. package/dist/dropped-traces.js.map +1 -0
  37. package/dist/env.d.ts +8 -0
  38. package/dist/env.d.ts.map +1 -0
  39. package/dist/env.js +18 -0
  40. package/dist/env.js.map +1 -0
  41. package/dist/error-message.d.ts +10 -0
  42. package/dist/error-message.d.ts.map +1 -1
  43. package/dist/error-message.js +14 -0
  44. package/dist/error-message.js.map +1 -1
  45. package/dist/index.d.ts +3 -2
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +3 -1
  48. package/dist/index.js.map +1 -1
  49. package/dist/integration-client.d.ts +20 -0
  50. package/dist/integration-client.d.ts.map +1 -0
  51. package/dist/integration-client.js +47 -0
  52. package/dist/integration-client.js.map +1 -0
  53. package/dist/langchain-context.d.ts +7 -0
  54. package/dist/langchain-context.d.ts.map +1 -0
  55. package/dist/langchain-context.js +28 -0
  56. package/dist/langchain-context.js.map +1 -0
  57. package/dist/langchain-eviction.d.ts +42 -0
  58. package/dist/langchain-eviction.d.ts.map +1 -0
  59. package/dist/langchain-eviction.js +56 -0
  60. package/dist/langchain-eviction.js.map +1 -0
  61. package/dist/langchain.d.ts +31 -13
  62. package/dist/langchain.d.ts.map +1 -1
  63. package/dist/langchain.js +74 -109
  64. package/dist/langchain.js.map +1 -1
  65. package/dist/mastra.d.ts +9 -11
  66. package/dist/mastra.d.ts.map +1 -1
  67. package/dist/mastra.js +40 -25
  68. package/dist/mastra.js.map +1 -1
  69. package/dist/openai-agents.d.ts +8 -0
  70. package/dist/openai-agents.d.ts.map +1 -1
  71. package/dist/openai-agents.js +17 -14
  72. package/dist/openai-agents.js.map +1 -1
  73. package/dist/serialize.d.ts +17 -0
  74. package/dist/serialize.d.ts.map +1 -0
  75. package/dist/serialize.js +143 -0
  76. package/dist/serialize.js.map +1 -0
  77. package/dist/stream-result.d.ts +33 -0
  78. package/dist/stream-result.d.ts.map +1 -0
  79. package/dist/stream-result.js +135 -0
  80. package/dist/stream-result.js.map +1 -0
  81. package/dist/vercel-ai-events.d.ts +308 -0
  82. package/dist/vercel-ai-events.d.ts.map +1 -0
  83. package/dist/vercel-ai-events.js +340 -0
  84. package/dist/vercel-ai-events.js.map +1 -0
  85. package/dist/vercel-ai-run.d.ts +171 -0
  86. package/dist/vercel-ai-run.d.ts.map +1 -0
  87. package/dist/vercel-ai-run.js +650 -0
  88. package/dist/vercel-ai-run.js.map +1 -0
  89. package/dist/vercel-ai.d.ts +36 -108
  90. package/dist/vercel-ai.d.ts.map +1 -1
  91. package/dist/vercel-ai.js +185 -882
  92. package/dist/vercel-ai.js.map +1 -1
  93. package/dist/version.d.ts +2 -0
  94. package/dist/version.d.ts.map +1 -0
  95. package/dist/version.js +6 -0
  96. package/dist/version.js.map +1 -0
  97. package/examples/vercel-ai-v6.ts +2 -2
  98. package/examples/vercel-ai-v7.ts +14 -16
  99. package/package.json +1 -1
package/dist/client.js CHANGED
@@ -1,11 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Lemma = exports.TraceHandle = exports.TraceContext = exports.NoopSpanHandle = exports.SpanHandle = exports.toWireTokenUsage = exports.normalizeTokenUsage = exports.attachResultUsage = void 0;
4
+ exports.startBackgroundTrace = startBackgroundTrace;
4
5
  const debug_delivery_1 = require("./debug-delivery");
5
6
  const debug_mode_1 = require("./debug-mode");
7
+ const delivery_1 = require("./delivery");
8
+ const dropped_traces_1 = require("./dropped-traces");
9
+ const env_1 = require("./env");
6
10
  const error_message_1 = require("./error-message");
7
11
  const release_1 = require("./release");
12
+ const serialize_1 = require("./serialize");
13
+ const stream_result_1 = require("./stream-result");
8
14
  const usage_1 = require("./usage");
15
+ const version_1 = require("./version");
9
16
  var usage_2 = require("./usage");
10
17
  Object.defineProperty(exports, "attachResultUsage", { enumerable: true, get: function () { return usage_2.attachResultUsage; } });
11
18
  Object.defineProperty(exports, "normalizeTokenUsage", { enumerable: true, get: function () { return usage_2.normalizeTokenUsage; } });
@@ -58,12 +65,7 @@ function serializeAttribute(value) {
58
65
  typeof value === "number" ||
59
66
  typeof value === "boolean")
60
67
  return value;
61
- try {
62
- return JSON.stringify(value);
63
- }
64
- catch {
65
- return String(value);
66
- }
68
+ return (0, serialize_1.stringifyTraceJson)(value);
67
69
  }
68
70
  function addDefined(attributes, key, value) {
69
71
  if (value !== undefined)
@@ -169,6 +171,13 @@ function normalizeSpan(options, fallbackType) {
169
171
  ...(usage ? { usage } : {}),
170
172
  };
171
173
  }
174
+ /** JSON for a built payload, which is a plain object and always serializes. */
175
+ function payloadBody(payload) {
176
+ const body = (0, serialize_1.stringifyTraceJson)(payload);
177
+ if (body === undefined)
178
+ throw new Error("trace payload is empty");
179
+ return body;
180
+ }
172
181
  function warnNoop(message) {
173
182
  console.warn(`@uselemma/tracing: ${message}`);
174
183
  }
@@ -227,6 +236,19 @@ class SpanHandle {
227
236
  this.trace.spanEnded(this.payload);
228
237
  this.trace.changed();
229
238
  }
239
+ /**
240
+ * Close this span as failed if it is still open. A no-op once ended, so a
241
+ * completed span is never rewritten. The end is never before the start.
242
+ */
243
+ failUnfinished(error, endedAt) {
244
+ if (this.ended)
245
+ return;
246
+ const startedMs = timestampMs(this.payload.started_at);
247
+ const closedAt = startedMs != null && startedMs > endedAt.getTime()
248
+ ? new Date(startedMs)
249
+ : endedAt;
250
+ this.end({ status: "ERROR", error, endedAt: closedAt });
251
+ }
230
252
  /**
231
253
  * Fill input or output after end() when a child model call finishes later.
232
254
  * Input is written only while this span still has none. Output is replaced
@@ -322,6 +344,7 @@ exports.SpanHandle = SpanHandle;
322
344
  class NoopSpanHandle {
323
345
  id = "";
324
346
  end() { }
347
+ failUnfinished(_error, _endedAt) { }
325
348
  ensureEndedAt(_endedAt) { }
326
349
  startSpan() {
327
350
  return this;
@@ -349,8 +372,11 @@ class TraceContext {
349
372
  onChange;
350
373
  spans = [];
351
374
  spanHandles = new Map();
352
- traceOutput;
375
+ /** Boxed, so an output set to undefined still counts as set. */
376
+ rootOutput;
353
377
  traceError = null;
378
+ /** Set by {@link markPayloadFinal}; cleared by the first change after it. */
379
+ sent = false;
354
380
  id;
355
381
  constructor(options, onChange) {
356
382
  this.options = options;
@@ -358,16 +384,21 @@ class TraceContext {
358
384
  this.options.name ??= "trace";
359
385
  this.options.id ??= crypto.randomUUID();
360
386
  this.id = this.options.id;
361
- this.traceOutput = options.output;
387
+ this.rootOutput =
388
+ options.output === undefined ? undefined : { value: options.output };
362
389
  }
363
390
  input(value) {
364
391
  this.options.input = value;
365
392
  this.changed();
366
393
  }
367
394
  output(value) {
368
- this.traceOutput = value;
395
+ this.rootOutput = { value };
369
396
  this.changed();
370
397
  }
398
+ /** Whether the root output was set through options or `output()`. */
399
+ get hasOutput() {
400
+ return this.rootOutput !== undefined;
401
+ }
371
402
  threadId(value) {
372
403
  this.options.threadId = value;
373
404
  this.changed();
@@ -402,8 +433,25 @@ class TraceContext {
402
433
  return this.spans.some((span) => span.id === id);
403
434
  }
404
435
  changed() {
436
+ if (this.sent) {
437
+ this.sent = false;
438
+ (0, debug_mode_1.lemmaDebug)("client", "trace changed after its final payload was built; not delivered", {
439
+ traceId: this.id,
440
+ });
441
+ }
405
442
  this.onChange?.();
406
443
  }
444
+ /**
445
+ * Marks that this trace's payload won't be built again: an automatic send
446
+ * builds it once and never rebuilds it, and a strict send can be retried
447
+ * with a rebuilt payload until it succeeds. Debug mode then logs the first
448
+ * later change, which isn't delivered.
449
+ *
450
+ * @internal
451
+ */
452
+ markPayloadFinal() {
453
+ this.sent = true;
454
+ }
407
455
  setChangeHandler(onChange) {
408
456
  this.onChange = onChange;
409
457
  }
@@ -500,7 +548,7 @@ class TraceContext {
500
548
  id: this.options.id,
501
549
  name: this.options.name ?? "trace",
502
550
  input: this.options.input,
503
- output: this.traceOutput,
551
+ output: this.rootOutput?.value,
504
552
  metadata: this.options.metadata,
505
553
  thread_id: this.options.threadId,
506
554
  user_id: this.options.userId,
@@ -517,8 +565,10 @@ class TraceContext {
517
565
  exports.TraceContext = TraceContext;
518
566
  class TraceHandle extends TraceContext {
519
567
  sendFn;
520
- sendPromise = Promise.resolve();
521
- ended = false;
568
+ /** The send `end()` started; cleared when a strict send fails. */
569
+ sending;
570
+ /** Set by the first `end()`; a retry reuses its output and root timing. */
571
+ rootTiming;
522
572
  startedAt;
523
573
  constructor(options, sendFn, startedAt) {
524
574
  super(options);
@@ -531,52 +581,95 @@ class TraceHandle extends TraceContext {
531
581
  // duplicates. Recording mutates the in-memory trace only; the single
532
582
  // terminal send from `end()` carries the complete trace.
533
583
  }
534
- async end(outputOrOptions) {
535
- // Ending is idempotent: a trace is sent exactly once so a second end()
536
- // can't duplicate its spans.
537
- if (this.ended)
538
- return this.sendPromise;
539
- let endedAtOverride;
540
- let startedAtOverride;
541
- if (isTraceEndOptions(outputOrOptions)) {
542
- if ("output" in outputOrOptions) {
543
- this.output(outputOrOptions.output);
544
- }
545
- if (outputOrOptions.durationMs != null) {
546
- this.duration(outputOrOptions.durationMs);
547
- }
548
- startedAtOverride = coerceDate(outputOrOptions.startedAt);
549
- endedAtOverride = coerceDate(outputOrOptions.endedAt);
584
+ end(outputOrOptions) {
585
+ // A second end() returns the first send, so a delivered trace's spans
586
+ // are never sent twice. Only a failed strict send lets end() send again.
587
+ if (this.sending)
588
+ return this.sending;
589
+ this.rootTiming ??= this.applyEnd(outputOrOptions, arguments.length > 0);
590
+ const { startedAt, endedAt } = this.rootTiming;
591
+ // Started now, not on a later tick, so a flush() called right after
592
+ // end() already waits for this send.
593
+ const sending = this.startSend(startedAt, endedAt);
594
+ this.sending = sending;
595
+ // Registered before the caller's own handler, so a caller that catches
596
+ // the failure can call end() again at once. It also observes the
597
+ // rejection, so an end() nobody awaits is not an unhandled rejection.
598
+ sending.catch(() => {
599
+ this.sending = undefined;
600
+ });
601
+ return sending;
602
+ }
603
+ /** Apply the first `end()`'s output and duration, and fix the root timing. */
604
+ applyEnd(outputOrOptions, hasArgument) {
605
+ if (!isTraceEndOptions(outputOrOptions)) {
606
+ if (hasArgument)
607
+ this.output(outputOrOptions);
608
+ return { startedAt: this.startedAt, endedAt: new Date() };
550
609
  }
551
- else if (arguments.length > 0) {
552
- this.output(outputOrOptions);
610
+ if ("output" in outputOrOptions)
611
+ this.output(outputOrOptions.output);
612
+ if (outputOrOptions.durationMs != null) {
613
+ this.duration(outputOrOptions.durationMs);
614
+ }
615
+ return {
616
+ startedAt: coerceDate(outputOrOptions.startedAt) ?? this.startedAt,
617
+ endedAt: coerceDate(outputOrOptions.endedAt) ?? new Date(),
618
+ };
619
+ }
620
+ /** A sendFn that throws synchronously rejects instead of throwing. */
621
+ startSend(startedAt, endedAt) {
622
+ try {
623
+ return this.sendFn(this, startedAt, endedAt);
624
+ }
625
+ catch (error) {
626
+ return Promise.reject(error);
553
627
  }
554
- this.ended = true;
555
- const startedAt = startedAtOverride ?? this.startedAt;
556
- const endedAt = endedAtOverride ?? new Date();
557
- this.sendPromise = this.sendPromise.then(() => this.sendFn(this, startedAt, endedAt));
558
- await this.sendPromise;
559
628
  }
560
- /** Whether this trace has already been delivered via `end()`. */
629
+ /** Whether `end()` has sent this trace, or is sending it. */
561
630
  get isEnded() {
562
- return this.ended;
631
+ return this.sending !== undefined;
563
632
  }
564
633
  }
565
634
  exports.TraceHandle = TraceHandle;
635
+ /**
636
+ * A trace handle whose `end()` delivers with the background budget, for an
637
+ * integration that starts and ends its own trace after the run.
638
+ *
639
+ * @internal
640
+ */
641
+ function startBackgroundTrace(lemma, options) {
642
+ return lemma.startTrace(options, delivery_1.BACKGROUND_DELIVERY);
643
+ }
566
644
  class Lemma {
567
645
  apiKey;
568
646
  projectId;
569
647
  baseUrl;
570
648
  fetchImpl;
649
+ /** Identity and credentials on every request; spread last so nothing overrides them. */
650
+ baseHeaders;
571
651
  release;
572
652
  traces = new Map();
653
+ /** Sends in flight, and callback traces held open by a returned stream. */
654
+ pending = new Set();
573
655
  configLogged = false;
574
656
  constructor(options = {}) {
575
- this.apiKey = required(options.apiKey ?? process.env.LEMMA_API_KEY, "LEMMA_API_KEY");
576
- this.projectId = required(options.projectId ?? process.env.LEMMA_PROJECT_ID, "LEMMA_PROJECT_ID");
577
- this.baseUrl = (options.baseUrl ?? "https://api.uselemma.ai").replace(/\/+$/, "");
578
- this.fetchImpl = options.fetch ?? fetch;
579
- this.release = (0, release_1.normalizeRelease)(options.release ?? process.env.LEMMA_RELEASE);
657
+ this.apiKey = required(options.apiKey ?? (0, env_1.readEnv)(() => process.env.LEMMA_API_KEY), "LEMMA_API_KEY");
658
+ this.projectId = required(options.projectId ?? (0, env_1.readEnv)(() => process.env.LEMMA_PROJECT_ID), "LEMMA_PROJECT_ID");
659
+ this.baseUrl = (options.baseUrl ??
660
+ ((0, env_1.readEnv)(() => process.env.LEMMA_BASE_URL)?.trim() || debug_delivery_1.PRODUCTION_BASE_URL)).replace(/\/+$/, "");
661
+ // Workers' fetch throws "Illegal invocation" when it is called with a
662
+ // receiver other than the global object, so neither the global nor a
663
+ // passed-in fetch is called as a method of this client. The global is
664
+ // read per call, so a fetch that instrumentation installs after the
665
+ // client is built is the one used.
666
+ const customFetch = options.fetch;
667
+ this.fetchImpl = (input, init) => (customFetch ?? fetch)(input, init);
668
+ this.baseHeaders = {
669
+ "User-Agent": options.userAgent ?? version_1.SDK_USER_AGENT,
670
+ Authorization: `Bearer ${this.apiKey}`,
671
+ };
672
+ this.release = (0, release_1.normalizeRelease)(options.release ?? (0, env_1.readEnv)(() => process.env.LEMMA_RELEASE));
580
673
  this.logInitConfigOnce();
581
674
  }
582
675
  /**
@@ -603,18 +696,11 @@ class Lemma {
603
696
  context.output("ok");
604
697
  const startedAt = new Date();
605
698
  const payload = this.stampRelease(context.toPayload(this.projectId, startedAt, new Date()));
606
- const body = JSON.stringify(payload);
699
+ const body = payloadBody(payload);
607
700
  const url = `${this.baseUrl}${debug_delivery_1.INGEST_PATH}`;
608
701
  let response;
609
702
  try {
610
- response = await this.fetchImpl(url, {
611
- method: "POST",
612
- headers: {
613
- Authorization: `Bearer ${this.apiKey}`,
614
- "Content-Type": "application/json",
615
- },
616
- body,
617
- });
703
+ response = await (0, delivery_1.withIngestTimeout)((signal) => this.postIngest(body, signal));
618
704
  }
619
705
  catch {
620
706
  hints.push("ingest request failed (network error)");
@@ -628,7 +714,10 @@ class Lemma {
628
714
  const ingestWarnings = [];
629
715
  if (response.status !== debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS) {
630
716
  ingestWarnings.push(`expected status ${debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS}, got ${response.status}`);
631
- const hint = (0, debug_delivery_1.ingestFailureHint)(response.status);
717
+ // Best effort under its own timeout: a stalled body must neither hang
718
+ // the smoke test nor hide the status Lemma returned.
719
+ const failureBody = await (0, delivery_1.withIngestTimeout)(() => response.text()).catch(() => "");
720
+ const hint = (0, delivery_1.ingestFailureHint)(response.status, failureBody);
632
721
  if (hint)
633
722
  hints.push(hint);
634
723
  }
@@ -670,24 +759,8 @@ class Lemma {
670
759
  }
671
760
  trace(options = {}, fn) {
672
761
  const traceOptions = typeof options === "string" ? { name: options } : options;
673
- if (!fn) {
674
- const handle = new TraceHandle(traceOptions, async (trace, startedAt, endedAt) => {
675
- try {
676
- await this.flushTraceAutomatic(trace, startedAt, endedAt);
677
- }
678
- finally {
679
- // Drop the handle once ended so long-lived clients don't retain
680
- // every historical TraceHandle (and its spans/payloads) forever.
681
- this.traces.delete(trace.id);
682
- }
683
- });
684
- this.traces.set(handle.id, handle);
685
- (0, debug_mode_1.lemmaDebug)("client", "trace handle created", {
686
- traceId: handle.id,
687
- name: traceOptions.name ?? "trace",
688
- });
689
- return handle;
690
- }
762
+ if (!fn)
763
+ return this.startTrace(traceOptions, delivery_1.AWAITED_DELIVERY);
691
764
  const context = new TraceContext(traceOptions);
692
765
  const startedAt = new Date();
693
766
  (0, debug_mode_1.lemmaDebug)("client", "trace started", {
@@ -702,19 +775,71 @@ class Lemma {
702
775
  catch (error) {
703
776
  // Only the agent's own failure belongs in this branch.
704
777
  context.fail(error);
705
- await this.flushTraceAutomatic(context, startedAt, new Date());
778
+ await this.flushTraceAutomatic(context, startedAt, new Date(), delivery_1.AWAITED_DELIVERY);
706
779
  throw error;
707
780
  }
708
- if (traceOptions.output === undefined) {
781
+ const held = (0, stream_result_1.holdTraceForStream)(result, context, () => this.flushTraceAutomatic(context, startedAt, new Date(), delivery_1.BACKGROUND_DELIVERY));
782
+ if (held) {
783
+ // Tracked from now, so a flush() called while the stream is still
784
+ // being read waits for its trace.
785
+ this.track(held.sent);
786
+ return held.stream;
787
+ }
788
+ if (!context.hasOutput) {
709
789
  context.output(result);
710
790
  }
711
791
  // Automatic delivery is outside the agent's try: a transport failure
712
792
  // must not be recorded as an agent failure. Fail-open so Lemma being
713
793
  // down cannot fail the caller's app; ingest() stays strict for retries.
714
- await this.flushTraceAutomatic(context, startedAt, new Date());
794
+ await this.flushTraceAutomatic(context, startedAt, new Date(), delivery_1.AWAITED_DELIVERY);
715
795
  return result;
716
796
  })();
717
797
  }
798
+ /**
799
+ * Wait until every trace this client has started sending is delivered or
800
+ * dropped, including each callback trace whose returned stream is still
801
+ * being read. Never rejects. A trace handle that hasn't been ended yet is
802
+ * not waited for.
803
+ *
804
+ * Pass it to the runtime so delivery outlives the response:
805
+ * `ctx.waitUntil(lemma.flush())` on Cloudflare Workers,
806
+ * `after(() => lemma.flush())` in Next.js. On AWS Lambda, await it before
807
+ * the handler returns.
808
+ */
809
+ async flush() {
810
+ await Promise.allSettled(Array.from(this.pending));
811
+ }
812
+ track(promise) {
813
+ this.pending.add(promise);
814
+ const forget = () => this.pending.delete(promise);
815
+ promise.then(forget, forget);
816
+ return promise;
817
+ }
818
+ /**
819
+ * A trace handle whose `end()` delivers within `budget`. A caller's
820
+ * `lemma.trace()` handle uses `AWAITED_DELIVERY`; `startBackgroundTrace()`
821
+ * uses `BACKGROUND_DELIVERY`.
822
+ *
823
+ * @internal
824
+ */
825
+ startTrace(options, budget) {
826
+ const handle = new TraceHandle(options, async (trace, startedAt, endedAt) => {
827
+ try {
828
+ await this.flushTraceAutomatic(trace, startedAt, endedAt, budget);
829
+ }
830
+ finally {
831
+ // Drop the handle once ended so long-lived clients don't retain
832
+ // every historical TraceHandle (and its spans/payloads) forever.
833
+ this.traces.delete(trace.id);
834
+ }
835
+ });
836
+ this.traces.set(handle.id, handle);
837
+ (0, debug_mode_1.lemmaDebug)("client", "trace handle created", {
838
+ traceId: handle.id,
839
+ name: options.name ?? "trace",
840
+ });
841
+ return handle;
842
+ }
718
843
  /**
719
844
  * Deliver a trace you assembled yourself, in a single request.
720
845
  *
@@ -730,11 +855,15 @@ class Lemma {
730
855
  * fields do not preserve prior values, and after Lemma processes the trace
731
856
  * once, a later re-delivery does not re-run issue extraction (late new span
732
857
  * IDs may still append for display). Retries of the same complete payload are
733
- * safe: already-stored span IDs are skipped. Throws on a non-2xx response and
734
- * never mutates the trace's status, so a failed send can be retried as-is.
858
+ * safe: already-stored span IDs are skipped. Throws an `IngestError` on
859
+ * a non-2xx response, and never mutates the trace's status, so a failed send
860
+ * can be retried as-is.
735
861
  */
736
862
  async ingest(context, options) {
737
- await this.flushTrace(context, options.startedAt, options.endedAt ?? new Date());
863
+ const failure = await this.sendTrace(context, options.startedAt, options.endedAt ?? new Date(), delivery_1.STRICT_DELIVERY);
864
+ if (failure)
865
+ throw failure.error;
866
+ context.markPayloadFinal();
738
867
  }
739
868
  recordSpan(options) {
740
869
  const context = this.detachedTraceFor(options.traceId, "span");
@@ -876,13 +1005,16 @@ class Lemma {
876
1005
  `?project_id=${encodeURIComponent(this.projectId)}` +
877
1006
  `&otel_trace_id=${encodeURIComponent(otelTraceId)}`;
878
1007
  try {
879
- const response = await this.fetchImpl(url, {
880
- headers: { Authorization: `Bearer ${this.apiKey}` },
1008
+ return await (0, delivery_1.withIngestTimeout)(async (signal) => {
1009
+ const response = await this.fetchImpl(url, {
1010
+ headers: { ...this.baseHeaders },
1011
+ signal,
1012
+ });
1013
+ if (!response.ok)
1014
+ return null;
1015
+ const data = (await response.json());
1016
+ return (0, debug_delivery_1.parseIngestStatus)(data.status);
881
1017
  });
882
- if (!response.ok)
883
- return null;
884
- const data = (await response.json());
885
- return (0, debug_delivery_1.parseIngestStatus)(data.status);
886
1018
  }
887
1019
  catch {
888
1020
  return null;
@@ -903,7 +1035,7 @@ class Lemma {
903
1035
  const remaining = deadline - Date.now();
904
1036
  if (remaining <= 0)
905
1037
  return status;
906
- await (0, debug_delivery_1.sleep)(Math.min(debug_delivery_1.INGEST_STATUS_POLL_INTERVAL_MS, remaining));
1038
+ await (0, delivery_1.sleep)(Math.min(debug_delivery_1.INGEST_STATUS_POLL_INTERVAL_MS, remaining));
907
1039
  }
908
1040
  }
909
1041
  async verifyIngestDelivery(otelTraceId) {
@@ -924,64 +1056,83 @@ class Lemma {
924
1056
  return payload;
925
1057
  }
926
1058
  /**
927
- * Automatic SDK delivery. Catches transport / non-2xx so Lemma being down
928
- * cannot fail the caller's app. {@link Lemma.ingest} uses {@link flushTrace}
929
- * (strict) so queue/plugin producers can retry.
1059
+ * Automatic SDK delivery. Retries transient failures, then fails open with
1060
+ * a rate-limited warning so Lemma being down cannot fail the caller's app.
1061
+ * {@link Lemma.ingest} sends once and throws, because queue/plugin producers
1062
+ * keep their own retry backlog.
930
1063
  */
931
- async flushTraceAutomatic(context, startedAt, endedAt) {
1064
+ async flushTraceAutomatic(context, startedAt, endedAt, budget) {
1065
+ const sending = this.sendTrace(context, startedAt, endedAt, budget);
1066
+ // Built by now, and never resent, so a later change isn't delivered.
1067
+ context.markPayloadFinal();
1068
+ const failure = await sending;
1069
+ if (failure)
1070
+ (0, dropped_traces_1.reportDroppedTrace)(context.id, failure.cause);
1071
+ }
1072
+ /** {@link Lemma.buildAndSend}, tracked so `flush()` waits for it. */
1073
+ sendTrace(context, startedAt, endedAt, budget) {
1074
+ return this.track(this.buildAndSend(context, startedAt, endedAt, budget));
1075
+ }
1076
+ /**
1077
+ * Build, send, and check one trace; undefined when it was delivered. A
1078
+ * payload that cannot be built comes back as a failure, so strict and
1079
+ * automatic delivery handle it once.
1080
+ */
1081
+ async buildAndSend(context, startedAt, endedAt, budget) {
1082
+ const built = this.buildIngestBody(context, startedAt, endedAt);
1083
+ if (!built.ok)
1084
+ return built;
1085
+ const result = await (0, delivery_1.deliver)((signal) => this.postIngest(built.body, signal), { traceId: context.id, projectId: this.projectId }, budget);
1086
+ if (!result.ok)
1087
+ return result;
1088
+ // Debug-only checks; the trace is already stored, so a failure here
1089
+ // must neither fail the caller nor count as a dropped trace.
932
1090
  try {
933
- await this.flushTrace(context, startedAt, endedAt);
1091
+ await this.afterTraceSent(built.payload, result.response);
934
1092
  }
935
- catch {
936
- // flushTrace already lemmaDebug'd "trace ingest failed".
1093
+ catch (error) {
1094
+ console.warn(`@uselemma/tracing: trace ${context.id} was delivered, but its post-send check failed: ${(0, error_message_1.describeError)(error)}`);
937
1095
  }
1096
+ return undefined;
938
1097
  }
939
- async flushTrace(context, startedAt, endedAt) {
940
- const payload = this.stampRelease(context.toPayload(this.projectId, startedAt, endedAt));
941
- const body = JSON.stringify(payload);
942
- const url = `${this.baseUrl}${debug_delivery_1.INGEST_PATH}`;
943
- (0, debug_mode_1.lemmaDebug)("client", "sending trace", {
944
- traceId: payload.trace.id,
945
- name: payload.trace.name,
946
- spanCount: payload.trace.spans.length,
947
- projectId: payload.project_id,
948
- bodyBytes: new TextEncoder().encode(body).length,
949
- requestedAt: new Date().toISOString(),
950
- url,
951
- });
952
- let response;
1098
+ /**
1099
+ * Serialize once, so every attempt resends the same span IDs and ingest
1100
+ * dedupes an earlier attempt that landed unseen.
1101
+ */
1102
+ buildIngestBody(context, startedAt, endedAt) {
953
1103
  try {
954
- response = await this.fetchImpl(url, {
955
- method: "POST",
956
- headers: {
957
- Authorization: `Bearer ${this.apiKey}`,
958
- "Content-Type": "application/json",
959
- },
960
- body,
1104
+ const payload = this.stampRelease(context.toPayload(this.projectId, startedAt, endedAt));
1105
+ const body = payloadBody(payload);
1106
+ (0, debug_mode_1.lemmaDebug)("client", "sending trace", {
1107
+ traceId: payload.trace.id,
1108
+ name: payload.trace.name,
1109
+ spanCount: payload.trace.spans.length,
1110
+ projectId: payload.project_id,
1111
+ bodyBytes: new TextEncoder().encode(body).length,
1112
+ requestedAt: new Date().toISOString(),
1113
+ url: `${this.baseUrl}${debug_delivery_1.INGEST_PATH}`,
961
1114
  });
1115
+ return { ok: true, payload, body };
962
1116
  }
963
1117
  catch (error) {
964
1118
  (0, debug_mode_1.lemmaDebug)("client", "trace ingest failed", {
965
- traceId: payload.trace.id,
966
- projectId: payload.project_id,
1119
+ traceId: context.id,
1120
+ projectId: this.projectId,
967
1121
  error: (0, error_message_1.failureMessage)(error) ?? String(error),
968
1122
  });
969
- throw error;
1123
+ return (0, delivery_1.failedBeforeSending)(error);
970
1124
  }
1125
+ }
1126
+ postIngest(body, signal) {
1127
+ return this.fetchImpl(`${this.baseUrl}${debug_delivery_1.INGEST_PATH}`, {
1128
+ method: "POST",
1129
+ headers: { "Content-Type": "application/json", ...this.baseHeaders },
1130
+ body,
1131
+ signal,
1132
+ });
1133
+ }
1134
+ async afterTraceSent(payload, response) {
971
1135
  const responseHeaders = (0, debug_delivery_1.pickResponseHeaders)(response.headers);
972
- if (!response.ok) {
973
- const responseBody = await response.text().catch(() => "");
974
- const hint = (0, debug_delivery_1.ingestFailureHint)(response.status);
975
- (0, debug_mode_1.lemmaDebug)("client", "trace ingest failed", {
976
- traceId: payload.trace.id,
977
- projectId: payload.project_id,
978
- status: response.status,
979
- body: responseBody,
980
- ...responseHeaders,
981
- ...(hint ? { hint } : {}),
982
- });
983
- throw new Error(`@uselemma/tracing: failed to ingest trace (${response.status})${responseBody ? `: ${responseBody}` : ""}`);
984
- }
985
1136
  const sentWarnings = [];
986
1137
  if (response.status !== debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS) {
987
1138
  sentWarnings.push(`expected status ${debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS}, got ${response.status} (wrong endpoint?)`);