@uselemma/opencode 0.1.3 → 0.2.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/runtime/lemma.mjs CHANGED
@@ -107,6 +107,22 @@ var require_debug_delivery = __commonJS({
107
107
  }
108
108
  });
109
109
 
110
+ // ../../packages/ts/tracing/dist/env.js
111
+ var require_env = __commonJS({
112
+ "../../packages/ts/tracing/dist/env.js"(exports) {
113
+ "use strict";
114
+ Object.defineProperty(exports, "__esModule", { value: true });
115
+ exports.readEnv = readEnv;
116
+ function readEnv(read) {
117
+ try {
118
+ return read();
119
+ } catch {
120
+ return void 0;
121
+ }
122
+ }
123
+ }
124
+ });
125
+
110
126
  // ../../packages/ts/tracing/dist/debug-mode.js
111
127
  var require_debug_mode = __commonJS({
112
128
  "../../packages/ts/tracing/dist/debug-mode.js"(exports) {
@@ -117,9 +133,9 @@ var require_debug_mode = __commonJS({
117
133
  exports.isDebugModeEnabled = isDebugModeEnabled;
118
134
  exports.isDebugVerifyEnabled = isDebugVerifyEnabled;
119
135
  exports.lemmaDebug = lemmaDebug;
136
+ var env_1 = require_env();
120
137
  var debugModeEnabled = false;
121
- function isEnvFlagEnabled(name) {
122
- const value = process.env[name];
138
+ function isFlagOn(value) {
123
139
  return value === "1" || value === "true";
124
140
  }
125
141
  function enableDebugMode() {
@@ -129,10 +145,10 @@ var require_debug_mode = __commonJS({
129
145
  debugModeEnabled = false;
130
146
  }
131
147
  function isDebugModeEnabled() {
132
- return debugModeEnabled || isEnvFlagEnabled("LEMMA_DEBUG");
148
+ return debugModeEnabled || isFlagOn((0, env_1.readEnv)(() => process.env.LEMMA_DEBUG));
133
149
  }
134
150
  function isDebugVerifyEnabled() {
135
- return isEnvFlagEnabled("LEMMA_DEBUG_VERIFY");
151
+ return isFlagOn((0, env_1.readEnv)(() => process.env.LEMMA_DEBUG_VERIFY));
136
152
  }
137
153
  function lemmaDebug(prefix, msg, data) {
138
154
  if (!isDebugModeEnabled())
@@ -154,6 +170,7 @@ var require_error_message = __commonJS({
154
170
  exports.errorMessage = errorMessage;
155
171
  exports.describeError = describeError;
156
172
  exports.failureMessage = failureMessage;
173
+ exports.failOpenGenerations = failOpenGenerations;
157
174
  function errorMessage(error) {
158
175
  if (error == null)
159
176
  return null;
@@ -224,6 +241,12 @@ var require_error_message = __commonJS({
224
241
  }
225
242
  }
226
243
  var GENERIC_ERROR_NAME = "Error";
244
+ function failOpenGenerations(handles, runError, endedAt) {
245
+ if (!runError)
246
+ return;
247
+ for (const handle of handles)
248
+ handle?.failUnfinished(runError, endedAt);
249
+ }
227
250
  }
228
251
  });
229
252
 
@@ -232,7 +255,7 @@ var require_delivery = __commonJS({
232
255
  "../../packages/ts/tracing/dist/delivery.js"(exports) {
233
256
  "use strict";
234
257
  Object.defineProperty(exports, "__esModule", { value: true });
235
- exports.INGEST_RETRY_MAX_DELAY_MS = exports.INGEST_RETRY_BASE_DELAY_MS = exports.INGEST_REQUEST_TIMEOUT_MS = exports.INGEST_MAX_ATTEMPTS = exports.INGEST_STRICT_ATTEMPTS = void 0;
258
+ exports.STRICT_DELIVERY = exports.BACKGROUND_DELIVERY = exports.AWAITED_DELIVERY = exports.IngestError = exports.INGEST_RETRY_MAX_DELAY_MS = exports.INGEST_RETRY_BASE_DELAY_MS = exports.AWAITED_INGEST_TOTAL_TIMEOUT_MS = exports.AWAITED_INGEST_REQUEST_TIMEOUT_MS = exports.INGEST_REQUEST_TIMEOUT_MS = exports.INGEST_MAX_ATTEMPTS = exports.INGEST_STRICT_ATTEMPTS = void 0;
236
259
  exports.ingestFailureHint = ingestFailureHint;
237
260
  exports.isRetryableIngestStatus = isRetryableIngestStatus;
238
261
  exports.parseRetryAfterMs = parseRetryAfterMs;
@@ -247,10 +270,30 @@ var require_delivery = __commonJS({
247
270
  exports.INGEST_STRICT_ATTEMPTS = 1;
248
271
  exports.INGEST_MAX_ATTEMPTS = 3;
249
272
  exports.INGEST_REQUEST_TIMEOUT_MS = 1e4;
273
+ exports.AWAITED_INGEST_REQUEST_TIMEOUT_MS = 4e3;
274
+ exports.AWAITED_INGEST_TOTAL_TIMEOUT_MS = 1e4;
250
275
  exports.INGEST_RETRY_BASE_DELAY_MS = 500;
251
276
  exports.INGEST_RETRY_MAX_DELAY_MS = 2e3;
252
- function ingestFailureHint(status) {
277
+ var IngestError = class extends Error {
278
+ /** The HTTP status ingest answered with. */
279
+ status;
280
+ /** Whether resending the same payload can succeed (408, 429 and 5xx). */
281
+ retryable;
282
+ /** The response body, often JSON with a `detail` naming the problem. */
283
+ body;
284
+ constructor(status, body) {
285
+ super(`@uselemma/tracing: failed to ingest trace (${status})${body ? `: ${body}` : ""}`);
286
+ this.name = "IngestError";
287
+ this.status = status;
288
+ this.retryable = isRetryableIngestStatus(status);
289
+ this.body = body;
290
+ }
291
+ };
292
+ exports.IngestError = IngestError;
293
+ function ingestFailureHint(status, body) {
253
294
  switch (status) {
295
+ case 400:
296
+ return responseDetail(body) ?? "ingest rejected the payload as invalid";
254
297
  case 401:
255
298
  return "check LEMMA_API_KEY";
256
299
  case 403:
@@ -263,6 +306,15 @@ var require_delivery = __commonJS({
263
306
  return void 0;
264
307
  }
265
308
  }
309
+ function responseDetail(body) {
310
+ try {
311
+ const parsed = JSON.parse(body);
312
+ const detail = typeof parsed === "object" && parsed !== null && "detail" in parsed ? parsed.detail : void 0;
313
+ return typeof detail === "string" && detail ? detail : void 0;
314
+ } catch {
315
+ return void 0;
316
+ }
317
+ }
266
318
  function isRetryableIngestStatus(status) {
267
319
  return status === 408 || status === 429 || status >= 500;
268
320
  }
@@ -277,19 +329,34 @@ var require_delivery = __commonJS({
277
329
  const jittered = backoff / 2 + random() * (backoff / 2);
278
330
  return Math.min(exports.INGEST_RETRY_MAX_DELAY_MS, Math.max(jittered, retryAfterMs ?? 0));
279
331
  }
332
+ exports.AWAITED_DELIVERY = {
333
+ maxAttempts: exports.INGEST_MAX_ATTEMPTS,
334
+ requestTimeoutMs: exports.AWAITED_INGEST_REQUEST_TIMEOUT_MS,
335
+ totalTimeoutMs: exports.AWAITED_INGEST_TOTAL_TIMEOUT_MS
336
+ };
337
+ exports.BACKGROUND_DELIVERY = {
338
+ maxAttempts: exports.INGEST_MAX_ATTEMPTS,
339
+ requestTimeoutMs: exports.INGEST_REQUEST_TIMEOUT_MS,
340
+ totalTimeoutMs: Number.POSITIVE_INFINITY
341
+ };
342
+ exports.STRICT_DELIVERY = {
343
+ maxAttempts: exports.INGEST_STRICT_ATTEMPTS,
344
+ requestTimeoutMs: exports.INGEST_REQUEST_TIMEOUT_MS,
345
+ totalTimeoutMs: Number.POSITIVE_INFINITY
346
+ };
280
347
  function sleep(ms) {
281
348
  return new Promise((resolve2) => setTimeout(resolve2, ms));
282
349
  }
283
- async function withIngestTimeout(run) {
350
+ async function withIngestTimeout(run, timeoutMs = exports.INGEST_REQUEST_TIMEOUT_MS) {
284
351
  const controller = new AbortController();
285
352
  let timer;
286
353
  const timedOut = new Promise((_, reject) => {
287
354
  timer = setTimeout(() => {
288
- const error = new Error(`ingest request timed out after ${exports.INGEST_REQUEST_TIMEOUT_MS}ms`);
355
+ const error = new Error(`ingest request timed out after ${timeoutMs}ms`);
289
356
  error.name = "TimeoutError";
290
357
  controller.abort(error);
291
358
  reject(error);
292
- }, exports.INGEST_REQUEST_TIMEOUT_MS);
359
+ }, timeoutMs);
293
360
  });
294
361
  try {
295
362
  return await Promise.race([run(controller.signal), timedOut]);
@@ -300,21 +367,34 @@ var require_delivery = __commonJS({
300
367
  function failedBeforeSending(error) {
301
368
  return { ok: false, error, cause: `before sending: ${(0, error_message_1.describeError)(error)}` };
302
369
  }
303
- function failedAfter(attempts, attempt) {
370
+ function failedAfter(attempts, attempt, stop, totalTimeoutMs) {
371
+ const ceiling = stop === "ceiling" ? ` (${totalTimeoutMs}ms delivery ceiling reached)` : "";
304
372
  return {
305
373
  ok: false,
306
374
  error: attempt.error,
307
- cause: `after ${attempts} attempt${attempts === 1 ? "" : "s"}: ${attempt.reason}`
375
+ cause: `after ${attempts} attempt${attempts === 1 ? "" : "s"}: ${attempt.reason}${ceiling}`
308
376
  };
309
377
  }
310
- async function sendOnce(post, log) {
378
+ function stopReason(attempt, attempts, maxAttempts, timing) {
379
+ if (!attempt.retryable)
380
+ return "rejected";
381
+ const now = Date.now();
382
+ if (now >= timing.deadline)
383
+ return "ceiling";
384
+ if (attempts >= maxAttempts)
385
+ return "attempts";
386
+ if (now + timing.delayMs >= timing.deadline)
387
+ return "ceiling";
388
+ return void 0;
389
+ }
390
+ async function sendOnce(post, log, timeoutMs) {
311
391
  try {
312
392
  return await withIngestTimeout(async (signal) => {
313
393
  const response = await post(signal);
314
394
  if (response.ok)
315
395
  return { ok: true, response };
316
396
  const body = await response.text().catch(() => "");
317
- const hint = ingestFailureHint(response.status);
397
+ const hint = ingestFailureHint(response.status, body);
318
398
  (0, debug_mode_1.lemmaDebug)("client", "trace ingest failed", {
319
399
  ...log,
320
400
  status: response.status,
@@ -322,14 +402,15 @@ var require_delivery = __commonJS({
322
402
  ...(0, debug_delivery_1.pickResponseHeaders)(response.headers),
323
403
  ...hint ? { hint } : {}
324
404
  });
405
+ const error = new IngestError(response.status, body);
325
406
  return {
326
407
  ok: false,
327
- error: new Error(`@uselemma/tracing: failed to ingest trace (${response.status})${body ? `: ${body}` : ""}`),
408
+ error,
328
409
  reason: `ingest returned ${response.status}${hint ? ` (${hint})` : ""}`,
329
- retryable: isRetryableIngestStatus(response.status),
410
+ retryable: error.retryable,
330
411
  retryAfterMs: parseRetryAfterMs(response.headers.get("retry-after"))
331
412
  };
332
- });
413
+ }, timeoutMs);
333
414
  } catch (error) {
334
415
  (0, debug_mode_1.lemmaDebug)("client", "trace ingest failed", {
335
416
  ...log,
@@ -344,15 +425,21 @@ var require_delivery = __commonJS({
344
425
  };
345
426
  }
346
427
  }
347
- async function deliver(post, log, maxAttempts) {
428
+ async function deliver(post, log, budget) {
429
+ const { maxAttempts, requestTimeoutMs, totalTimeoutMs } = budget;
430
+ const deadline = Date.now() + totalTimeoutMs;
348
431
  for (let attempts = 1; ; attempts += 1) {
349
- const attempt = await sendOnce(post, log);
432
+ const timeoutMs = Math.min(requestTimeoutMs, deadline - Date.now());
433
+ const attempt = await sendOnce(post, log, timeoutMs);
350
434
  if (attempt.ok)
351
435
  return { ok: true, response: attempt.response };
352
- if (!attempt.retryable || attempts >= maxAttempts) {
353
- return failedAfter(attempts, attempt);
354
- }
355
436
  const delayMs = ingestRetryDelayMs(attempts, attempt.retryAfterMs);
437
+ const stop = stopReason(attempt, attempts, maxAttempts, {
438
+ deadline,
439
+ delayMs
440
+ });
441
+ if (stop)
442
+ return failedAfter(attempts, attempt, stop, totalTimeoutMs);
356
443
  (0, debug_mode_1.lemmaDebug)("client", "retrying trace ingest", {
357
444
  ...log,
358
445
  attempt: attempts,
@@ -426,6 +513,223 @@ var require_release = __commonJS({
426
513
  }
427
514
  });
428
515
 
516
+ // ../../packages/ts/tracing/dist/serialize.js
517
+ var require_serialize = __commonJS({
518
+ "../../packages/ts/tracing/dist/serialize.js"(exports) {
519
+ "use strict";
520
+ Object.defineProperty(exports, "__esModule", { value: true });
521
+ exports.TRACE_STRING_MAX_LENGTH = void 0;
522
+ exports.stringifyTraceJson = stringifyTraceJson;
523
+ function stringifyTraceJson(value) {
524
+ return JSON.stringify(toJsonSafe(value, "", []));
525
+ }
526
+ exports.TRACE_STRING_MAX_LENGTH = 65536;
527
+ function capString(value) {
528
+ if (value.length <= exports.TRACE_STRING_MAX_LENGTH)
529
+ return value;
530
+ let end = exports.TRACE_STRING_MAX_LENGTH;
531
+ const last = value.charCodeAt(end - 1);
532
+ if (last >= 55296 && last <= 56319)
533
+ end -= 1;
534
+ return `${value.slice(0, end)}\u2026[truncated ${value.length - end} chars]`;
535
+ }
536
+ function unserializable(value) {
537
+ return `[unserializable: ${typeName(value)}]`;
538
+ }
539
+ function typeName(value) {
540
+ try {
541
+ const name = value.constructor?.name;
542
+ return typeof name === "string" && name ? name : "Object";
543
+ } catch {
544
+ return "Object";
545
+ }
546
+ }
547
+ function binaryByteLength(value) {
548
+ if (value === null || typeof value !== "object")
549
+ return void 0;
550
+ if (ArrayBuffer.isView(value))
551
+ return value.byteLength;
552
+ const tag = Object.prototype.toString.call(value);
553
+ if (tag === "[object ArrayBuffer]" || tag === "[object SharedArrayBuffer]") {
554
+ const { byteLength } = value;
555
+ if (typeof byteLength === "number")
556
+ return byteLength;
557
+ }
558
+ if (typeof Blob !== "undefined" && value instanceof Blob)
559
+ return value.size;
560
+ return void 0;
561
+ }
562
+ function toJsonSafe(value, key, ancestors) {
563
+ let json;
564
+ try {
565
+ json = toJsonValue(value, key);
566
+ } catch {
567
+ return unserializable(value);
568
+ }
569
+ if (typeof json === "bigint")
570
+ return unserializable(json);
571
+ if (typeof json === "function" || typeof json === "symbol")
572
+ return void 0;
573
+ if (json === null || typeof json !== "object")
574
+ return json;
575
+ if (ancestors.includes(json))
576
+ return unserializable(json);
577
+ ancestors.push(json);
578
+ try {
579
+ return childrenToJsonSafe(json, ancestors);
580
+ } catch {
581
+ return unserializable(json);
582
+ } finally {
583
+ ancestors.pop();
584
+ }
585
+ }
586
+ function toJsonValue(value, key) {
587
+ if (value === null || typeof value !== "object" && typeof value !== "function" && typeof value !== "bigint") {
588
+ return compactLeaf(value);
589
+ }
590
+ if (binaryByteLength(value) !== void 0)
591
+ return compactLeaf(value);
592
+ const toJSON = value.toJSON;
593
+ const json = typeof toJSON === "function" ? toJSON.call(value, key) : value;
594
+ const unboxed = json instanceof Number || json instanceof String || json instanceof Boolean || json instanceof BigInt ? json.valueOf() : json;
595
+ return compactLeaf(unboxed);
596
+ }
597
+ function compactLeaf(value) {
598
+ if (typeof value === "string")
599
+ return capString(value);
600
+ const bytes = binaryByteLength(value);
601
+ return bytes === void 0 ? value : `[binary ${bytes} bytes]`;
602
+ }
603
+ function childrenToJsonSafe(json, ancestors) {
604
+ if (Array.isArray(json)) {
605
+ const items = [];
606
+ for (let index = 0; index < json.length; index += 1) {
607
+ items.push(toJsonSafe(json[index], String(index), ancestors));
608
+ }
609
+ return items;
610
+ }
611
+ const result = /* @__PURE__ */ Object.create(null);
612
+ for (const name of Object.keys(json)) {
613
+ result[name] = toJsonSafe(json[name], name, ancestors);
614
+ }
615
+ return result;
616
+ }
617
+ }
618
+ });
619
+
620
+ // ../../packages/ts/tracing/dist/stream-result.js
621
+ var require_stream_result = __commonJS({
622
+ "../../packages/ts/tracing/dist/stream-result.js"(exports) {
623
+ "use strict";
624
+ Object.defineProperty(exports, "__esModule", { value: true });
625
+ exports.wrapReturnedStream = wrapReturnedStream;
626
+ exports.holdTraceForStream = holdTraceForStream;
627
+ var debug_mode_1 = require_debug_mode();
628
+ function wrapReturnedStream(value) {
629
+ const kind = streamKind(value);
630
+ if (!kind)
631
+ return void 0;
632
+ let settle;
633
+ const ended = new Promise((resolve2) => {
634
+ settle = resolve2;
635
+ });
636
+ let finished = false;
637
+ const finish = (failure) => {
638
+ if (finished)
639
+ return;
640
+ finished = true;
641
+ settle(failure);
642
+ };
643
+ const stream = kind === "readable" ? readableEndingWith(value, finish) : iterate(value, finish);
644
+ return { stream, ended };
645
+ }
646
+ function holdTraceForStream(value, context, send) {
647
+ const wrapped = wrapReturnedStream(value);
648
+ if (!wrapped)
649
+ return void 0;
650
+ const sent = wrapped.ended.then((failure) => {
651
+ if (failure)
652
+ context.fail(failure.error);
653
+ return send();
654
+ });
655
+ (0, debug_mode_1.lemmaDebug)("client", "trace stays open until the returned stream ends", {
656
+ traceId: context.id
657
+ });
658
+ return { stream: wrapped.stream, sent };
659
+ }
660
+ function streamKind(value) {
661
+ if (typeof value !== "object" || value === null)
662
+ return void 0;
663
+ try {
664
+ if (typeof ReadableStream !== "undefined" && Object.getPrototypeOf(value) === ReadableStream.prototype && !value.locked) {
665
+ return "readable";
666
+ }
667
+ if (Object.prototype.toString.call(value) === "[object AsyncGenerator]") {
668
+ return "generator";
669
+ }
670
+ } catch {
671
+ }
672
+ return void 0;
673
+ }
674
+ function readableEndingWith(source, finish) {
675
+ const reader = source.getReader();
676
+ return new ReadableStream(
677
+ {
678
+ async pull(controller) {
679
+ const chunk = await reader.read().catch((error) => {
680
+ finish({ error });
681
+ throw error;
682
+ });
683
+ if (chunk.done) {
684
+ finish(void 0);
685
+ controller.close();
686
+ } else {
687
+ controller.enqueue(chunk.value);
688
+ }
689
+ },
690
+ async cancel(reason) {
691
+ finish(void 0);
692
+ await reader.cancel(reason);
693
+ }
694
+ },
695
+ // Reads from the source only when the caller reads.
696
+ { highWaterMark: 0 }
697
+ );
698
+ }
699
+ function iterate(source, finish) {
700
+ let started = false;
701
+ const wrapper = (async function* () {
702
+ started = true;
703
+ try {
704
+ return yield* source;
705
+ } catch (error) {
706
+ finish({ error });
707
+ throw error;
708
+ } finally {
709
+ finish(void 0);
710
+ }
711
+ })();
712
+ const close = wrapper.return;
713
+ const raise = wrapper.throw;
714
+ wrapper.return = async (value) => {
715
+ if (!started) {
716
+ finish(void 0);
717
+ await source.return(await value);
718
+ }
719
+ return close.call(wrapper, value);
720
+ };
721
+ wrapper.throw = async (error) => {
722
+ if (!started) {
723
+ finish({ error });
724
+ await source.return(void 0);
725
+ }
726
+ return raise.call(wrapper, error);
727
+ };
728
+ return wrapper;
729
+ }
730
+ }
731
+ });
732
+
429
733
  // ../../packages/ts/tracing/dist/usage.js
430
734
  var require_usage = __commonJS({
431
735
  "../../packages/ts/tracing/dist/usage.js"(exports) {
@@ -659,7 +963,7 @@ var require_version = __commonJS({
659
963
  "use strict";
660
964
  Object.defineProperty(exports, "__esModule", { value: true });
661
965
  exports.SDK_USER_AGENT = void 0;
662
- exports.SDK_USER_AGENT = "@uselemma/tracing/7.14.0";
966
+ exports.SDK_USER_AGENT = "@uselemma/tracing/7.15.0";
663
967
  }
664
968
  });
665
969
 
@@ -669,12 +973,16 @@ var require_client = __commonJS({
669
973
  "use strict";
670
974
  Object.defineProperty(exports, "__esModule", { value: true });
671
975
  exports.Lemma = exports.TraceHandle = exports.TraceContext = exports.NoopSpanHandle = exports.SpanHandle = exports.toWireTokenUsage = exports.normalizeTokenUsage = exports.attachResultUsage = void 0;
976
+ exports.startBackgroundTrace = startBackgroundTrace;
672
977
  var debug_delivery_1 = require_debug_delivery();
673
978
  var debug_mode_1 = require_debug_mode();
674
979
  var delivery_1 = require_delivery();
675
980
  var dropped_traces_1 = require_dropped_traces();
981
+ var env_1 = require_env();
676
982
  var error_message_1 = require_error_message();
677
983
  var release_1 = require_release();
984
+ var serialize_1 = require_serialize();
985
+ var stream_result_1 = require_stream_result();
678
986
  var usage_1 = require_usage();
679
987
  var version_1 = require_version();
680
988
  var usage_2 = require_usage();
@@ -733,11 +1041,7 @@ var require_client = __commonJS({
733
1041
  return value;
734
1042
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean")
735
1043
  return value;
736
- try {
737
- return JSON.stringify(value);
738
- } catch {
739
- return String(value);
740
- }
1044
+ return (0, serialize_1.stringifyTraceJson)(value);
741
1045
  }
742
1046
  function addDefined(attributes, key, value) {
743
1047
  if (value !== void 0)
@@ -840,6 +1144,12 @@ var require_client = __commonJS({
840
1144
  ...usage ? { usage } : {}
841
1145
  };
842
1146
  }
1147
+ function payloadBody(payload) {
1148
+ const body = (0, serialize_1.stringifyTraceJson)(payload);
1149
+ if (body === void 0)
1150
+ throw new Error("trace payload is empty");
1151
+ return body;
1152
+ }
843
1153
  function warnNoop(message) {
844
1154
  console.warn(`@uselemma/tracing: ${message}`);
845
1155
  }
@@ -891,6 +1201,17 @@ var require_client = __commonJS({
891
1201
  this.trace.spanEnded(this.payload);
892
1202
  this.trace.changed();
893
1203
  }
1204
+ /**
1205
+ * Close this span as failed if it is still open. A no-op once ended, so a
1206
+ * completed span is never rewritten. The end is never before the start.
1207
+ */
1208
+ failUnfinished(error, endedAt) {
1209
+ if (this.ended)
1210
+ return;
1211
+ const startedMs = timestampMs(this.payload.started_at);
1212
+ const closedAt = startedMs != null && startedMs > endedAt.getTime() ? new Date(startedMs) : endedAt;
1213
+ this.end({ status: "ERROR", error, endedAt: closedAt });
1214
+ }
894
1215
  /**
895
1216
  * Fill input or output after end() when a child model call finishes later.
896
1217
  * Input is written only while this span still has none. Output is replaced
@@ -985,6 +1306,8 @@ var require_client = __commonJS({
985
1306
  id = "";
986
1307
  end() {
987
1308
  }
1309
+ failUnfinished(_error, _endedAt) {
1310
+ }
988
1311
  ensureEndedAt(_endedAt) {
989
1312
  }
990
1313
  startSpan() {
@@ -1017,8 +1340,11 @@ var require_client = __commonJS({
1017
1340
  onChange;
1018
1341
  spans = [];
1019
1342
  spanHandles = /* @__PURE__ */ new Map();
1020
- traceOutput;
1343
+ /** Boxed, so an output set to undefined still counts as set. */
1344
+ rootOutput;
1021
1345
  traceError = null;
1346
+ /** Set by {@link markPayloadFinal}; cleared by the first change after it. */
1347
+ sent = false;
1022
1348
  id;
1023
1349
  constructor(options, onChange) {
1024
1350
  this.options = options;
@@ -1026,16 +1352,20 @@ var require_client = __commonJS({
1026
1352
  this.options.name ??= "trace";
1027
1353
  this.options.id ??= crypto.randomUUID();
1028
1354
  this.id = this.options.id;
1029
- this.traceOutput = options.output;
1355
+ this.rootOutput = options.output === void 0 ? void 0 : { value: options.output };
1030
1356
  }
1031
1357
  input(value) {
1032
1358
  this.options.input = value;
1033
1359
  this.changed();
1034
1360
  }
1035
1361
  output(value) {
1036
- this.traceOutput = value;
1362
+ this.rootOutput = { value };
1037
1363
  this.changed();
1038
1364
  }
1365
+ /** Whether the root output was set through options or `output()`. */
1366
+ get hasOutput() {
1367
+ return this.rootOutput !== void 0;
1368
+ }
1039
1369
  threadId(value) {
1040
1370
  this.options.threadId = value;
1041
1371
  this.changed();
@@ -1070,8 +1400,25 @@ var require_client = __commonJS({
1070
1400
  return this.spans.some((span) => span.id === id);
1071
1401
  }
1072
1402
  changed() {
1403
+ if (this.sent) {
1404
+ this.sent = false;
1405
+ (0, debug_mode_1.lemmaDebug)("client", "trace changed after its final payload was built; not delivered", {
1406
+ traceId: this.id
1407
+ });
1408
+ }
1073
1409
  this.onChange?.();
1074
1410
  }
1411
+ /**
1412
+ * Marks that this trace's payload won't be built again: an automatic send
1413
+ * builds it once and never rebuilds it, and a strict send can be retried
1414
+ * with a rebuilt payload until it succeeds. Debug mode then logs the first
1415
+ * later change, which isn't delivered.
1416
+ *
1417
+ * @internal
1418
+ */
1419
+ markPayloadFinal() {
1420
+ this.sent = true;
1421
+ }
1075
1422
  setChangeHandler(onChange) {
1076
1423
  this.onChange = onChange;
1077
1424
  }
@@ -1166,7 +1513,7 @@ var require_client = __commonJS({
1166
1513
  id: this.options.id,
1167
1514
  name: this.options.name ?? "trace",
1168
1515
  input: this.options.input,
1169
- output: this.traceOutput,
1516
+ output: this.rootOutput?.value,
1170
1517
  metadata: this.options.metadata,
1171
1518
  thread_id: this.options.threadId,
1172
1519
  user_id: this.options.userId,
@@ -1183,43 +1530,62 @@ var require_client = __commonJS({
1183
1530
  exports.TraceContext = TraceContext;
1184
1531
  var TraceHandle = class extends TraceContext {
1185
1532
  sendFn;
1186
- sendPromise = Promise.resolve();
1187
- ended = false;
1533
+ /** The send `end()` started; cleared when a strict send fails. */
1534
+ sending;
1535
+ /** Set by the first `end()`; a retry reuses its output and root timing. */
1536
+ rootTiming;
1188
1537
  startedAt;
1189
1538
  constructor(options, sendFn, startedAt) {
1190
1539
  super(options);
1191
1540
  this.sendFn = sendFn;
1192
1541
  this.startedAt = startedAt ?? coerceDate(options.startedAt) ?? /* @__PURE__ */ new Date();
1193
1542
  }
1194
- async end(outputOrOptions) {
1195
- if (this.ended)
1196
- return this.sendPromise;
1197
- let endedAtOverride;
1198
- let startedAtOverride;
1199
- if (isTraceEndOptions(outputOrOptions)) {
1200
- if ("output" in outputOrOptions) {
1201
- this.output(outputOrOptions.output);
1202
- }
1203
- if (outputOrOptions.durationMs != null) {
1204
- this.duration(outputOrOptions.durationMs);
1205
- }
1206
- startedAtOverride = coerceDate(outputOrOptions.startedAt);
1207
- endedAtOverride = coerceDate(outputOrOptions.endedAt);
1208
- } else if (arguments.length > 0) {
1209
- this.output(outputOrOptions);
1543
+ end(outputOrOptions) {
1544
+ if (this.sending)
1545
+ return this.sending;
1546
+ this.rootTiming ??= this.applyEnd(outputOrOptions, arguments.length > 0);
1547
+ const { startedAt, endedAt } = this.rootTiming;
1548
+ const sending = this.startSend(startedAt, endedAt);
1549
+ this.sending = sending;
1550
+ sending.catch(() => {
1551
+ this.sending = void 0;
1552
+ });
1553
+ return sending;
1554
+ }
1555
+ /** Apply the first `end()`'s output and duration, and fix the root timing. */
1556
+ applyEnd(outputOrOptions, hasArgument) {
1557
+ if (!isTraceEndOptions(outputOrOptions)) {
1558
+ if (hasArgument)
1559
+ this.output(outputOrOptions);
1560
+ return { startedAt: this.startedAt, endedAt: /* @__PURE__ */ new Date() };
1210
1561
  }
1211
- this.ended = true;
1212
- const startedAt = startedAtOverride ?? this.startedAt;
1213
- const endedAt = endedAtOverride ?? /* @__PURE__ */ new Date();
1214
- this.sendPromise = this.sendPromise.then(() => this.sendFn(this, startedAt, endedAt));
1215
- await this.sendPromise;
1562
+ if ("output" in outputOrOptions)
1563
+ this.output(outputOrOptions.output);
1564
+ if (outputOrOptions.durationMs != null) {
1565
+ this.duration(outputOrOptions.durationMs);
1566
+ }
1567
+ return {
1568
+ startedAt: coerceDate(outputOrOptions.startedAt) ?? this.startedAt,
1569
+ endedAt: coerceDate(outputOrOptions.endedAt) ?? /* @__PURE__ */ new Date()
1570
+ };
1216
1571
  }
1217
- /** Whether this trace has already been delivered via `end()`. */
1572
+ /** A sendFn that throws synchronously rejects instead of throwing. */
1573
+ startSend(startedAt, endedAt) {
1574
+ try {
1575
+ return this.sendFn(this, startedAt, endedAt);
1576
+ } catch (error) {
1577
+ return Promise.reject(error);
1578
+ }
1579
+ }
1580
+ /** Whether `end()` has sent this trace, or is sending it. */
1218
1581
  get isEnded() {
1219
- return this.ended;
1582
+ return this.sending !== void 0;
1220
1583
  }
1221
1584
  };
1222
1585
  exports.TraceHandle = TraceHandle;
1586
+ function startBackgroundTrace(lemma, options) {
1587
+ return lemma.startTrace(options, delivery_1.BACKGROUND_DELIVERY);
1588
+ }
1223
1589
  var Lemma2 = class {
1224
1590
  apiKey;
1225
1591
  projectId;
@@ -1229,17 +1595,20 @@ var require_client = __commonJS({
1229
1595
  baseHeaders;
1230
1596
  release;
1231
1597
  traces = /* @__PURE__ */ new Map();
1598
+ /** Sends in flight, and callback traces held open by a returned stream. */
1599
+ pending = /* @__PURE__ */ new Set();
1232
1600
  configLogged = false;
1233
1601
  constructor(options = {}) {
1234
- this.apiKey = required(options.apiKey ?? process.env.LEMMA_API_KEY, "LEMMA_API_KEY");
1235
- this.projectId = required(options.projectId ?? process.env.LEMMA_PROJECT_ID, "LEMMA_PROJECT_ID");
1236
- this.baseUrl = (options.baseUrl ?? (process.env.LEMMA_BASE_URL?.trim() || debug_delivery_1.PRODUCTION_BASE_URL)).replace(/\/+$/, "");
1237
- this.fetchImpl = options.fetch ?? fetch;
1602
+ this.apiKey = required(options.apiKey ?? (0, env_1.readEnv)(() => process.env.LEMMA_API_KEY), "LEMMA_API_KEY");
1603
+ this.projectId = required(options.projectId ?? (0, env_1.readEnv)(() => process.env.LEMMA_PROJECT_ID), "LEMMA_PROJECT_ID");
1604
+ this.baseUrl = (options.baseUrl ?? ((0, env_1.readEnv)(() => process.env.LEMMA_BASE_URL)?.trim() || debug_delivery_1.PRODUCTION_BASE_URL)).replace(/\/+$/, "");
1605
+ const customFetch = options.fetch;
1606
+ this.fetchImpl = (input, init) => (customFetch ?? fetch)(input, init);
1238
1607
  this.baseHeaders = {
1239
1608
  "User-Agent": options.userAgent ?? version_1.SDK_USER_AGENT,
1240
1609
  Authorization: `Bearer ${this.apiKey}`
1241
1610
  };
1242
- this.release = (0, release_1.normalizeRelease)(options.release ?? process.env.LEMMA_RELEASE);
1611
+ this.release = (0, release_1.normalizeRelease)(options.release ?? (0, env_1.readEnv)(() => process.env.LEMMA_RELEASE));
1243
1612
  this.logInitConfigOnce();
1244
1613
  }
1245
1614
  /**
@@ -1266,7 +1635,7 @@ var require_client = __commonJS({
1266
1635
  context.output("ok");
1267
1636
  const startedAt = /* @__PURE__ */ new Date();
1268
1637
  const payload = this.stampRelease(context.toPayload(this.projectId, startedAt, /* @__PURE__ */ new Date()));
1269
- const body = JSON.stringify(payload);
1638
+ const body = payloadBody(payload);
1270
1639
  const url = `${this.baseUrl}${debug_delivery_1.INGEST_PATH}`;
1271
1640
  let response;
1272
1641
  try {
@@ -1283,7 +1652,8 @@ var require_client = __commonJS({
1283
1652
  const ingestWarnings = [];
1284
1653
  if (response.status !== debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS) {
1285
1654
  ingestWarnings.push(`expected status ${debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS}, got ${response.status}`);
1286
- const hint = (0, delivery_1.ingestFailureHint)(response.status);
1655
+ const failureBody = await (0, delivery_1.withIngestTimeout)(() => response.text()).catch(() => "");
1656
+ const hint = (0, delivery_1.ingestFailureHint)(response.status, failureBody);
1287
1657
  if (hint)
1288
1658
  hints.push(hint);
1289
1659
  }
@@ -1323,21 +1693,8 @@ var require_client = __commonJS({
1323
1693
  }
1324
1694
  trace(options = {}, fn) {
1325
1695
  const traceOptions = typeof options === "string" ? { name: options } : options;
1326
- if (!fn) {
1327
- const handle = new TraceHandle(traceOptions, async (trace, startedAt2, endedAt) => {
1328
- try {
1329
- await this.flushTraceAutomatic(trace, startedAt2, endedAt);
1330
- } finally {
1331
- this.traces.delete(trace.id);
1332
- }
1333
- });
1334
- this.traces.set(handle.id, handle);
1335
- (0, debug_mode_1.lemmaDebug)("client", "trace handle created", {
1336
- traceId: handle.id,
1337
- name: traceOptions.name ?? "trace"
1338
- });
1339
- return handle;
1340
- }
1696
+ if (!fn)
1697
+ return this.startTrace(traceOptions, delivery_1.AWAITED_DELIVERY);
1341
1698
  const context = new TraceContext(traceOptions);
1342
1699
  const startedAt = /* @__PURE__ */ new Date();
1343
1700
  (0, debug_mode_1.lemmaDebug)("client", "trace started", {
@@ -1350,16 +1707,63 @@ var require_client = __commonJS({
1350
1707
  result = await fn(context);
1351
1708
  } catch (error) {
1352
1709
  context.fail(error);
1353
- await this.flushTraceAutomatic(context, startedAt, /* @__PURE__ */ new Date());
1710
+ await this.flushTraceAutomatic(context, startedAt, /* @__PURE__ */ new Date(), delivery_1.AWAITED_DELIVERY);
1354
1711
  throw error;
1355
1712
  }
1356
- if (traceOptions.output === void 0) {
1713
+ const held = (0, stream_result_1.holdTraceForStream)(result, context, () => this.flushTraceAutomatic(context, startedAt, /* @__PURE__ */ new Date(), delivery_1.BACKGROUND_DELIVERY));
1714
+ if (held) {
1715
+ this.track(held.sent);
1716
+ return held.stream;
1717
+ }
1718
+ if (!context.hasOutput) {
1357
1719
  context.output(result);
1358
1720
  }
1359
- await this.flushTraceAutomatic(context, startedAt, /* @__PURE__ */ new Date());
1721
+ await this.flushTraceAutomatic(context, startedAt, /* @__PURE__ */ new Date(), delivery_1.AWAITED_DELIVERY);
1360
1722
  return result;
1361
1723
  })();
1362
1724
  }
1725
+ /**
1726
+ * Wait until every trace this client has started sending is delivered or
1727
+ * dropped, including each callback trace whose returned stream is still
1728
+ * being read. Never rejects. A trace handle that hasn't been ended yet is
1729
+ * not waited for.
1730
+ *
1731
+ * Pass it to the runtime so delivery outlives the response:
1732
+ * `ctx.waitUntil(lemma.flush())` on Cloudflare Workers,
1733
+ * `after(() => lemma.flush())` in Next.js. On AWS Lambda, await it before
1734
+ * the handler returns.
1735
+ */
1736
+ async flush() {
1737
+ await Promise.allSettled(Array.from(this.pending));
1738
+ }
1739
+ track(promise) {
1740
+ this.pending.add(promise);
1741
+ const forget = () => this.pending.delete(promise);
1742
+ promise.then(forget, forget);
1743
+ return promise;
1744
+ }
1745
+ /**
1746
+ * A trace handle whose `end()` delivers within `budget`. A caller's
1747
+ * `lemma.trace()` handle uses `AWAITED_DELIVERY`; `startBackgroundTrace()`
1748
+ * uses `BACKGROUND_DELIVERY`.
1749
+ *
1750
+ * @internal
1751
+ */
1752
+ startTrace(options, budget) {
1753
+ const handle = new TraceHandle(options, async (trace, startedAt, endedAt) => {
1754
+ try {
1755
+ await this.flushTraceAutomatic(trace, startedAt, endedAt, budget);
1756
+ } finally {
1757
+ this.traces.delete(trace.id);
1758
+ }
1759
+ });
1760
+ this.traces.set(handle.id, handle);
1761
+ (0, debug_mode_1.lemmaDebug)("client", "trace handle created", {
1762
+ traceId: handle.id,
1763
+ name: options.name ?? "trace"
1764
+ });
1765
+ return handle;
1766
+ }
1363
1767
  /**
1364
1768
  * Deliver a trace you assembled yourself, in a single request.
1365
1769
  *
@@ -1375,13 +1779,15 @@ var require_client = __commonJS({
1375
1779
  * fields do not preserve prior values, and after Lemma processes the trace
1376
1780
  * once, a later re-delivery does not re-run issue extraction (late new span
1377
1781
  * IDs may still append for display). Retries of the same complete payload are
1378
- * safe: already-stored span IDs are skipped. Throws on a non-2xx response and
1379
- * never mutates the trace's status, so a failed send can be retried as-is.
1782
+ * safe: already-stored span IDs are skipped. Throws an `IngestError` on
1783
+ * a non-2xx response, and never mutates the trace's status, so a failed send
1784
+ * can be retried as-is.
1380
1785
  */
1381
1786
  async ingest(context, options) {
1382
- const failure = await this.sendTrace(context, options.startedAt, options.endedAt ?? /* @__PURE__ */ new Date(), delivery_1.INGEST_STRICT_ATTEMPTS);
1787
+ const failure = await this.sendTrace(context, options.startedAt, options.endedAt ?? /* @__PURE__ */ new Date(), delivery_1.STRICT_DELIVERY);
1383
1788
  if (failure)
1384
1789
  throw failure.error;
1790
+ context.markPayloadFinal();
1385
1791
  }
1386
1792
  recordSpan(options) {
1387
1793
  const context = this.detachedTraceFor(options.traceId, "span");
@@ -1576,21 +1982,27 @@ var require_client = __commonJS({
1576
1982
  * {@link Lemma.ingest} sends once and throws, because queue/plugin producers
1577
1983
  * keep their own retry backlog.
1578
1984
  */
1579
- async flushTraceAutomatic(context, startedAt, endedAt) {
1580
- const failure = await this.sendTrace(context, startedAt, endedAt, delivery_1.INGEST_MAX_ATTEMPTS);
1985
+ async flushTraceAutomatic(context, startedAt, endedAt, budget) {
1986
+ const sending = this.sendTrace(context, startedAt, endedAt, budget);
1987
+ context.markPayloadFinal();
1988
+ const failure = await sending;
1581
1989
  if (failure)
1582
1990
  (0, dropped_traces_1.reportDroppedTrace)(context.id, failure.cause);
1583
1991
  }
1992
+ /** {@link Lemma.buildAndSend}, tracked so `flush()` waits for it. */
1993
+ sendTrace(context, startedAt, endedAt, budget) {
1994
+ return this.track(this.buildAndSend(context, startedAt, endedAt, budget));
1995
+ }
1584
1996
  /**
1585
1997
  * Build, send, and check one trace; undefined when it was delivered. A
1586
1998
  * payload that cannot be built comes back as a failure, so strict and
1587
1999
  * automatic delivery handle it once.
1588
2000
  */
1589
- async sendTrace(context, startedAt, endedAt, maxAttempts) {
2001
+ async buildAndSend(context, startedAt, endedAt, budget) {
1590
2002
  const built = this.buildIngestBody(context, startedAt, endedAt);
1591
2003
  if (!built.ok)
1592
2004
  return built;
1593
- const result = await (0, delivery_1.deliver)((signal) => this.postIngest(built.body, signal), { traceId: context.id, projectId: this.projectId }, maxAttempts);
2005
+ const result = await (0, delivery_1.deliver)((signal) => this.postIngest(built.body, signal), { traceId: context.id, projectId: this.projectId }, budget);
1594
2006
  if (!result.ok)
1595
2007
  return result;
1596
2008
  try {
@@ -1607,7 +2019,7 @@ var require_client = __commonJS({
1607
2019
  buildIngestBody(context, startedAt, endedAt) {
1608
2020
  try {
1609
2021
  const payload = this.stampRelease(context.toPayload(this.projectId, startedAt, endedAt));
1610
- const body = JSON.stringify(payload);
2022
+ const body = payloadBody(payload);
1611
2023
  (0, debug_mode_1.lemmaDebug)("client", "sending trace", {
1612
2024
  traceId: payload.trace.id,
1613
2025
  name: payload.trace.name,
@@ -1968,6 +2380,7 @@ var require_coding_agent = __commonJS({
1968
2380
  exports.startCodingAgentTurn = startCodingAgentTurn2;
1969
2381
  exports.recordCodingAgentToolStart = recordCodingAgentToolStart2;
1970
2382
  exports.recordCodingAgentToolResult = recordCodingAgentToolResult2;
2383
+ exports.reopenCodingAgentTurn = reopenCodingAgentTurn;
1971
2384
  exports.completeCodingAgentTurn = completeCodingAgentTurn2;
1972
2385
  exports.codingAgentTurnTrace = codingAgentTurnTrace2;
1973
2386
  var node_crypto_1 = __require("node:crypto");
@@ -2062,6 +2475,35 @@ var require_coding_agent = __commonJS({
2062
2475
  tools[existingIndex] = completed;
2063
2476
  return { ...open, tools };
2064
2477
  }
2478
+ function reopenCodingAgentTurn(turn) {
2479
+ if (turn.status === "open")
2480
+ return turn;
2481
+ const response = {
2482
+ generationId: turn.generationId,
2483
+ response: turn.response,
2484
+ model: turn.model,
2485
+ provider: turn.provider,
2486
+ generationStartedAt: turn.generationStartedAt,
2487
+ generationEndedAt: turn.generationEndedAt
2488
+ };
2489
+ const earlierResponses = [...turn.earlierResponses ?? [], response];
2490
+ const base = {
2491
+ version: turn.version,
2492
+ harness: turn.harness,
2493
+ sessionId: turn.sessionId,
2494
+ turnId: turn.turnId,
2495
+ traceId: turn.traceId,
2496
+ generationId: deterministicUuid(`lemma-coding-agent-continuation\0${turn.traceId}\0${earlierResponses.length}`),
2497
+ prompt: turn.prompt,
2498
+ model: turn.model,
2499
+ provider: turn.provider,
2500
+ metadata: turn.metadata,
2501
+ startedAt: turn.startedAt,
2502
+ tools: turn.tools.map(({ resultMissing: _resultMissing, ...tool }) => tool),
2503
+ earlierResponses
2504
+ };
2505
+ return { ...base, status: "open" };
2506
+ }
2065
2507
  function completeCodingAgentTurn2(turn, event) {
2066
2508
  if (turn.status === "completed")
2067
2509
  return turn;
@@ -2120,21 +2562,23 @@ var require_coding_agent = __commonJS({
2120
2562
  }
2121
2563
  });
2122
2564
  }
2123
- const generationTimingMissing = turn.generationStartedAt === void 0;
2124
- context.recordGeneration({
2125
- id: turn.generationId,
2126
- name: `${turn.harness} response`,
2127
- input: turn.prompt,
2128
- output: turn.response,
2129
- model: turn.model,
2130
- llmProvider: turn.provider,
2131
- llmInputMessages: [{ role: "user", content: turn.prompt }],
2132
- llmOutputMessages: [{ role: "assistant", content: turn.response }],
2133
- startedAt: turn.generationStartedAt ?? null,
2134
- endedAt: turn.generationEndedAt ?? null,
2135
- attributes,
2136
- metadata: generationTimingMissing ? { timing_missing: true } : void 0
2137
- });
2565
+ for (const response of [...turn.earlierResponses ?? [], turn]) {
2566
+ const timingMissing = response.generationStartedAt === void 0;
2567
+ context.recordGeneration({
2568
+ id: response.generationId,
2569
+ name: `${turn.harness} response`,
2570
+ input: turn.prompt,
2571
+ output: response.response,
2572
+ model: response.model,
2573
+ llmProvider: response.provider,
2574
+ llmInputMessages: [{ role: "user", content: turn.prompt }],
2575
+ llmOutputMessages: [{ role: "assistant", content: response.response }],
2576
+ startedAt: response.generationStartedAt ?? null,
2577
+ endedAt: response.generationEndedAt ?? null,
2578
+ attributes,
2579
+ metadata: timingMissing ? { timing_missing: true } : void 0
2580
+ });
2581
+ }
2138
2582
  return {
2139
2583
  context,
2140
2584
  startedAt: turn.startedAt,
@@ -2144,6 +2588,74 @@ var require_coding_agent = __commonJS({
2144
2588
  }
2145
2589
  });
2146
2590
 
2591
+ // ../../packages/ts/tracing/dist/langchain-context.js
2592
+ var require_langchain_context = __commonJS({
2593
+ "../../packages/ts/tracing/dist/langchain-context.js"(exports) {
2594
+ "use strict";
2595
+ Object.defineProperty(exports, "__esModule", { value: true });
2596
+ exports.ensureLangChainAsyncContext = ensureLangChainAsyncContext;
2597
+ var LANGCHAIN_ASYNC_LOCAL_STORAGE = Symbol.for("ls:tracing_async_local_storage");
2598
+ function ensureLangChainAsyncContext() {
2599
+ const runtime = globalThis;
2600
+ if (runtime[LANGCHAIN_ASYNC_LOCAL_STORAGE] !== void 0)
2601
+ return;
2602
+ const Storage = runtime.AsyncLocalStorage ?? runtime.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage;
2603
+ if (Storage)
2604
+ runtime[LANGCHAIN_ASYNC_LOCAL_STORAGE] = new Storage();
2605
+ }
2606
+ }
2607
+ });
2608
+
2609
+ // ../../packages/ts/tracing/dist/langchain-eviction.js
2610
+ var require_langchain_eviction = __commonJS({
2611
+ "../../packages/ts/tracing/dist/langchain-eviction.js"(exports) {
2612
+ "use strict";
2613
+ Object.defineProperty(exports, "__esModule", { value: true });
2614
+ exports.IdleTraceSweeper = void 0;
2615
+ var DEFAULT_OPEN_TRACE_TTL_MS = 2 * 60 * 60 * 1e3;
2616
+ var DEFAULT_EVICTION_INTERVAL_MS = 5 * 60 * 1e3;
2617
+ var IdleTraceSweeper = class {
2618
+ ttlMs;
2619
+ intervalMs;
2620
+ lastSweepAt = Number.NEGATIVE_INFINITY;
2621
+ constructor({ openTraceTtlMs = DEFAULT_OPEN_TRACE_TTL_MS, evictionIntervalMs = DEFAULT_EVICTION_INTERVAL_MS }) {
2622
+ this.ttlMs = openTraceTtlMs;
2623
+ this.intervalMs = evictionIntervalMs;
2624
+ }
2625
+ /**
2626
+ * Pass each open trace idle past the TTL to `evict`, with one warning that
2627
+ * lists their root run IDs. Runs at most once per interval.
2628
+ */
2629
+ sweep(traces, runs, evict) {
2630
+ if (this.ttlMs === null)
2631
+ return;
2632
+ const now = Date.now();
2633
+ if (now - this.lastSweepAt < this.intervalMs)
2634
+ return;
2635
+ this.lastSweepAt = now;
2636
+ const latestRunStart = /* @__PURE__ */ new Map();
2637
+ for (const run of runs) {
2638
+ const startedAt = run.startedAt.getTime();
2639
+ const seen = latestRunStart.get(run.owningTraceId) ?? 0;
2640
+ if (startedAt > seen)
2641
+ latestRunStart.set(run.owningTraceId, startedAt);
2642
+ }
2643
+ const cutoff = now - this.ttlMs;
2644
+ const stale = Array.from(traces).filter(([id, trace]) => {
2645
+ const lastActivity = Math.max(trace.openedAt.getTime(), trace.latestEnd?.getTime() ?? 0, latestRunStart.get(id) ?? 0);
2646
+ return !trace.ended && lastActivity < cutoff;
2647
+ });
2648
+ if (stale.length === 0)
2649
+ return;
2650
+ console.warn(`@uselemma/tracing: evicting ${stale.length} stale LangChain trace(s) that never received an end event (openTraceTtlMs=${this.ttlMs}); root run IDs: ${stale.map(([id]) => id).join(", ")}`);
2651
+ for (const [rootRunId, trace] of stale)
2652
+ evict(rootRunId, trace);
2653
+ }
2654
+ };
2655
+ exports.IdleTraceSweeper = IdleTraceSweeper;
2656
+ }
2657
+ });
2658
+
2147
2659
  // ../../packages/ts/tracing/dist/schedule.js
2148
2660
  var require_schedule = __commonJS({
2149
2661
  "../../packages/ts/tracing/dist/schedule.js"(exports) {
@@ -2427,6 +2939,8 @@ var require_langchain = __commonJS({
2427
2939
  exports.langGraph = langGraph;
2428
2940
  var client_1 = require_client();
2429
2941
  var error_message_1 = require_error_message();
2942
+ var langchain_context_1 = require_langchain_context();
2943
+ var langchain_eviction_1 = require_langchain_eviction();
2430
2944
  var schedule_1 = require_schedule();
2431
2945
  var tool_result_1 = require_tool_result();
2432
2946
  var model_1 = require_model();
@@ -2815,20 +3329,6 @@ var require_langchain = __commonJS({
2815
3329
  }
2816
3330
  return messages.length ? messages : void 0;
2817
3331
  }
2818
- function hasToolCalls(output) {
2819
- if (!output || typeof output !== "object")
2820
- return false;
2821
- if (Array.isArray(output))
2822
- return output.some((item) => hasToolCalls(item));
2823
- const record = output;
2824
- if (Array.isArray(record.tool_calls) && record.tool_calls.length > 0) {
2825
- return true;
2826
- }
2827
- if (Array.isArray(record.toolCalls) && record.toolCalls.length > 0) {
2828
- return true;
2829
- }
2830
- return false;
2831
- }
2832
3332
  function providerFromId(id) {
2833
3333
  if (!Array.isArray(id))
2834
3334
  return void 0;
@@ -2968,13 +3468,23 @@ var require_langchain = __commonJS({
2968
3468
  ignore_chain = false;
2969
3469
  ignore_agent = false;
2970
3470
  ignore_retriever = false;
3471
+ /**
3472
+ * Callbacks only record in memory and schedule delivery, so LangChain runs
3473
+ * them inline instead of on its process-wide callback queue (concurrency 1).
3474
+ * A root's end callback has therefore run before `invoke()` resolves, and
3475
+ * `flush()` sees its send.
3476
+ */
3477
+ awaitHandlers = true;
2971
3478
  lemma;
2972
3479
  runs = /* @__PURE__ */ new Map();
2973
3480
  traces = /* @__PURE__ */ new Map();
2974
3481
  pending = /* @__PURE__ */ new Set();
3482
+ idleTraces;
2975
3483
  constructor(options = {}) {
2976
3484
  this.options = options;
3485
+ (0, langchain_context_1.ensureLangChainAsyncContext)();
2977
3486
  this.lemma = options.lemma;
3487
+ this.idleTraces = new langchain_eviction_1.IdleTraceSweeper(options);
2978
3488
  }
2979
3489
  getLemma() {
2980
3490
  this.lemma ??= new client_1.Lemma({
@@ -3043,7 +3553,7 @@ var require_langchain = __commonJS({
3043
3553
  }
3044
3554
  createOwnedTrace(runId, name, input, kind, metadata, tags) {
3045
3555
  const startedAt = /* @__PURE__ */ new Date();
3046
- const handle = this.getLemma().trace({
3556
+ const handle = (0, client_1.startBackgroundTrace)(this.getLemma(), {
3047
3557
  name,
3048
3558
  input: rootTraceInput(input),
3049
3559
  metadata: {
@@ -3134,8 +3644,14 @@ var require_langchain = __commonJS({
3134
3644
  });
3135
3645
  }
3136
3646
  async finalizeTrace(owningTraceId, stored) {
3137
- this.traces.delete(owningTraceId);
3138
- this.forgetTraceRuns(owningTraceId);
3647
+ const ownsRuns = this.traces.get(owningTraceId) === stored;
3648
+ if (ownsRuns)
3649
+ this.traces.delete(owningTraceId);
3650
+ if (!stored.ended && ownsRuns) {
3651
+ (0, error_message_1.failOpenGenerations)([...this.runs.values()].filter((run) => run.owningTraceId === owningTraceId && run.kind === "llm").map((run) => run.handle), stored.rootError, stored.latestEnd ?? /* @__PURE__ */ new Date());
3652
+ }
3653
+ if (ownsRuns)
3654
+ this.forgetTraceRuns(owningTraceId);
3139
3655
  if (stored.ended)
3140
3656
  return;
3141
3657
  stored.ended = true;
@@ -3146,40 +3662,36 @@ var require_langchain = __commonJS({
3146
3662
  endedAt,
3147
3663
  durationMs: durationMs(startedAt, endedAt)
3148
3664
  };
3149
- if (stored.rootError) {
3665
+ if (stored.rootError)
3150
3666
  stored.handle.fail(stored.rootError);
3151
- const promise2 = stored.handle.end(timing);
3152
- this.trackPending(promise2);
3153
- await promise2;
3154
- return;
3155
- }
3156
- if (stored.rootOutput === void 0) {
3157
- const promise2 = stored.handle.end(timing);
3158
- this.trackPending(promise2);
3159
- await promise2;
3160
- return;
3161
- }
3162
- const promise = stored.handle.end({
3163
- output: stored.rootOutput,
3164
- ...timing
3667
+ const output = stored.rootError ? void 0 : stored.rootOutput;
3668
+ const sent = stored.handle.end(output === void 0 ? timing : { output, ...timing });
3669
+ this.trackPending(sent);
3670
+ await sent;
3671
+ }
3672
+ /** Send the partial trace of each root idle past `openTraceTtlMs`, and forget it. */
3673
+ evictIdleTraces() {
3674
+ this.idleTraces.sweep(this.traces, this.runs.values(), (rootRunId, stored) => {
3675
+ void this.finalizeTrace(rootRunId, stored);
3165
3676
  });
3166
- this.trackPending(promise);
3167
- await promise;
3168
3677
  }
3169
- maybeFinalizeOwner(run, endedAt) {
3678
+ /**
3679
+ * Send an owner's trace on a later macrotask and track it in `pending`.
3680
+ * Callbacks never await delivery, and recordResult(invoke return) can still
3681
+ * stamp usage onto generations whose callback event omitted it.
3682
+ */
3683
+ maybeFinalizeOwner(run) {
3170
3684
  if (!run.ownsTrace)
3171
3685
  return;
3172
3686
  const stored = this.traces.get(run.owningTraceId);
3173
3687
  if (!stored || stored.ended)
3174
3688
  return;
3175
- this.noteBounds(stored, run.startedAt, endedAt);
3176
3689
  const promise = new Promise((resolve2, reject) => {
3177
3690
  (0, schedule_1.scheduleMacrotask)(() => {
3178
3691
  this.finalizeTrace(run.owningTraceId, stored).then(resolve2, reject);
3179
3692
  });
3180
3693
  });
3181
3694
  this.trackPending(promise);
3182
- return promise;
3183
3695
  }
3184
3696
  /**
3185
3697
  * Copy token usage from an `invoke` / chain result onto generation spans
@@ -3198,6 +3710,7 @@ var require_langchain = __commonJS({
3198
3710
  return this.options.agentName ?? serializedName(serialized, fallback);
3199
3711
  }
3200
3712
  handleChainStart(serialized, inputs, runId, parentRunId, tags, metadata, runType, name) {
3713
+ this.evictIdleTraces();
3201
3714
  const startedAt = /* @__PURE__ */ new Date();
3202
3715
  const chainName = name ?? serializedName(serialized, "langchain-chain");
3203
3716
  const parent = this.parentRun(parentRunId);
@@ -3230,7 +3743,7 @@ var require_langchain = __commonJS({
3230
3743
  ownsTrace: false
3231
3744
  });
3232
3745
  }
3233
- async handleChainEnd(outputs, runId) {
3746
+ handleChainEnd(outputs, runId) {
3234
3747
  const run = this.runs.get(runId);
3235
3748
  if (!run)
3236
3749
  return;
@@ -3248,11 +3761,9 @@ var require_langchain = __commonJS({
3248
3761
  }
3249
3762
  }
3250
3763
  this.runs.delete(runId);
3251
- if (run.ownsTrace && stored) {
3252
- await this.finalizeTrace(run.owningTraceId, stored);
3253
- }
3764
+ this.maybeFinalizeOwner(run);
3254
3765
  }
3255
- async handleChainError(error, runId) {
3766
+ handleChainError(error, runId) {
3256
3767
  const run = this.runs.get(runId);
3257
3768
  if (!run)
3258
3769
  return;
@@ -3272,11 +3783,10 @@ var require_langchain = __commonJS({
3272
3783
  }
3273
3784
  }
3274
3785
  this.runs.delete(runId);
3275
- if (run.ownsTrace && stored) {
3276
- await this.finalizeTrace(run.owningTraceId, stored);
3277
- }
3786
+ this.maybeFinalizeOwner(run);
3278
3787
  }
3279
3788
  handleLLMStart(serialized, prompts, runId, parentRunId, extraParams, tags, metadata, _runName) {
3789
+ this.evictIdleTraces();
3280
3790
  const startedAt = /* @__PURE__ */ new Date();
3281
3791
  const attachment = this.resolveAttachment(runId, parentRunId, () => this.createOwnedTrace(runId, this.traceName(serialized, "langchain-llm"), prompts, "llm", metadata, tags));
3282
3792
  if (attachment.ownsTrace) {
@@ -3308,6 +3818,7 @@ var require_langchain = __commonJS({
3308
3818
  });
3309
3819
  }
3310
3820
  handleChatModelStart(serialized, messages, runId, parentRunId, extraParams, tags, metadata, _runName) {
3821
+ this.evictIdleTraces();
3311
3822
  const startedAt = /* @__PURE__ */ new Date();
3312
3823
  const flatMessages = messages.flat();
3313
3824
  const normalized = normalizeMessages(flatMessages);
@@ -3340,15 +3851,7 @@ var require_langchain = __commonJS({
3340
3851
  ownsTrace: attachment.ownsTrace
3341
3852
  });
3342
3853
  }
3343
- deferredOwnerFor(owningTraceId) {
3344
- for (const run of this.runs.values()) {
3345
- if (run.ownsTrace && run.deferFinalize && run.owningTraceId === owningTraceId) {
3346
- return run;
3347
- }
3348
- }
3349
- return void 0;
3350
- }
3351
- async handleLLMEnd(output, runId) {
3854
+ handleLLMEnd(output, runId) {
3352
3855
  const run = this.runs.get(runId);
3353
3856
  if (!run?.handle)
3354
3857
  return;
@@ -3356,7 +3859,6 @@ var require_langchain = __commonJS({
3356
3859
  const structured = llmStructuredOutput(output);
3357
3860
  const outputMessages = llmOutputMessages(output);
3358
3861
  const softError = (0, tool_result_1.toolResultError)(structured);
3359
- const awaitingTools = !softError && hasToolCalls(structured);
3360
3862
  const model = (0, model_1.pickGenerationModelIdentity)(output);
3361
3863
  this.endStoredRun(run, {
3362
3864
  output: softError ? void 0 : structured,
@@ -3380,33 +3882,10 @@ var require_langchain = __commonJS({
3380
3882
  this.noteRootOutput(stored, structured);
3381
3883
  }
3382
3884
  }
3383
- if (awaitingTools) {
3384
- if (run.ownsTrace)
3385
- run.deferFinalize = true;
3386
- return;
3387
- }
3388
3885
  this.runs.delete(runId);
3389
- if (run.ownsTrace) {
3390
- void this.maybeFinalizeOwner(run, endedAt);
3391
- return;
3392
- }
3393
- const deferred = this.deferredOwnerFor(run.owningTraceId);
3394
- if (deferred) {
3395
- this.runs.delete(deferred.rootRunId);
3396
- void this.maybeFinalizeOwner(deferred, endedAt);
3397
- }
3398
- }
3399
- async finalizeDeferredOwner(owningTraceId, endedAt, rootError) {
3400
- const deferred = this.deferredOwnerFor(owningTraceId);
3401
- if (!deferred)
3402
- return;
3403
- const stored = this.storedTrace(deferred.owningTraceId);
3404
- if (stored && rootError)
3405
- this.noteRootError(stored, rootError);
3406
- this.runs.delete(deferred.rootRunId);
3407
- void this.maybeFinalizeOwner(deferred, endedAt);
3886
+ this.maybeFinalizeOwner(run);
3408
3887
  }
3409
- async handleLLMError(error, runId) {
3888
+ handleLLMError(error, runId) {
3410
3889
  const run = this.runs.get(runId);
3411
3890
  if (!run)
3412
3891
  return;
@@ -3425,13 +3904,10 @@ var require_langchain = __commonJS({
3425
3904
  this.noteRootError(stored, message);
3426
3905
  }
3427
3906
  this.runs.delete(runId);
3428
- if (run.ownsTrace) {
3429
- void this.maybeFinalizeOwner(run, endedAt);
3430
- return;
3431
- }
3432
- void this.finalizeDeferredOwner(run.owningTraceId, endedAt, message);
3907
+ this.maybeFinalizeOwner(run);
3433
3908
  }
3434
3909
  handleToolStart(serialized, input, runId, parentRunId, tags, metadata, _runName, _toolCallId) {
3910
+ this.evictIdleTraces();
3435
3911
  const startedAt = /* @__PURE__ */ new Date();
3436
3912
  const attachment = this.resolveAttachment(runId, parentRunId, () => this.createOwnedTrace(runId, this.traceName(serialized, "langchain-tool"), input, "tool", metadata, tags));
3437
3913
  if (attachment.ownsTrace) {
@@ -3459,7 +3935,7 @@ var require_langchain = __commonJS({
3459
3935
  ownsTrace: attachment.ownsTrace
3460
3936
  });
3461
3937
  }
3462
- async handleToolEnd(output, runId) {
3938
+ handleToolEnd(output, runId) {
3463
3939
  const run = this.runs.get(runId);
3464
3940
  if (!run)
3465
3941
  return;
@@ -3490,9 +3966,9 @@ var require_langchain = __commonJS({
3490
3966
  }
3491
3967
  }
3492
3968
  this.runs.delete(runId);
3493
- void this.maybeFinalizeOwner(run, endedAt);
3969
+ this.maybeFinalizeOwner(run);
3494
3970
  }
3495
- async handleToolError(error, runId) {
3971
+ handleToolError(error, runId) {
3496
3972
  const run = this.runs.get(runId);
3497
3973
  if (!run)
3498
3974
  return;
@@ -3511,13 +3987,10 @@ var require_langchain = __commonJS({
3511
3987
  this.noteRootError(stored, message);
3512
3988
  }
3513
3989
  this.runs.delete(runId);
3514
- if (run.ownsTrace) {
3515
- void this.maybeFinalizeOwner(run, endedAt);
3516
- return;
3517
- }
3518
- void this.finalizeDeferredOwner(run.owningTraceId, endedAt, message);
3990
+ this.maybeFinalizeOwner(run);
3519
3991
  }
3520
3992
  handleRetrieverStart(serialized, query, runId, parentRunId, tags, metadata, _name) {
3993
+ this.evictIdleTraces();
3521
3994
  const startedAt = /* @__PURE__ */ new Date();
3522
3995
  const attachment = this.resolveAttachment(runId, parentRunId, () => this.createOwnedTrace(runId, this.traceName(serialized, "langchain-retriever"), query, "retriever", metadata, tags));
3523
3996
  if (attachment.ownsTrace) {
@@ -3543,7 +4016,7 @@ var require_langchain = __commonJS({
3543
4016
  ownsTrace: attachment.ownsTrace
3544
4017
  });
3545
4018
  }
3546
- async handleRetrieverEnd(documents, runId) {
4019
+ handleRetrieverEnd(documents, runId) {
3547
4020
  const run = this.runs.get(runId);
3548
4021
  if (!run)
3549
4022
  return;
@@ -3560,9 +4033,9 @@ var require_langchain = __commonJS({
3560
4033
  this.noteRootOutput(stored, documents);
3561
4034
  }
3562
4035
  this.runs.delete(runId);
3563
- void this.maybeFinalizeOwner(run, endedAt);
4036
+ this.maybeFinalizeOwner(run);
3564
4037
  }
3565
- async handleRetrieverError(error, runId) {
4038
+ handleRetrieverError(error, runId) {
3566
4039
  const run = this.runs.get(runId);
3567
4040
  if (!run)
3568
4041
  return;
@@ -3581,18 +4054,22 @@ var require_langchain = __commonJS({
3581
4054
  this.noteRootError(stored, message);
3582
4055
  }
3583
4056
  this.runs.delete(runId);
3584
- void this.maybeFinalizeOwner(run, endedAt);
4057
+ this.maybeFinalizeOwner(run);
3585
4058
  }
3586
- /** Send completed traces and await ingest delivery. */
4059
+ /**
4060
+ * Await delivery of every trace whose root run already ended. One handler
4061
+ * serves every concurrent run, so a trace whose root is still running stays
4062
+ * open; `shutdown()` sends those.
4063
+ */
3587
4064
  async flush() {
4065
+ await Promise.all(this.pending);
4066
+ }
4067
+ /** Finalize and send every trace, open ones included, and reset state. */
4068
+ async shutdown() {
3588
4069
  await Promise.all([
3589
4070
  ...Array.from(this.traces.entries(), ([id, stored]) => this.finalizeTrace(id, stored)),
3590
4071
  ...Array.from(this.pending)
3591
4072
  ]);
3592
- }
3593
- /** Finalize open traces and reset integration state. */
3594
- async shutdown() {
3595
- await this.flush();
3596
4073
  this.runs.clear();
3597
4074
  this.traces.clear();
3598
4075
  }
@@ -3608,6 +4085,43 @@ var require_langchain = __commonJS({
3608
4085
  }
3609
4086
  });
3610
4087
 
4088
+ // ../../packages/ts/tracing/dist/integration-client.js
4089
+ var require_integration_client = __commonJS({
4090
+ "../../packages/ts/tracing/dist/integration-client.js"(exports) {
4091
+ "use strict";
4092
+ Object.defineProperty(exports, "__esModule", { value: true });
4093
+ exports.integrationClientGetter = integrationClientGetter;
4094
+ exports.resetIntegrationClientErrors = resetIntegrationClientErrors;
4095
+ var client_1 = require_client();
4096
+ var error_message_1 = require_error_message();
4097
+ var reportedIntegrations = /* @__PURE__ */ new Set();
4098
+ function integrationClientGetter(integration, options) {
4099
+ const { lemma: provided, ...clientOptions } = options;
4100
+ let lemma = provided;
4101
+ return () => {
4102
+ if (lemma)
4103
+ return lemma;
4104
+ try {
4105
+ lemma = new client_1.Lemma(clientOptions);
4106
+ } catch (error) {
4107
+ reportClientError(integration, error);
4108
+ }
4109
+ return lemma;
4110
+ };
4111
+ }
4112
+ function reportClientError(integration, error) {
4113
+ if (reportedIntegrations.has(integration))
4114
+ return;
4115
+ reportedIntegrations.add(integration);
4116
+ const cause = (0, error_message_1.describeError)(error).replace(/^@uselemma\/tracing:\s*/, "");
4117
+ console.error(`@uselemma/tracing: ${integration} can't send traces: ${cause}. Set LEMMA_API_KEY and LEMMA_PROJECT_ID (and LEMMA_BASE_URL if you use one) in this runtime's environment, or pass apiKey, projectId and baseUrl in its options. It drops traces until this is fixed; this error is logged once per process.`);
4118
+ }
4119
+ function resetIntegrationClientErrors() {
4120
+ reportedIntegrations.clear();
4121
+ }
4122
+ }
4123
+ });
4124
+
3611
4125
  // ../../packages/ts/tracing/dist/mastra.js
3612
4126
  var require_mastra = __commonJS({
3613
4127
  "../../packages/ts/tracing/dist/mastra.js"(exports) {
@@ -3616,7 +4130,10 @@ var require_mastra = __commonJS({
3616
4130
  exports.LemmaMastraExporter = void 0;
3617
4131
  exports.mastra = mastra;
3618
4132
  var client_1 = require_client();
4133
+ var delivery_1 = require_delivery();
4134
+ var dropped_traces_1 = require_dropped_traces();
3619
4135
  var error_message_1 = require_error_message();
4136
+ var integration_client_1 = require_integration_client();
3620
4137
  var schedule_1 = require_schedule();
3621
4138
  var model_1 = require_model();
3622
4139
  var tool_result_1 = require_tool_result();
@@ -3787,26 +4304,26 @@ var require_mastra = __commonJS({
3787
4304
  return fromOutput;
3788
4305
  return (0, usage_1.normalizeTokenUsage)(span.attributes?.usage) ?? (0, usage_1.normalizeTokenUsage)(span.attributes);
3789
4306
  }
4307
+ function nextMacrotask() {
4308
+ return new Promise((resolve2) => (0, schedule_1.scheduleMacrotask)(resolve2));
4309
+ }
3790
4310
  var LemmaMastraExporter = class {
3791
4311
  options;
3792
4312
  name = "lemma";
3793
- lemma;
4313
+ getLemma;
3794
4314
  buffers = /* @__PURE__ */ new Map();
3795
4315
  pending = /* @__PURE__ */ new Set();
3796
4316
  pendingUsage;
3797
4317
  constructor(options = {}) {
3798
4318
  this.options = options;
3799
- this.lemma = options.lemma;
4319
+ this.getLemma = (0, integration_client_1.integrationClientGetter)("LemmaMastraExporter", options);
3800
4320
  }
3801
- getLemma() {
3802
- this.lemma ??= new client_1.Lemma({
3803
- apiKey: this.options.apiKey,
3804
- projectId: this.options.projectId,
3805
- baseUrl: this.options.baseUrl,
3806
- fetch: this.options.fetch,
3807
- release: this.options.release
3808
- });
3809
- return this.lemma;
4321
+ track(promise) {
4322
+ this.pending.add(promise);
4323
+ const settle = () => {
4324
+ this.pending.delete(promise);
4325
+ };
4326
+ promise.then(settle, settle);
3810
4327
  }
3811
4328
  bufferFor(traceId) {
3812
4329
  const existing = this.buffers.get(traceId);
@@ -3890,10 +4407,22 @@ var require_mastra = __commonJS({
3890
4407
  trace.recordSpan(base);
3891
4408
  }
3892
4409
  deliver(root, children) {
4410
+ const lemma = this.getLemma();
4411
+ if (!lemma) {
4412
+ throw new Error(`@uselemma/tracing: trace ${root.traceId} not sent: no client`);
4413
+ }
4414
+ try {
4415
+ return this.send(lemma, root, children);
4416
+ } catch (error) {
4417
+ (0, dropped_traces_1.reportDroppedTrace)(root.traceId, (0, delivery_1.failedBeforeSending)(error).cause);
4418
+ throw error;
4419
+ }
4420
+ }
4421
+ send(lemma, root, children) {
3893
4422
  const startedAt = toDate(root.startTime) ?? /* @__PURE__ */ new Date();
3894
4423
  const endedAt = toDate(root.endTime) ?? /* @__PURE__ */ new Date();
3895
4424
  const recordedIds = new Set(children.map((child) => child.id));
3896
- const trace = this.getLemma().trace({
4425
+ const trace = (0, client_1.startBackgroundTrace)(lemma, {
3897
4426
  id: root.traceId,
3898
4427
  name: this.options.agentName ?? resolveAgentName(root),
3899
4428
  input: rootTraceInput(root.input),
@@ -3920,14 +4449,11 @@ var require_mastra = __commonJS({
3920
4449
  if (rootError) {
3921
4450
  trace.fail(rootError);
3922
4451
  }
3923
- const endPromise = trace.end(rootError ? { durationMs: durationMs(startedAt, endedAt), endedAt } : {
4452
+ return trace.end(rootError ? { durationMs: durationMs(startedAt, endedAt), endedAt } : {
3924
4453
  output: root.output,
3925
4454
  durationMs: durationMs(startedAt, endedAt),
3926
4455
  endedAt
3927
4456
  });
3928
- this.pending.add(endPromise);
3929
- void endPromise.finally(() => this.pending.delete(endPromise));
3930
- return endPromise;
3931
4457
  }
3932
4458
  async exportTracingEvent(event) {
3933
4459
  if (event.type === "span_updated")
@@ -3943,13 +4469,7 @@ var require_mastra = __commonJS({
3943
4469
  const buffer = this.buffers.get(span.traceId);
3944
4470
  const children = buffer?.children ?? [];
3945
4471
  this.buffers.delete(span.traceId);
3946
- const promise = new Promise((resolve2, reject) => {
3947
- (0, schedule_1.scheduleMacrotask)(() => {
3948
- this.deliver(span, children).then(resolve2, reject);
3949
- });
3950
- });
3951
- this.pending.add(promise);
3952
- void promise.finally(() => this.pending.delete(promise));
4472
+ this.track(nextMacrotask().then(() => this.deliver(span, children)));
3953
4473
  return;
3954
4474
  }
3955
4475
  this.pushChild(span);
@@ -3962,9 +4482,12 @@ var require_mastra = __commonJS({
3962
4482
  this.pendingUsage = result;
3963
4483
  return 0;
3964
4484
  }
3965
- /** Send completed traces and await ingest delivery. */
4485
+ /**
4486
+ * Send completed traces and await ingest delivery. A trace that could not
4487
+ * be sent was already reported, so it never rejects into the caller.
4488
+ */
3966
4489
  async flush() {
3967
- await Promise.all(Array.from(this.pending));
4490
+ await Promise.allSettled(Array.from(this.pending));
3968
4491
  }
3969
4492
  async shutdown() {
3970
4493
  await this.flush();
@@ -4217,6 +4740,7 @@ var require_openai_agents = __commonJS({
4217
4740
  var openai_agents_containers_1 = require_openai_agents_containers();
4218
4741
  var model_1 = require_model();
4219
4742
  var reply_text_1 = require_reply_text();
4743
+ var serialize_1 = require_serialize();
4220
4744
  var INTEGRATION_ATTRS = {
4221
4745
  "lemma.sdk.integration": "openai-agents"
4222
4746
  };
@@ -4295,8 +4819,8 @@ var require_openai_agents = __commonJS({
4295
4819
  "openai.agents.span_id": span.spanId,
4296
4820
  "openai.agents.parent_id": span.parentId,
4297
4821
  "openai.agents.span_type": span.spanData.type,
4298
- "openai.agents.trace_metadata": span.traceMetadata ? JSON.stringify(span.traceMetadata) : void 0,
4299
- "openai.agents.span_data": JSON.stringify((0, openai_agents_generation_1.spanDataForAttribute)(span.spanData))
4822
+ "openai.agents.trace_metadata": span.traceMetadata ? (0, serialize_1.stringifyTraceJson)(span.traceMetadata) : void 0,
4823
+ "openai.agents.span_data": (0, serialize_1.stringifyTraceJson)((0, openai_agents_generation_1.spanDataForAttribute)(span.spanData))
4300
4824
  }).filter(([, value]) => value !== void 0 && value !== null));
4301
4825
  }
4302
4826
  function coerceDate(value) {
@@ -4399,7 +4923,7 @@ var require_openai_agents = __commonJS({
4399
4923
  applyIdentity(existing, trace.groupId, trace.metadata);
4400
4924
  return existing;
4401
4925
  }
4402
- const handle = lemma.trace({
4926
+ const handle = (0, client_1.startBackgroundTrace)(lemma, {
4403
4927
  name: trace.name || "openai-agents-trace",
4404
4928
  metadata: {
4405
4929
  ...options.metadata,
@@ -4577,9 +5101,6 @@ var require_openai_agents = __commonJS({
4577
5101
  ...timing
4578
5102
  });
4579
5103
  }
4580
- async function finalizeAll() {
4581
- await Promise.all(Array.from(traces.entries(), ([traceId, stored]) => finalizeTrace(traceId, stored)));
4582
- }
4583
5104
  return {
4584
5105
  onTraceStart: async (trace) => {
4585
5106
  ensureTrace(trace);
@@ -4610,14 +5131,13 @@ var require_openai_agents = __commonJS({
4610
5131
  endSpan(span);
4611
5132
  },
4612
5133
  recordResult,
4613
- // Shutdown/forceFlush finalize any still-open traces (a one-time terminal
4614
- // send for traces that never received onTraceEnd), then drop them.
5134
+ // The one-time terminal send for traces that never received onTraceEnd.
4615
5135
  shutdown: async () => {
4616
- await finalizeAll();
5136
+ await Promise.all(Array.from(traces.entries(), ([traceId, stored]) => finalizeTrace(traceId, stored)));
4617
5137
  await Promise.all(pending);
4618
5138
  },
4619
5139
  forceFlush: async () => {
4620
- await finalizeAll();
5140
+ await new Promise((resolve2) => (0, schedule_1.scheduleMacrotask)(resolve2));
4621
5141
  await Promise.all(pending);
4622
5142
  }
4623
5143
  };
@@ -4625,33 +5145,81 @@ var require_openai_agents = __commonJS({
4625
5145
  }
4626
5146
  });
4627
5147
 
4628
- // ../../packages/ts/tracing/dist/vercel-ai.js
4629
- var require_vercel_ai = __commonJS({
4630
- "../../packages/ts/tracing/dist/vercel-ai.js"(exports) {
5148
+ // ../../packages/ts/tracing/dist/vercel-ai-events.js
5149
+ var require_vercel_ai_events = __commonJS({
5150
+ "../../packages/ts/tracing/dist/vercel-ai-events.js"(exports) {
4631
5151
  "use strict";
4632
5152
  Object.defineProperty(exports, "__esModule", { value: true });
4633
- exports.vercelAI = vercelAI;
4634
- var client_1 = require_client();
4635
- var error_message_1 = require_error_message();
4636
- var schedule_1 = require_schedule();
5153
+ exports.UNKEYED_RUN = void 0;
5154
+ exports.finishReasonError = finishReasonError;
5155
+ exports.eventOutput = eventOutput;
5156
+ exports.generationOutcome = generationOutcome;
5157
+ exports.errorName = errorName;
5158
+ exports.isCallerStop = isCallerStop;
5159
+ exports.reportedError = reportedError;
5160
+ exports.addMs = addMs;
5161
+ exports.subtractMs = subtractMs;
5162
+ exports.isV7StepStart = isV7StepStart;
5163
+ exports.isV7StepEnd = isV7StepEnd;
5164
+ exports.toolOutput = toolOutput2;
5165
+ exports.v6ToolOutput = v6ToolOutput;
5166
+ exports.resolveDurationMs = resolveDurationMs;
5167
+ exports.siblingSystem = siblingSystem;
5168
+ exports.resolveSystemForMessages = resolveSystemForMessages;
5169
+ exports.withSystemMessage = withSystemMessage;
5170
+ exports.v6NormalizedMessages = v6NormalizedMessages;
5171
+ exports.v6Input = v6Input;
5172
+ exports.rootTraceInput = rootTraceInput;
5173
+ exports.eventTraceInput = eventTraceInput;
5174
+ exports.eventMetadata = eventMetadata;
5175
+ exports.readIdentity = readIdentity;
5176
+ exports.eventIdentity = eventIdentity;
5177
+ exports.traceName = traceName;
5178
+ exports.eventUsage = eventUsage;
5179
+ exports.withIntegrationAttrs = withIntegrationAttrs;
5180
+ exports.runKey = runKey;
4637
5181
  var tool_result_1 = require_tool_result();
4638
5182
  var usage_1 = require_usage();
4639
5183
  var INTEGRATION_ATTRS = {
4640
5184
  "lemma.sdk.integration": "vercel-ai"
4641
5185
  };
4642
- var CONCURRENT_REUSE_ERROR = "vercelAI() is already tracing a run. Create a new vercelAI() integration per concurrent AI SDK operation.";
5186
+ var FINISH_REASON_ERROR = 'Model call ended with finishReason "error"';
5187
+ function finishReasonError(event) {
5188
+ return event.finishReason === "error" ? FINISH_REASON_ERROR : void 0;
5189
+ }
5190
+ function eventOutput(event) {
5191
+ return structuredAssistantOutput(event.text, event.content);
5192
+ }
5193
+ function generationOutcome(event) {
5194
+ const kept = event.error == null ? eventOutput(event) : void 0;
5195
+ return {
5196
+ output: kept,
5197
+ llmOutputMessages: kept === void 0 ? void 0 : [{ role: "assistant", content: kept }],
5198
+ error: event.error ?? finishReasonError(event)
5199
+ };
5200
+ }
5201
+ function errorName(value) {
5202
+ return typeof value === "object" && value !== null ? value.name : void 0;
5203
+ }
5204
+ function isCallerStop(error) {
5205
+ const name = errorName(error);
5206
+ return name === "AbortError" || name === "ResponseAborted";
5207
+ }
5208
+ function reportedError(event) {
5209
+ return typeof event === "object" && event !== null && "error" in event ? event.error : event;
5210
+ }
4643
5211
  function addMs(startedAt, durationMs) {
4644
5212
  return typeof durationMs === "number" ? new Date(startedAt.getTime() + durationMs) : /* @__PURE__ */ new Date();
4645
5213
  }
4646
5214
  function subtractMs(endedAt, durationMs) {
4647
5215
  return typeof durationMs === "number" ? new Date(endedAt.getTime() - durationMs) : endedAt;
4648
5216
  }
4649
- function v7StepKey(callId, stepNumber) {
4650
- return `${callId}:${stepNumber}`;
4651
- }
4652
5217
  function isV7StepStart(event) {
4653
5218
  return "callId" in event && "provider" in event && "modelId" in event;
4654
5219
  }
5220
+ function isV7StepEnd(event) {
5221
+ return "callId" in event;
5222
+ }
4655
5223
  function stringifyContent(content) {
4656
5224
  const text = content.map((part) => {
4657
5225
  if (!part || typeof part !== "object")
@@ -4826,17 +5394,21 @@ var require_vercel_ai = __commonJS({
4826
5394
  function eventMetadata(event) {
4827
5395
  return event && "metadata" in event ? event.metadata ?? void 0 : void 0;
4828
5396
  }
4829
- function traceName(options, event) {
4830
- if (options.agentName)
4831
- return options.agentName;
4832
- const functionId = event && "functionId" in event && typeof event.functionId === "string" ? event.functionId : void 0;
4833
- return functionId || "vercel-ai-agent";
5397
+ function readIdentity(sources, options) {
5398
+ return {
5399
+ threadId: lookupString(sources, [options.threadIdKey ?? "threadId"]),
5400
+ userId: lookupString(sources, [options.userIdKey ?? "userId"])
5401
+ };
4834
5402
  }
4835
- function v6Output(event) {
4836
- return structuredAssistantOutput(event.text, event.content);
5403
+ function eventIdentity(event, options) {
5404
+ const runtimeContext = event && "runtimeContext" in event ? event.runtimeContext : void 0;
5405
+ return readIdentity([runtimeContext, eventMetadata(event)], options);
4837
5406
  }
4838
- function endOutput(event) {
4839
- return structuredAssistantOutput(event.text, event.content);
5407
+ function traceName(agentName, event) {
5408
+ if (agentName)
5409
+ return agentName;
5410
+ const functionId = event && "functionId" in event && typeof event.functionId === "string" ? event.functionId : void 0;
5411
+ return functionId || "vercel-ai-agent";
4840
5412
  }
4841
5413
  function eventUsage(event) {
4842
5414
  return (0, usage_1.normalizeTokenUsage)(event.usage) ?? (0, usage_1.normalizeTokenUsage)(event.totalUsage);
@@ -4844,624 +5416,795 @@ var require_vercel_ai = __commonJS({
4844
5416
  function withIntegrationAttrs(attributes) {
4845
5417
  return { ...INTEGRATION_ATTRS, ...attributes ?? {} };
4846
5418
  }
4847
- function vercelAI(options = {}) {
4848
- let lemma = options.lemma;
4849
- const pending = /* @__PURE__ */ new Set();
4850
- let phase = "idle";
4851
- let modelCalls = /* @__PURE__ */ new Map();
4852
- let v7Steps = /* @__PURE__ */ new Map();
4853
- let v6Steps = /* @__PURE__ */ new Map();
4854
- let v6Starts = [];
4855
- let generationSpanIdsByCallId = /* @__PURE__ */ new Map();
4856
- let generationSpanIdsByToolCallId = /* @__PURE__ */ new Map();
4857
- let generationHandlesById = /* @__PURE__ */ new Map();
4858
- let toolExecutions = /* @__PURE__ */ new Map();
4859
- let latestV6GenerationId;
4860
- let managedTrace;
4861
- let recordedV6Step = false;
4862
- let sawV7StepZero = false;
4863
- let runStartedAt;
4864
- let runError;
4865
- let endingTrace;
4866
- let deliverOwnedTrace;
4867
- function resetRunState() {
4868
- phase = "idle";
4869
- modelCalls = /* @__PURE__ */ new Map();
4870
- v7Steps = /* @__PURE__ */ new Map();
4871
- v6Steps = /* @__PURE__ */ new Map();
4872
- v6Starts = [];
4873
- generationSpanIdsByCallId = /* @__PURE__ */ new Map();
4874
- generationSpanIdsByToolCallId = /* @__PURE__ */ new Map();
4875
- generationHandlesById = /* @__PURE__ */ new Map();
4876
- toolExecutions = /* @__PURE__ */ new Map();
4877
- latestV6GenerationId = void 0;
4878
- managedTrace = void 0;
4879
- recordedV6Step = false;
4880
- sawV7StepZero = false;
4881
- runStartedAt = void 0;
4882
- runError = void 0;
4883
- endingTrace = void 0;
4884
- deliverOwnedTrace = void 0;
4885
- }
4886
- function trackGeneration(handle) {
4887
- generationHandlesById.set(handle.id, handle);
4888
- }
4889
- function coverParent(parentId, endedAt) {
4890
- if (!parentId)
5419
+ exports.UNKEYED_RUN = void 0;
5420
+ function runKey(event) {
5421
+ const callId = typeof event === "object" && event !== null ? event.callId : void 0;
5422
+ return typeof callId === "string" && callId ? callId : exports.UNKEYED_RUN;
5423
+ }
5424
+ }
5425
+ });
5426
+
5427
+ // ../../packages/ts/tracing/dist/vercel-ai-run.js
5428
+ var require_vercel_ai_run = __commonJS({
5429
+ "../../packages/ts/tracing/dist/vercel-ai-run.js"(exports) {
5430
+ "use strict";
5431
+ Object.defineProperty(exports, "__esModule", { value: true });
5432
+ exports.VercelAIRun = exports.CANCELLED_METADATA_KEY = void 0;
5433
+ exports.endableTrace = endableTrace;
5434
+ var client_1 = require_client();
5435
+ var error_message_1 = require_error_message();
5436
+ var schedule_1 = require_schedule();
5437
+ var vercel_ai_events_1 = require_vercel_ai_events();
5438
+ exports.CANCELLED_METADATA_KEY = "lemma.cancelled";
5439
+ function signalOutcome(reason) {
5440
+ return (0, vercel_ai_events_1.errorName)(reason) === "TimeoutError" ? { kind: "failed", error: reason } : { kind: "cancelled", reason };
5441
+ }
5442
+ function outcomeValue(outcome) {
5443
+ if (outcome.kind === "failed")
5444
+ return outcome.error;
5445
+ return outcome.kind === "cancelled" ? outcome.reason : void 0;
5446
+ }
5447
+ function replaces(current, next) {
5448
+ if (current.kind === "cancelled")
5449
+ return false;
5450
+ if (next.kind === "failed")
5451
+ return true;
5452
+ return next.kind === "cancelled" && current.kind === "failed" && current.error === next.reason;
5453
+ }
5454
+ function endableTrace(options) {
5455
+ const trace = options.trace;
5456
+ return trace && typeof trace.end === "function" ? trace : void 0;
5457
+ }
5458
+ var VercelAIRun = class {
5459
+ ctx;
5460
+ startedAt = /* @__PURE__ */ new Date();
5461
+ /** The operation's start event; its system prompt backs later steps. */
5462
+ startEvent;
5463
+ /** AI SDK 7 model call in flight; one at a time per operation. */
5464
+ openModelCall;
5465
+ v7Steps = /* @__PURE__ */ new Map();
5466
+ v6Steps = /* @__PURE__ */ new Map();
5467
+ generationSpanIdsByToolCallId = /* @__PURE__ */ new Map();
5468
+ generationHandlesById = /* @__PURE__ */ new Map();
5469
+ toolExecutions = /* @__PURE__ */ new Map();
5470
+ /** The generation a tool without a known parent nests under. */
5471
+ latestGenerationId;
5472
+ managedTrace;
5473
+ recordedV6Step = false;
5474
+ /** The managed trace's metadata object; the cancelled marker goes here. */
5475
+ runMetadata;
5476
+ /** The latest finished step: a stopped run's partial output. */
5477
+ lastStep;
5478
+ signal;
5479
+ stopWatchingAbort;
5480
+ state = { phase: "active" };
5481
+ /**
5482
+ * The integration's threadId and userId, replaced key by key by the latest
5483
+ * event that carries the call's own: only some events carry them.
5484
+ */
5485
+ identity;
5486
+ constructor(ctx) {
5487
+ this.ctx = ctx;
5488
+ this.identity = (0, vercel_ai_events_1.readIdentity)([ctx.options.metadata], ctx.options);
5489
+ }
5490
+ get phase() {
5491
+ return this.state.phase;
5492
+ }
5493
+ get options() {
5494
+ return this.ctx.options;
5495
+ }
5496
+ /** The caller's trace, or the one this run started. */
5497
+ get rootTrace() {
5498
+ return this.options.trace ?? this.managedTrace;
5499
+ }
5500
+ /** `signal` is the call's, from withAbortSignal(); AI SDK 6 sends its own. */
5501
+ start(event, signal) {
5502
+ this.watchAbort(event.abortSignal ?? signal);
5503
+ this.startEvent = { event, startedAt: /* @__PURE__ */ new Date() };
5504
+ this.resolveTrace(event);
5505
+ }
5506
+ stepStart(event) {
5507
+ if ((0, vercel_ai_events_1.isV7StepStart)(event)) {
5508
+ this.startV7Generation(event);
5509
+ return;
5510
+ }
5511
+ if (this.v6Steps.has(event.stepNumber))
4891
5512
  return;
4892
- generationHandlesById.get(parentId)?.ensureEndedAt(endedAt);
4893
- }
4894
- function getLemma() {
4895
- lemma ??= new client_1.Lemma({
4896
- apiKey: options.apiKey,
4897
- projectId: options.projectId,
4898
- baseUrl: options.baseUrl,
4899
- fetch: options.fetch,
4900
- release: options.release
5513
+ const stored = this.startV6Generation(event);
5514
+ if (stored)
5515
+ this.v6Steps.set(event.stepNumber, stored);
5516
+ }
5517
+ stepEnd(event) {
5518
+ this.lastStep = event;
5519
+ if ((0, vercel_ai_events_1.isV7StepEnd)(event)) {
5520
+ this.endV7Generation(event);
5521
+ return;
5522
+ }
5523
+ this.recordedV6Step = true;
5524
+ const stored = this.v6Steps.get(event.stepNumber);
5525
+ this.v6Steps.delete(event.stepNumber);
5526
+ this.recordV6Generation(event, stored);
5527
+ }
5528
+ modelCallStart(event) {
5529
+ const trace = this.resolveTrace(event);
5530
+ if (!trace)
5531
+ return;
5532
+ if (this.latestGenerationId) {
5533
+ this.openModelCall = { event, startedAt: /* @__PURE__ */ new Date() };
5534
+ return;
5535
+ }
5536
+ const startedAt = /* @__PURE__ */ new Date();
5537
+ const handle = trace.startGeneration({
5538
+ name: this.generationName({
5539
+ callId: event.callId,
5540
+ provider: event.provider,
5541
+ modelId: event.modelId,
5542
+ content: [],
5543
+ performance: {}
5544
+ }),
5545
+ input: event.messages,
5546
+ metadata: this.options.metadata,
5547
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
5548
+ model: event.modelId,
5549
+ startedAt,
5550
+ llmProvider: event.provider,
5551
+ llmInputMessages: event.messages,
5552
+ llmTools: event.tools
5553
+ });
5554
+ this.openModelCall = { event, startedAt, handle };
5555
+ this.latestGenerationId = handle.id;
5556
+ this.trackGeneration(handle);
5557
+ }
5558
+ modelCallEnd(event) {
5559
+ const stored = this.openModelCall;
5560
+ this.openModelCall = void 0;
5561
+ if (!stored?.handle)
5562
+ return;
5563
+ const endedAt = /* @__PURE__ */ new Date();
5564
+ const durationMs = (0, vercel_ai_events_1.resolveDurationMs)(stored.startedAt, endedAt, event.performance.responseTimeMs);
5565
+ stored.handle.end({
5566
+ model: event.modelId,
5567
+ durationMs,
5568
+ endedAt: (0, vercel_ai_events_1.addMs)(stored.startedAt, durationMs),
5569
+ llmProvider: event.provider,
5570
+ usage: (0, vercel_ai_events_1.eventUsage)(event),
5571
+ ...(0, vercel_ai_events_1.generationOutcome)(event)
4901
5572
  });
4902
- return lemma;
4903
5573
  }
4904
- function resolveThreadId(metadata) {
4905
- const key = options.threadIdKey ?? "threadId";
4906
- return lookupString([metadata, options.metadata], [key]);
5574
+ toolStart(event) {
5575
+ const trace = this.resolveTrace();
5576
+ if (!trace)
5577
+ return;
5578
+ const parentId = this.resolveToolParentId(event.toolCall.toolCallId);
5579
+ const startedAt = /* @__PURE__ */ new Date();
5580
+ const handle = trace.startTool({
5581
+ name: this.toolSpanName({
5582
+ ...event,
5583
+ toolExecutionMs: void 0,
5584
+ toolOutput: { type: "tool-result" }
5585
+ }),
5586
+ parentId,
5587
+ input: event.toolCall.input,
5588
+ metadata: this.options.metadata,
5589
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
5590
+ startedAt,
5591
+ toolName: event.toolCall.toolName
5592
+ });
5593
+ if (event.toolCall.toolCallId) {
5594
+ this.toolExecutions.set(event.toolCall.toolCallId, {
5595
+ handle,
5596
+ startedAt,
5597
+ parentId
5598
+ });
5599
+ }
4907
5600
  }
4908
- function resolveUserId(metadata) {
4909
- const key = options.userIdKey ?? "userId";
4910
- return lookupString([metadata, options.metadata], [key]);
5601
+ /** AI SDK 7 tool end. */
5602
+ toolEnd(event) {
5603
+ this.endTool(event, {
5604
+ name: this.toolSpanName(event),
5605
+ reportedMs: event.toolExecutionMs,
5606
+ outcome: (0, vercel_ai_events_1.toolOutput)(event)
5607
+ });
4911
5608
  }
4912
- function mergedMetadata(metadata) {
4913
- return {
4914
- ...options.metadata,
4915
- ...metadata ?? {}
4916
- };
5609
+ /** AI SDK 6 tool end. */
5610
+ v6ToolEnd(event) {
5611
+ this.endTool(event, {
5612
+ name: this.toolSpanName(event),
5613
+ reportedMs: event.durationMs,
5614
+ outcome: (0, vercel_ai_events_1.v6ToolOutput)(event)
5615
+ });
4917
5616
  }
4918
- function beginActivity() {
4919
- if (phase === "idle") {
4920
- phase = "active";
4921
- runStartedAt = /* @__PURE__ */ new Date();
5617
+ /** AI SDK 6 terminal event. */
5618
+ finish(event) {
5619
+ if (this.phase === "active" && !this.recordedV6Step) {
5620
+ this.recordV6Generation(event, this.startEvent);
4922
5621
  }
5622
+ this.end(event);
4923
5623
  }
4924
- function beginNewRun() {
4925
- if (phase === "active" || phase === "ending") {
4926
- throw new Error(CONCURRENT_REUSE_ERROR);
4927
- }
4928
- resetRunState();
4929
- phase = "active";
4930
- runStartedAt = /* @__PURE__ */ new Date();
5624
+ /** AI SDK terminal event; one that carries an error fails the run. */
5625
+ end(event) {
5626
+ this.settle(event.error != null ? { kind: "failed", error: event.error } : { kind: "completed", event });
4931
5627
  }
4932
- function hasExplicitEndableTrace() {
4933
- const trace = options.trace;
4934
- return Boolean(trace && typeof trace.end === "function");
5628
+ /** The call's abort signal fired. */
5629
+ abort(reason) {
5630
+ this.settle(signalOutcome(reason));
4935
5631
  }
4936
- function applyIdentity(trace, metadata) {
4937
- const threadId = resolveThreadId(metadata);
4938
- const userId = resolveUserId(metadata);
4939
- if (threadId)
4940
- trace.threadId(threadId);
4941
- if (userId)
4942
- trace.userId(userId);
5632
+ /** A thrown error: a failure, or a stop when it is the caller's abort. */
5633
+ stop(error) {
5634
+ this.settle((0, vercel_ai_events_1.isCallerStop)(error) ? { kind: "cancelled", reason: error } : { kind: "failed", error });
4943
5635
  }
4944
- function resolveTrace(event) {
4945
- if (phase === "ending") {
4946
- const trace = options.trace ?? managedTrace;
4947
- return trace ? {
4948
- trace,
4949
- source: options.trace ? "explicit" : "managed"
4950
- } : null;
4951
- }
4952
- beginActivity();
4953
- const metadata = eventMetadata(event);
4954
- if (options.trace) {
4955
- applyIdentity(options.trace, metadata);
4956
- return { trace: options.trace, source: "explicit" };
4957
- }
4958
- if (!managedTrace) {
4959
- const rawInput = eventTraceInput(event);
4960
- managedTrace = getLemma().trace({
4961
- name: traceName(options, event),
4962
- input: rootTraceInput(rawInput),
4963
- metadata: mergedMetadata(metadata),
4964
- threadId: resolveThreadId(metadata),
4965
- userId: resolveUserId(metadata),
4966
- startedAt: runStartedAt
4967
- });
4968
- } else {
4969
- applyIdentity(managedTrace, metadata);
4970
- if (event) {
4971
- const rawInput = eventTraceInput(event);
4972
- if (rawInput !== void 0) {
4973
- managedTrace.input(rootTraceInput(rawInput));
4974
- }
4975
- }
5636
+ /**
5637
+ * Stop an AI SDK 6 run whose signal was already aborted, which gets no
5638
+ * terminal event.
5639
+ */
5640
+ stopIfAborted() {
5641
+ if (this.phase === "active" && this.signal?.aborted) {
5642
+ this.abort(this.signal.reason);
4976
5643
  }
4977
- return { trace: managedTrace, source: "managed" };
4978
- }
4979
- function trackPending(promise) {
4980
- pending.add(promise);
4981
- void promise.finally(() => pending.delete(promise));
4982
- return promise;
4983
5644
  }
4984
- function ensureManagedTrace(event) {
4985
- if (options.trace || managedTrace)
5645
+ /** End an unfinished run for shutdown, closing its open spans. */
5646
+ close() {
5647
+ if (this.phase !== "active")
4986
5648
  return;
4987
- beginActivity();
4988
- managedTrace = getLemma().trace({
4989
- name: traceName(options, event),
4990
- metadata: mergedMetadata(eventMetadata(event)),
4991
- threadId: resolveThreadId(eventMetadata(event)),
4992
- userId: resolveUserId(eventMetadata(event)),
4993
- startedAt: runStartedAt
4994
- });
5649
+ this.closeOpenSpans({ endedAt: /* @__PURE__ */ new Date() });
5650
+ this.end({});
5651
+ }
5652
+ /** Send the ended run's trace now; resolves at once for an active run. */
5653
+ deliver() {
5654
+ const { state } = this;
5655
+ if (state.phase === "active")
5656
+ return Promise.resolve();
5657
+ if (state.phase === "sent")
5658
+ return state.sending;
5659
+ if (state.ownedTrace) {
5660
+ this.closeSpansFor(state.outcome, state.timing.endedAt);
5661
+ }
5662
+ this.ctx.release();
5663
+ const sending = Promise.resolve(state.ownedTrace?.end(state.timing));
5664
+ this.state = { phase: "sent", sending };
5665
+ return sending;
4995
5666
  }
4996
- async function endOwnedTrace(event) {
4997
- if (phase === "idle")
5667
+ /**
5668
+ * Record how the run ended. The first outcome ends an active run and
5669
+ * schedules its delivery a macrotask later, so a caller's recordResult()
5670
+ * can still stamp usage on its generations; see replaces() for what may
5671
+ * follow while delivery is pending.
5672
+ */
5673
+ settle(reported) {
5674
+ const { state } = this;
5675
+ const next = state.phase === "active" ? this.bySignal(reported) : reported;
5676
+ this.ctx.claim(outcomeValue(next));
5677
+ this.ctx.claim(outcomeValue(reported));
5678
+ if (state.phase === "sent")
4998
5679
  return;
4999
- if (phase === "ending")
5680
+ if (state.phase === "ending") {
5681
+ if (!replaces(state.outcome, next))
5682
+ return;
5683
+ const replaced = state.outcome;
5684
+ state.outcome = next;
5685
+ this.writeOutcome(next, replaced);
5000
5686
  return;
5001
- phase = "ending";
5002
- const trace = options.trace;
5003
- let ownedTrace;
5004
- let explicit = false;
5005
- if (trace && typeof trace.end === "function") {
5006
- explicit = true;
5007
- ownedTrace = {
5008
- end: trace.end.bind(trace),
5009
- fail: trace.fail.bind(trace),
5010
- output: trace.output.bind(trace)
5011
- };
5012
- } else {
5013
- ensureManagedTrace(event);
5014
- if (managedTrace) {
5015
- ownedTrace = managedTrace;
5016
- }
5017
- }
5018
- const identityTrace = options.trace ?? managedTrace;
5019
- if (identityTrace) {
5020
- applyIdentity(identityTrace, eventMetadata(event));
5021
- }
5022
- const eventError = "error" in event && event.error != null ? (0, error_message_1.describeError)(event.error) : void 0;
5023
- if (eventError && !runError) {
5024
- runError = eventError;
5025
5687
  }
5688
+ this.stopWatchingAbort?.();
5689
+ const endable = endableTrace(this.options);
5690
+ const terminalEvent = next.kind === "completed" ? next.event : void 0;
5691
+ this.noteIdentity(terminalEvent);
5692
+ const ownedTrace = this.options.trace ? endable : this.managedTrace ?? this.startManagedTrace(terminalEvent);
5026
5693
  const endedAt = /* @__PURE__ */ new Date();
5027
- const startedAt = runStartedAt ?? endedAt;
5028
- const durationMs = Math.max(0, endedAt.getTime() - startedAt.getTime());
5029
- const successOutput = endOutput(event);
5030
- endingTrace = ownedTrace;
5031
- let delivered = false;
5032
- const deliver = async () => {
5033
- if (delivered)
5694
+ if (!ownedTrace)
5695
+ this.closeSpansFor(next, endedAt);
5696
+ if (this.rootTrace)
5697
+ this.applyIdentity(this.rootTrace);
5698
+ const durationMs = Math.max(0, endedAt.getTime() - this.startedAt.getTime());
5699
+ this.state = {
5700
+ phase: "ending",
5701
+ outcome: next,
5702
+ ownedTrace,
5703
+ // Explicit handles already own startedAt from construction; only pass
5704
+ // durationMs for managed traces started with this run's startedAt.
5705
+ timing: endable ? { endedAt } : { durationMs, endedAt }
5706
+ };
5707
+ this.writeOutcome(next);
5708
+ this.ctx.trackPending(new Promise((resolve2) => (0, schedule_1.scheduleMacrotask)(resolve2)).then(() => this.deliver()));
5709
+ }
5710
+ /**
5711
+ * Write an outcome to the root. Written at once rather than at delivery: a
5712
+ * callback-form context is sent when its callback returns, and a failed
5713
+ * stream never throws there. Output is written only to a trace this run
5714
+ * ends.
5715
+ */
5716
+ writeOutcome(outcome, replaced) {
5717
+ const root = this.rootTrace;
5718
+ if (!root || this.state.phase !== "ending")
5719
+ return;
5720
+ const owned = this.state.ownedTrace !== void 0;
5721
+ switch (outcome.kind) {
5722
+ case "completed": {
5723
+ const { event } = outcome;
5724
+ const failure = (0, vercel_ai_events_1.finishReasonError)(event);
5725
+ if (failure)
5726
+ root.fail(failure);
5727
+ const output = (0, vercel_ai_events_1.eventOutput)(event);
5728
+ if (owned && output !== void 0)
5729
+ root.output(output);
5034
5730
  return;
5035
- delivered = true;
5036
- try {
5037
- if (!ownedTrace)
5038
- return;
5039
- const terminalError = runError;
5040
- const timing = explicit ? { endedAt } : { durationMs, endedAt };
5041
- if (terminalError) {
5042
- ownedTrace.fail(terminalError);
5043
- ownedTrace.output(void 0);
5044
- await ownedTrace.end(timing);
5045
- return;
5046
- }
5047
- if (successOutput === void 0) {
5048
- await ownedTrace.end(timing);
5049
- } else {
5050
- await ownedTrace.end({
5051
- output: successOutput,
5052
- ...timing
5053
- });
5054
- }
5055
- } finally {
5056
- resetRunState();
5057
5731
  }
5058
- };
5059
- deliverOwnedTrace = deliver;
5060
- trackPending(new Promise((resolve2, reject) => {
5732
+ case "failed":
5733
+ root.fail((0, error_message_1.describeError)(outcome.error));
5734
+ root.output(void 0);
5735
+ return;
5736
+ case "cancelled":
5737
+ if (replaced?.kind === "failed")
5738
+ root.fail(void 0);
5739
+ if (owned)
5740
+ root.output((0, vercel_ai_events_1.eventOutput)(this.lastStep ?? {}));
5741
+ if (this.runMetadata)
5742
+ this.runMetadata[exports.CANCELLED_METADATA_KEY] = true;
5743
+ return;
5744
+ }
5745
+ }
5746
+ recordResult(result) {
5747
+ return this.rootTrace?.applyGenerationUsage(result) ?? 0;
5748
+ }
5749
+ /**
5750
+ * AI SDK 6 sends no abort callback, and AI SDK 7 never passes the signal to
5751
+ * telemetry, so the run listens to it.
5752
+ */
5753
+ watchAbort(signal) {
5754
+ if (!signal)
5755
+ return;
5756
+ this.signal = signal;
5757
+ if (signal.aborted) {
5758
+ let live = true;
5061
5759
  (0, schedule_1.scheduleMacrotask)(() => {
5062
- deliver().then(resolve2, reject);
5760
+ if (live)
5761
+ this.abort(signal.reason);
5063
5762
  });
5064
- }));
5763
+ this.stopWatchingAbort = () => {
5764
+ live = false;
5765
+ };
5766
+ return;
5767
+ }
5768
+ const onAbort = () => this.abort(signal.reason);
5769
+ signal.addEventListener("abort", onAbort, { once: true });
5770
+ this.stopWatchingAbort = () => signal.removeEventListener("abort", onAbort);
5065
5771
  }
5066
- function recordResult(result) {
5067
- const trace = options.trace ?? managedTrace;
5068
- if (!trace)
5069
- return 0;
5070
- return trace.applyGenerationUsage(result);
5772
+ /**
5773
+ * A failure reported once the call's signal has aborted is the signal's
5774
+ * outcome, whatever value its reason is: AI SDK 7 rethrows the reason, and
5775
+ * reports it before the scheduled stop of a signal aborted at start.
5776
+ */
5777
+ bySignal(reported) {
5778
+ return reported.kind === "failed" && this.signal?.aborted ? signalOutcome(this.signal.reason) : reported;
5779
+ }
5780
+ /**
5781
+ * A stop or failure ends the spans still open, at the time the run ended
5782
+ * rather than when it is delivered; a completion leaves them.
5783
+ */
5784
+ closeSpansFor(outcome, endedAt) {
5785
+ if (outcome.kind === "completed")
5786
+ return;
5787
+ const error = outcome.kind === "failed" ? (0, error_message_1.describeError)(outcome.error) : void 0;
5788
+ this.closeOpenSpans({ error, endedAt });
5789
+ }
5790
+ /** End spans still open when a run stops early, so none is sent open. */
5791
+ closeOpenSpans({ error, endedAt }) {
5792
+ const generations = [
5793
+ ...[...this.v7Steps.values()].map((step) => step.handle),
5794
+ ...[...this.v6Steps.values()].map((step) => step.handle),
5795
+ this.openModelCall?.handle
5796
+ ];
5797
+ for (const handle of generations)
5798
+ handle?.end({ error, endedAt });
5799
+ for (const tool of this.toolExecutions.values()) {
5800
+ tool.handle.end({ endedAt });
5801
+ }
5802
+ }
5803
+ trackGeneration(handle) {
5804
+ this.generationHandlesById.set(handle.id, handle);
5805
+ }
5806
+ coverParent(parentId, endedAt) {
5807
+ if (!parentId)
5808
+ return;
5809
+ this.generationHandlesById.get(parentId)?.ensureEndedAt(endedAt);
5810
+ }
5811
+ noteIdentity(event) {
5812
+ const own = (0, vercel_ai_events_1.eventIdentity)(event, this.options);
5813
+ this.identity = {
5814
+ threadId: own.threadId ?? this.identity.threadId,
5815
+ userId: own.userId ?? this.identity.userId
5816
+ };
5817
+ }
5818
+ applyIdentity(trace) {
5819
+ const { threadId, userId } = this.identity;
5820
+ if (threadId)
5821
+ trace.threadId(threadId);
5822
+ if (userId)
5823
+ trace.userId(userId);
5824
+ }
5825
+ generationName(event) {
5826
+ return typeof this.options.generationName === "function" ? this.options.generationName(event) : this.options.generationName ?? "vercel-ai-generation";
5071
5827
  }
5072
- function recordV6Generation(event, stored) {
5073
- const resolved = resolveTrace(stored?.event);
5074
- if (!resolved)
5828
+ toolSpanName(event) {
5829
+ return typeof this.options.toolName === "function" ? this.options.toolName(event) : this.options.toolName ?? event.toolCall.toolName;
5830
+ }
5831
+ /** Start the run's managed trace; undefined when there is no client. */
5832
+ startManagedTrace(event, input) {
5833
+ const metadata = (0, vercel_ai_events_1.eventMetadata)(event);
5834
+ this.runMetadata = { ...this.options.metadata, ...metadata ?? {} };
5835
+ const lemma = this.ctx.getLemma();
5836
+ this.managedTrace = lemma ? (0, client_1.startBackgroundTrace)(lemma, {
5837
+ name: (0, vercel_ai_events_1.traceName)(this.options.agentName, event),
5838
+ input,
5839
+ metadata: this.runMetadata,
5840
+ threadId: this.identity.threadId,
5841
+ userId: this.identity.userId,
5842
+ startedAt: this.startedAt
5843
+ }) : void 0;
5844
+ return this.managedTrace;
5845
+ }
5846
+ resolveTrace(event) {
5847
+ if (this.phase !== "active")
5848
+ return this.rootTrace;
5849
+ this.noteIdentity(event);
5850
+ if (this.options.trace) {
5851
+ this.applyIdentity(this.options.trace);
5852
+ return this.options.trace;
5853
+ }
5854
+ if (!this.managedTrace) {
5855
+ return this.startManagedTrace(event, (0, vercel_ai_events_1.rootTraceInput)((0, vercel_ai_events_1.eventTraceInput)(event)));
5856
+ }
5857
+ this.applyIdentity(this.managedTrace);
5858
+ const rawInput = (0, vercel_ai_events_1.eventTraceInput)(event);
5859
+ if (rawInput !== void 0) {
5860
+ this.managedTrace.input((0, vercel_ai_events_1.rootTraceInput)(rawInput));
5861
+ }
5862
+ return this.managedTrace;
5863
+ }
5864
+ fallbackSystem() {
5865
+ return (0, vercel_ai_events_1.siblingSystem)(this.startEvent?.event);
5866
+ }
5867
+ recordV6Generation(event, stored) {
5868
+ const trace = this.resolveTrace(stored?.event);
5869
+ if (!trace)
5075
5870
  return;
5076
- const { trace } = resolved;
5077
5871
  const startedAt = stored?.startedAt ?? /* @__PURE__ */ new Date();
5078
5872
  const endedAt = /* @__PURE__ */ new Date();
5079
- const durationMs = resolveDurationMs(startedAt, endedAt, void 0);
5080
- const id = crypto.randomUUID();
5081
- const name = typeof options.generationName === "function" ? options.generationName(event) : options.generationName ?? "vercel-ai-generation";
5082
- const output = v6Output(event);
5083
- const generationError = "error" in event && event.error != null ? (0, error_message_1.describeError)(event.error) : void 0;
5084
- const fallbackSystem = siblingSystem(v6Starts.at(-1)?.event);
5873
+ const fallbackSystem = this.fallbackSystem();
5085
5874
  const generation = {
5086
- name,
5087
- input: stored?.event && v6Input(stored.event, fallbackSystem),
5088
- output: generationError ? void 0 : output,
5089
- metadata: options.metadata,
5090
- attributes: withIntegrationAttrs(),
5875
+ name: this.generationName(event),
5876
+ input: stored?.event && (0, vercel_ai_events_1.v6Input)(stored.event, fallbackSystem),
5877
+ metadata: this.options.metadata,
5878
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
5091
5879
  model: event.model.modelId,
5092
5880
  startedAt,
5093
5881
  endedAt,
5094
- durationMs,
5882
+ durationMs: (0, vercel_ai_events_1.resolveDurationMs)(startedAt, endedAt, void 0),
5095
5883
  llmProvider: event.model.provider,
5096
- llmInputMessages: stored?.event ? v6NormalizedMessages(stored.event, fallbackSystem) : void 0,
5097
- llmOutputMessages: output === void 0 || generationError ? void 0 : [{ role: "assistant", content: output }],
5884
+ llmInputMessages: stored?.event ? (0, vercel_ai_events_1.v6NormalizedMessages)(stored.event, fallbackSystem) : void 0,
5098
5885
  llmTools: stored?.event.tools,
5099
- status: generationError ? "ERROR" : void 0,
5100
- error: generationError,
5101
- usage: eventUsage(event)
5886
+ usage: (0, vercel_ai_events_1.eventUsage)(event),
5887
+ ...(0, vercel_ai_events_1.generationOutcome)(event)
5102
5888
  };
5103
5889
  if (stored?.handle) {
5104
5890
  stored.handle.end(generation);
5105
- latestV6GenerationId = stored.handle.id;
5106
- trackGeneration(stored.handle);
5891
+ this.latestGenerationId = stored.handle.id;
5892
+ this.trackGeneration(stored.handle);
5107
5893
  return;
5108
5894
  }
5109
- trace.recordGeneration({
5110
- id,
5111
- ...generation
5112
- });
5113
- latestV6GenerationId = id;
5895
+ const id = crypto.randomUUID();
5896
+ trace.recordGeneration({ id, ...generation });
5897
+ this.latestGenerationId = id;
5114
5898
  }
5115
- function startV7Generation(event) {
5116
- if (event.stepNumber === 0) {
5117
- if (sawV7StepZero && phase === "active") {
5118
- throw new Error(CONCURRENT_REUSE_ERROR);
5119
- }
5120
- sawV7StepZero = true;
5121
- }
5122
- const resolved = resolveTrace(event);
5123
- if (!resolved)
5899
+ startV7Generation(event) {
5900
+ const trace = this.resolveTrace(event);
5901
+ if (!trace)
5124
5902
  return;
5125
- const { trace } = resolved;
5126
- const name = typeof options.generationName === "function" ? options.generationName({
5127
- callId: event.callId,
5128
- provider: event.provider,
5129
- modelId: event.modelId,
5130
- content: [],
5131
- performance: {}
5132
- }) : options.generationName ?? "vercel-ai-generation";
5133
5903
  const startedAt = /* @__PURE__ */ new Date();
5134
- const messages = withSystemMessage(resolveSystemForMessages(event, event.messages, siblingSystem(v6Starts.at(-1)?.event)), event.messages);
5904
+ const messages = (0, vercel_ai_events_1.withSystemMessage)((0, vercel_ai_events_1.resolveSystemForMessages)(event, event.messages, this.fallbackSystem()), event.messages);
5135
5905
  const handle = trace.startGeneration({
5136
- name,
5906
+ name: this.generationName({
5907
+ callId: event.callId,
5908
+ provider: event.provider,
5909
+ modelId: event.modelId,
5910
+ content: [],
5911
+ performance: {}
5912
+ }),
5137
5913
  input: messages,
5138
- metadata: options.metadata,
5139
- attributes: withIntegrationAttrs(),
5914
+ metadata: this.options.metadata,
5915
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
5140
5916
  model: event.modelId,
5141
5917
  startedAt,
5142
5918
  llmProvider: event.provider,
5143
5919
  llmInputMessages: messages,
5144
5920
  llmTools: event.tools
5145
5921
  });
5146
- const stored = { event, startedAt, handle };
5147
- v7Steps.set(v7StepKey(event.callId, event.stepNumber), stored);
5148
- generationSpanIdsByCallId.set(event.callId, handle.id);
5149
- trackGeneration(handle);
5150
- }
5151
- function startV6Generation(event, key) {
5152
- const resolved = resolveTrace(event);
5153
- if (!resolved)
5922
+ this.v7Steps.set(event.stepNumber, { event, startedAt, handle });
5923
+ this.latestGenerationId = handle.id;
5924
+ this.trackGeneration(handle);
5925
+ }
5926
+ startV6Generation(event) {
5927
+ const trace = this.resolveTrace(event);
5928
+ if (!trace)
5154
5929
  return void 0;
5155
- const { trace } = resolved;
5156
5930
  const startedAt = /* @__PURE__ */ new Date();
5157
- const name = typeof options.generationName === "function" ? options.generationName({
5158
- stepNumber: "stepNumber" in event ? event.stepNumber : 0,
5159
- model: event.model
5160
- }) : options.generationName ?? "vercel-ai-generation";
5161
- const fallbackSystem = siblingSystem(v6Starts.at(-1)?.event);
5162
- const input = v6Input(event, fallbackSystem);
5931
+ const fallbackSystem = this.fallbackSystem();
5163
5932
  const handle = trace.startGeneration({
5164
- name,
5165
- input,
5166
- metadata: options.metadata,
5167
- attributes: withIntegrationAttrs(),
5933
+ name: this.generationName({
5934
+ stepNumber: event.stepNumber,
5935
+ model: event.model
5936
+ }),
5937
+ input: (0, vercel_ai_events_1.v6Input)(event, fallbackSystem),
5938
+ metadata: this.options.metadata,
5939
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
5168
5940
  model: event.model.modelId,
5169
5941
  startedAt,
5170
5942
  llmProvider: event.model.provider,
5171
- llmInputMessages: v6NormalizedMessages(event, fallbackSystem),
5943
+ llmInputMessages: (0, vercel_ai_events_1.v6NormalizedMessages)(event, fallbackSystem),
5172
5944
  llmTools: event.tools
5173
5945
  });
5174
- latestV6GenerationId = handle.id;
5175
- trackGeneration(handle);
5176
- return { event, startedAt, handle, key };
5177
- }
5178
- function endV7Generation(event) {
5179
- const key = v7StepKey(event.callId, event.stepNumber);
5180
- const stored = v7Steps.get(key);
5181
- v7Steps.delete(key);
5946
+ this.latestGenerationId = handle.id;
5947
+ this.trackGeneration(handle);
5948
+ return { event, startedAt, handle };
5949
+ }
5950
+ endV7Generation(event) {
5951
+ const stored = this.v7Steps.get(event.stepNumber);
5952
+ this.v7Steps.delete(event.stepNumber);
5182
5953
  if (!stored)
5183
5954
  return;
5184
5955
  const endedAt = /* @__PURE__ */ new Date();
5185
- const durationMs = resolveDurationMs(stored.startedAt, endedAt, event.performance?.stepTimeMs ?? event.performance?.responseTimeMs);
5186
- const output = structuredAssistantOutput(event.text, event.content);
5187
- const generationError = event.error != null ? (0, error_message_1.describeError)(event.error) : void 0;
5956
+ const durationMs = (0, vercel_ai_events_1.resolveDurationMs)(stored.startedAt, endedAt, event.performance?.stepTimeMs ?? event.performance?.responseTimeMs);
5188
5957
  for (const toolCall of event.toolCalls ?? []) {
5189
5958
  if (toolCall.toolCallId) {
5190
- generationSpanIdsByToolCallId.set(toolCall.toolCallId, stored.handle.id);
5959
+ this.generationSpanIdsByToolCallId.set(toolCall.toolCallId, stored.handle.id);
5191
5960
  }
5192
5961
  }
5193
5962
  stored.handle.end({
5194
- output: generationError ? void 0 : output,
5195
5963
  model: event.model.modelId,
5196
5964
  durationMs,
5197
- endedAt: addMs(stored.startedAt, durationMs),
5965
+ endedAt: (0, vercel_ai_events_1.addMs)(stored.startedAt, durationMs),
5198
5966
  llmProvider: event.model.provider,
5199
- llmOutputMessages: output === void 0 || generationError ? void 0 : [{ role: "assistant", content: output }],
5200
- status: generationError ? "ERROR" : void 0,
5201
- error: generationError,
5202
- usage: eventUsage(event)
5967
+ usage: (0, vercel_ai_events_1.eventUsage)(event),
5968
+ ...(0, vercel_ai_events_1.generationOutcome)(event)
5203
5969
  });
5204
5970
  }
5205
- function resolveToolParentId(callId, toolCallId) {
5206
- return toolCallId && generationSpanIdsByToolCallId.get(toolCallId) || (callId ? generationSpanIdsByCallId.get(callId) : void 0) || latestV6GenerationId;
5971
+ resolveToolParentId(toolCallId) {
5972
+ return toolCallId && this.generationSpanIdsByToolCallId.get(toolCallId) || this.latestGenerationId;
5207
5973
  }
5208
- const integration = {
5209
- onLanguageModelCallStart(event) {
5210
- if (phase === "active" && generationSpanIdsByCallId.size > 0 && !generationSpanIdsByCallId.has(event.callId)) {
5211
- const belongsToActiveStep = [...v7Steps.values()].some((step) => step.event.callId === event.callId);
5212
- if (!belongsToActiveStep) {
5213
- throw new Error(CONCURRENT_REUSE_ERROR);
5974
+ endTool(event, { name, reportedMs, outcome }) {
5975
+ const trace = this.resolveTrace();
5976
+ if (!trace)
5977
+ return;
5978
+ const { toolCallId, toolName } = event.toolCall;
5979
+ const storedTool = toolCallId ? this.toolExecutions.get(toolCallId) : void 0;
5980
+ if (toolCallId)
5981
+ this.toolExecutions.delete(toolCallId);
5982
+ if (storedTool) {
5983
+ const endedAt2 = (0, vercel_ai_events_1.addMs)(storedTool.startedAt, reportedMs);
5984
+ const durationMs2 = (0, vercel_ai_events_1.resolveDurationMs)(storedTool.startedAt, endedAt2, reportedMs);
5985
+ const toolEndedAt = (0, vercel_ai_events_1.addMs)(storedTool.startedAt, durationMs2);
5986
+ storedTool.handle.end({
5987
+ durationMs: durationMs2,
5988
+ endedAt: toolEndedAt,
5989
+ toolName,
5990
+ ...outcome
5991
+ });
5992
+ this.coverParent(storedTool.parentId, toolEndedAt);
5993
+ return;
5994
+ }
5995
+ const endedAt = /* @__PURE__ */ new Date();
5996
+ const durationMs = (0, vercel_ai_events_1.resolveDurationMs)((0, vercel_ai_events_1.subtractMs)(endedAt, reportedMs), endedAt, reportedMs);
5997
+ const parentId = this.resolveToolParentId(toolCallId);
5998
+ trace.recordTool({
5999
+ name,
6000
+ parentId,
6001
+ toolName,
6002
+ input: event.toolCall.input,
6003
+ metadata: this.options.metadata,
6004
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
6005
+ durationMs,
6006
+ startedAt: (0, vercel_ai_events_1.subtractMs)(endedAt, durationMs),
6007
+ endedAt,
6008
+ ...outcome
6009
+ });
6010
+ this.coverParent(parentId, endedAt);
6011
+ }
6012
+ };
6013
+ exports.VercelAIRun = VercelAIRun;
6014
+ }
6015
+ });
6016
+
6017
+ // ../../packages/ts/tracing/dist/vercel-ai.js
6018
+ var require_vercel_ai = __commonJS({
6019
+ "../../packages/ts/tracing/dist/vercel-ai.js"(exports) {
6020
+ "use strict";
6021
+ Object.defineProperty(exports, "__esModule", { value: true });
6022
+ exports.CANCELLED_METADATA_KEY = void 0;
6023
+ exports.vercelAI = vercelAI;
6024
+ var integration_client_1 = require_integration_client();
6025
+ var vercel_ai_events_1 = require_vercel_ai_events();
6026
+ var vercel_ai_run_1 = require_vercel_ai_run();
6027
+ var vercel_ai_run_2 = require_vercel_ai_run();
6028
+ Object.defineProperty(exports, "CANCELLED_METADATA_KEY", { enumerable: true, get: function() {
6029
+ return vercel_ai_run_2.CANCELLED_METADATA_KEY;
6030
+ } });
6031
+ var CONCURRENT_V6_WARNING = "@uselemma/tracing: vercelAI() received an AI SDK 6 run while another was in flight. AI SDK 6 sends no call ID, so the two runs' spans get mixed into one trace and some are dropped. Create one vercelAI() per concurrent AI SDK 6 call, or use AI SDK 7.";
6032
+ var CALL_EVENT_CALLBACKS = {
6033
+ onStepStart: true,
6034
+ onStepEnd: true,
6035
+ onStepFinish: true,
6036
+ onLanguageModelCallStart: true,
6037
+ onLanguageModelCallEnd: true,
6038
+ onToolExecutionStart: true,
6039
+ onToolCallStart: true,
6040
+ onToolExecutionEnd: true,
6041
+ onToolCallFinish: true,
6042
+ onFinish: true,
6043
+ onEnd: true,
6044
+ onAbort: true,
6045
+ onError: true
6046
+ };
6047
+ function resultCallId(result) {
6048
+ const steps = typeof result === "object" && result !== null ? result.steps : void 0;
6049
+ return Array.isArray(steps) ? (0, vercel_ai_events_1.runKey)(steps[0]) : void 0;
6050
+ }
6051
+ function vercelAI(options = {}) {
6052
+ const getLemma = (0, integration_client_1.integrationClientGetter)("vercelAI()", options);
6053
+ const pending = /* @__PURE__ */ new Set();
6054
+ const runs = /* @__PURE__ */ new Map();
6055
+ let runsOpened = 0;
6056
+ const claims = /* @__PURE__ */ new WeakMap();
6057
+ let lastPrimitiveClaim;
6058
+ let warnedConcurrentV6 = false;
6059
+ function trackPending(delivery) {
6060
+ pending.add(delivery);
6061
+ void delivery.finally(() => pending.delete(delivery));
6062
+ }
6063
+ function newRun(key) {
6064
+ runsOpened += 1;
6065
+ const run = new vercel_ai_run_1.VercelAIRun({
6066
+ options,
6067
+ getLemma,
6068
+ trackPending,
6069
+ release: () => {
6070
+ if (runs.get(key) === run)
6071
+ runs.delete(key);
6072
+ },
6073
+ claim: (value) => {
6074
+ if (typeof value === "object" && value !== null) {
6075
+ claims.set(value, run);
6076
+ } else if (value !== void 0) {
6077
+ lastPrimitiveClaim = { value, run };
5214
6078
  }
5215
6079
  }
5216
- const resolved = resolveTrace(event);
5217
- if (!resolved)
5218
- return;
5219
- const { trace } = resolved;
5220
- if (generationSpanIdsByCallId.has(event.callId)) {
5221
- modelCalls.set(event.callId, { event, startedAt: /* @__PURE__ */ new Date() });
5222
- return;
6080
+ });
6081
+ runs.set(key, run);
6082
+ return run;
6083
+ }
6084
+ function openRun(event) {
6085
+ const key = (0, vercel_ai_events_1.runKey)(event);
6086
+ return runs.get(key) ?? newRun(key);
6087
+ }
6088
+ function existingRun(event) {
6089
+ return runs.get((0, vercel_ai_events_1.runKey)(event));
6090
+ }
6091
+ function terminalRun(event) {
6092
+ return existingRun(event) ?? ((0, vercel_ai_run_1.endableTrace)(options) ? newRun((0, vercel_ai_events_1.runKey)(event)) : void 0);
6093
+ }
6094
+ function onlyRunEver() {
6095
+ return runsOpened === 1 ? runs.values().next().value : void 0;
6096
+ }
6097
+ function claimant(value) {
6098
+ if (typeof value === "object" && value !== null)
6099
+ return claims.get(value);
6100
+ const primitive = lastPrimitiveClaim;
6101
+ return primitive && primitive.value === value ? primitive.run : void 0;
6102
+ }
6103
+ function startRun(event, signal) {
6104
+ const key = (0, vercel_ai_events_1.runKey)(event);
6105
+ const current = runs.get(key);
6106
+ current?.stopIfAborted();
6107
+ if (current?.phase === "active") {
6108
+ if (key === vercel_ai_events_1.UNKEYED_RUN && !warnedConcurrentV6) {
6109
+ console.warn(CONCURRENT_V6_WARNING);
6110
+ warnedConcurrentV6 = true;
5223
6111
  }
5224
- const startedAt = /* @__PURE__ */ new Date();
5225
- const name = typeof options.generationName === "function" ? options.generationName({
5226
- callId: event.callId,
5227
- provider: event.provider,
5228
- modelId: event.modelId,
5229
- content: [],
5230
- performance: {}
5231
- }) : options.generationName ?? "vercel-ai-generation";
5232
- const handle = trace.startGeneration({
5233
- name,
5234
- input: event.messages,
5235
- metadata: options.metadata,
5236
- attributes: withIntegrationAttrs(),
5237
- model: event.modelId,
5238
- startedAt,
5239
- llmProvider: event.provider,
5240
- llmInputMessages: event.messages,
5241
- llmTools: event.tools
5242
- });
5243
- modelCalls.set(event.callId, { event, startedAt, handle });
5244
- generationSpanIdsByCallId.set(event.callId, handle.id);
5245
- trackGeneration(handle);
5246
- },
6112
+ return void 0;
6113
+ }
6114
+ void current?.deliver();
6115
+ const run = newRun(key);
6116
+ run.start(event, signal);
6117
+ return run;
6118
+ }
6119
+ const integration = {
6120
+ onStart(event) {
6121
+ startRun(event);
6122
+ },
6123
+ onStepStart(event) {
6124
+ openRun(event).stepStart(event);
6125
+ },
6126
+ // AI SDK 7 sends each step end to onStepEnd and to the deprecated
6127
+ // onStepFinish; the first ends the step's open generation and the second
6128
+ // finds nothing left to end.
6129
+ onStepEnd(event) {
6130
+ existingRun(event)?.stepEnd(event);
6131
+ },
6132
+ onStepFinish(event) {
6133
+ existingRun(event)?.stepEnd(event);
6134
+ },
6135
+ onLanguageModelCallStart(event) {
6136
+ openRun(event).modelCallStart(event);
6137
+ },
5247
6138
  onLanguageModelCallEnd(event) {
5248
- if (phase !== "active" && phase !== "ending")
5249
- return;
5250
- const stored = modelCalls.get(event.callId);
5251
- modelCalls.delete(event.callId);
5252
- if (!stored?.handle)
5253
- return;
5254
- const endedAt = /* @__PURE__ */ new Date();
5255
- const durationMs = resolveDurationMs(stored.startedAt, endedAt, event.performance.responseTimeMs);
5256
- const output = structuredAssistantOutput(void 0, event.content);
5257
- stored.handle.end({
5258
- output,
5259
- model: event.modelId,
5260
- durationMs,
5261
- endedAt: addMs(stored.startedAt, durationMs),
5262
- llmProvider: event.provider,
5263
- llmOutputMessages: output === void 0 ? void 0 : [{ role: "assistant", content: output }],
5264
- usage: eventUsage(event)
5265
- });
6139
+ existingRun(event)?.modelCallEnd(event);
5266
6140
  },
6141
+ // A tool event with no run in flight trails a run already sent.
5267
6142
  onToolExecutionStart(event) {
5268
- const resolved = resolveTrace();
5269
- if (!resolved)
5270
- return;
5271
- const { trace } = resolved;
5272
- const parentId = resolveToolParentId(event.callId, event.toolCall.toolCallId);
5273
- const name = typeof options.toolName === "function" ? options.toolName({
5274
- ...event,
5275
- toolExecutionMs: void 0,
5276
- toolOutput: { type: "tool-result" }
5277
- }) : options.toolName ?? event.toolCall.toolName;
5278
- const startedAt = /* @__PURE__ */ new Date();
5279
- const handle = trace.startTool({
5280
- name,
5281
- parentId,
5282
- input: event.toolCall.input,
5283
- metadata: options.metadata,
5284
- attributes: withIntegrationAttrs(),
5285
- startedAt,
5286
- toolName: event.toolCall.toolName
5287
- });
5288
- if (event.toolCall.toolCallId) {
5289
- toolExecutions.set(event.toolCall.toolCallId, {
5290
- handle,
5291
- startedAt,
5292
- parentId
5293
- });
5294
- }
6143
+ existingRun(event)?.toolStart(event);
5295
6144
  },
5296
6145
  onToolCallStart(event) {
5297
- integration.onToolExecutionStart?.(event);
6146
+ existingRun(event)?.toolStart(event);
5298
6147
  },
5299
6148
  onToolExecutionEnd(event) {
5300
- const resolved = resolveTrace();
5301
- if (!resolved)
5302
- return;
5303
- const { trace } = resolved;
5304
- const name = typeof options.toolName === "function" ? options.toolName(event) : options.toolName ?? event.toolCall.toolName;
5305
- const storedTool = event.toolCall.toolCallId ? toolExecutions.get(event.toolCall.toolCallId) : void 0;
5306
- if (event.toolCall.toolCallId) {
5307
- toolExecutions.delete(event.toolCall.toolCallId);
5308
- }
5309
- if (storedTool) {
5310
- const endedAt2 = addMs(storedTool.startedAt, event.toolExecutionMs);
5311
- const durationMs2 = resolveDurationMs(storedTool.startedAt, endedAt2, event.toolExecutionMs);
5312
- storedTool.handle.end({
5313
- durationMs: durationMs2,
5314
- endedAt: addMs(storedTool.startedAt, durationMs2),
5315
- toolName: event.toolCall.toolName,
5316
- ...toolOutput2(event)
5317
- });
5318
- coverParent(storedTool.parentId, addMs(storedTool.startedAt, durationMs2));
5319
- return;
5320
- }
5321
- const endedAt = /* @__PURE__ */ new Date();
5322
- const startedAt = subtractMs(endedAt, event.toolExecutionMs);
5323
- const durationMs = resolveDurationMs(startedAt, endedAt, event.toolExecutionMs);
5324
- const parentId = resolveToolParentId(event.callId, event.toolCall.toolCallId);
5325
- trace.recordTool({
5326
- name,
5327
- parentId,
5328
- toolName: event.toolCall.toolName,
5329
- input: event.toolCall.input,
5330
- metadata: options.metadata,
5331
- attributes: withIntegrationAttrs(),
5332
- durationMs,
5333
- startedAt: subtractMs(endedAt, durationMs),
5334
- endedAt,
5335
- ...toolOutput2(event)
5336
- });
5337
- coverParent(parentId, endedAt);
6149
+ existingRun(event)?.toolEnd(event);
5338
6150
  },
5339
- onStart(event) {
5340
- beginNewRun();
5341
- recordedV6Step = false;
5342
- const key = `start:${v6Starts.length}:${Date.now()}`;
5343
- v6Starts.push({ event, startedAt: /* @__PURE__ */ new Date(), key });
5344
- resolveTrace(event);
6151
+ onToolCallFinish(event) {
6152
+ existingRun(event)?.v6ToolEnd(event);
5345
6153
  },
5346
- onStepStart(event) {
5347
- if (isV7StepStart(event)) {
5348
- startV7Generation(event);
5349
- return;
5350
- }
5351
- const key = `step:${event.stepNumber}`;
5352
- if (v6Steps.has(key)) {
5353
- return;
5354
- }
5355
- const stored = startV6Generation(event, key);
5356
- if (stored)
5357
- v6Steps.set(key, stored);
6154
+ onFinish(event) {
6155
+ terminalRun(event)?.finish(event);
5358
6156
  },
5359
- onStepEnd(event) {
5360
- if (phase !== "active" && phase !== "ending")
5361
- return;
5362
- endV7Generation(event);
6157
+ onEnd(event) {
6158
+ terminalRun(event)?.end(event);
5363
6159
  },
5364
- onStepFinish(event) {
5365
- if (phase !== "active" && phase !== "ending")
5366
- return;
5367
- recordedV6Step = true;
5368
- const key = `step:${event.stepNumber}`;
5369
- const stored = v6Steps.get(key);
5370
- v6Steps.delete(key);
5371
- recordV6Generation(event, stored);
6160
+ // Neither handler awaits delivery: the AI SDK awaits them before it
6161
+ // closes the stream or rethrows to the caller.
6162
+ onAbort(event) {
6163
+ terminalRun(event)?.abort(event.reason);
5372
6164
  },
5373
- async onFinish(event) {
5374
- if (phase === "idle") {
5375
- if (!hasExplicitEndableTrace())
5376
- return;
5377
- beginActivity();
5378
- }
5379
- if (phase === "active") {
5380
- if (recordedV6Step) {
5381
- v6Starts.shift();
5382
- recordedV6Step = false;
5383
- } else {
5384
- recordV6Generation(event, v6Starts.shift());
5385
- }
5386
- }
5387
- await endOwnedTrace(event);
5388
- },
5389
- async onEnd(event) {
5390
- if (phase === "idle") {
5391
- if (!hasExplicitEndableTrace())
5392
- return;
5393
- beginActivity();
5394
- }
5395
- await endOwnedTrace(event);
5396
- },
5397
- onToolCallFinish(event) {
5398
- const resolved = resolveTrace();
5399
- if (!resolved)
5400
- return;
5401
- const { trace } = resolved;
5402
- const name = typeof options.toolName === "function" ? options.toolName(event) : options.toolName ?? event.toolCall.toolName;
5403
- const storedTool = event.toolCall.toolCallId ? toolExecutions.get(event.toolCall.toolCallId) : void 0;
5404
- if (event.toolCall.toolCallId) {
5405
- toolExecutions.delete(event.toolCall.toolCallId);
5406
- }
5407
- if (storedTool) {
5408
- const endedAt2 = addMs(storedTool.startedAt, event.durationMs);
5409
- const durationMs2 = resolveDurationMs(storedTool.startedAt, endedAt2, event.durationMs);
5410
- const toolEndedAt = addMs(storedTool.startedAt, durationMs2);
5411
- storedTool.handle.end({
5412
- durationMs: durationMs2,
5413
- endedAt: toolEndedAt,
5414
- toolName: event.toolCall.toolName,
5415
- ...v6ToolOutput(event)
5416
- });
5417
- coverParent(storedTool.parentId, toolEndedAt);
5418
- return;
5419
- }
5420
- const endedAt = /* @__PURE__ */ new Date();
5421
- const durationMs = resolveDurationMs(subtractMs(endedAt, event.durationMs), endedAt, event.durationMs);
5422
- const startedAt = subtractMs(endedAt, durationMs);
5423
- const parentId = resolveToolParentId(void 0, event.toolCall.toolCallId);
5424
- trace.recordTool({
5425
- name,
5426
- parentId,
5427
- toolName: event.toolCall.toolName,
5428
- input: event.toolCall.input,
5429
- metadata: options.metadata,
5430
- attributes: withIntegrationAttrs(),
5431
- durationMs,
5432
- startedAt,
5433
- endedAt,
5434
- ...v6ToolOutput(event)
5435
- });
5436
- coverParent(parentId, endedAt);
6165
+ onError(event) {
6166
+ openRun(event).stop((0, vercel_ai_events_1.reportedError)(event));
5437
6167
  },
5438
6168
  async fail(error) {
5439
- const message = (0, error_message_1.describeError)(error);
5440
- runError = message;
5441
- if (phase === "ending") {
5442
- endingTrace?.fail(message);
5443
- endingTrace?.output(void 0);
5444
- return;
5445
- }
5446
- if (phase === "idle") {
5447
- beginActivity();
5448
- }
5449
- await endOwnedTrace({ error });
5450
- if (deliverOwnedTrace)
5451
- await deliverOwnedTrace();
6169
+ const run = claimant(error) ?? runs.get(vercel_ai_events_1.UNKEYED_RUN) ?? onlyRunEver() ?? ((0, vercel_ai_events_1.isCallerStop)(error) && !(0, vercel_ai_run_1.endableTrace)(options) ? void 0 : newRun(vercel_ai_events_1.UNKEYED_RUN));
6170
+ run?.stop(error);
6171
+ await run?.deliver();
5452
6172
  },
5453
- recordResult,
6173
+ recordResult(result) {
6174
+ const key = resultCallId(result);
6175
+ const run = key ? runs.get(key) : runs.get(vercel_ai_events_1.UNKEYED_RUN) ?? onlyRunEver();
6176
+ if (run)
6177
+ return run.recordResult(result);
6178
+ return options.trace?.applyGenerationUsage(result) ?? 0;
6179
+ },
6180
+ // Each ended run's delivery waits a macrotask for its caller's
6181
+ // recordResult(); flushing early would send other requests' runs first.
5454
6182
  async flush() {
5455
- if (deliverOwnedTrace)
5456
- await deliverOwnedTrace();
5457
6183
  await Promise.all(Array.from(pending));
5458
6184
  },
5459
6185
  async shutdown() {
5460
- if (phase === "active") {
5461
- await endOwnedTrace({});
5462
- }
6186
+ for (const run of [...runs.values()])
6187
+ run.close();
5463
6188
  await integration.flush();
5464
- resetRunState();
6189
+ },
6190
+ withAbortSignal(signal) {
6191
+ const opened = /* @__PURE__ */ new Map();
6192
+ const callbacks = {
6193
+ onStart(event) {
6194
+ const run = startRun(event, signal);
6195
+ if (run)
6196
+ opened.set((0, vercel_ai_events_1.runKey)(event), run);
6197
+ }
6198
+ };
6199
+ for (const name of Object.keys(CALL_EVENT_CALLBACKS)) {
6200
+ const callback = integration[name];
6201
+ callbacks[name] = (event) => {
6202
+ if (opened.get((0, vercel_ai_events_1.runKey)(event))?.phase !== "sent") {
6203
+ return callback(event);
6204
+ }
6205
+ };
6206
+ }
6207
+ return callbacks;
5465
6208
  }
5466
6209
  };
5467
6210
  return integration;
@@ -5474,7 +6217,7 @@ var require_dist = __commonJS({
5474
6217
  "../../packages/ts/tracing/dist/index.js"(exports) {
5475
6218
  "use strict";
5476
6219
  Object.defineProperty(exports, "__esModule", { value: true });
5477
- exports.vercelAI = exports.openAIAgents = exports.mastra = exports.LemmaMastraExporter = exports.langGraph = exports.langChain = exports.LemmaLangChainCallbackHandler = exports.LangChainCallbackHandler = exports.lemmaDebug = exports.isDebugVerifyEnabled = exports.isDebugModeEnabled = exports.enableDebugMode = exports.disableDebugMode = exports.RELEASE_MAX_LENGTH = exports.normalizeRelease = exports.startCodingAgentTurn = exports.recordCodingAgentToolStart = exports.recordCodingAgentToolResult = exports.completeCodingAgentTurn = exports.codingAgentTurnTrace = exports.TurnHandle = exports.TURN_JOURNAL_VERSION = exports.TURN_CONTEXT_VERSION = exports.AttachedTurn = exports.AttachedSpanHandle = exports.startTurn = exports.parseTurnContextToken = exports.assembleTurn = exports.applyTurnJournal = exports.attachTurn = exports.toWireTokenUsage = exports.normalizeTokenUsage = exports.attachResultUsage = exports.TraceHandle = exports.TraceContext = exports.SpanHandle = exports.NoopSpanHandle = exports.Lemma = void 0;
6220
+ exports.vercelAI = exports.openAIAgents = exports.mastra = exports.LemmaMastraExporter = exports.langGraph = exports.langChain = exports.LemmaLangChainCallbackHandler = exports.LangChainCallbackHandler = exports.lemmaDebug = exports.isDebugVerifyEnabled = exports.isDebugModeEnabled = exports.enableDebugMode = exports.disableDebugMode = exports.RELEASE_MAX_LENGTH = exports.normalizeRelease = exports.IngestError = exports.startCodingAgentTurn = exports.recordCodingAgentToolStart = exports.recordCodingAgentToolResult = exports.completeCodingAgentTurn = exports.codingAgentTurnTrace = exports.TurnHandle = exports.TURN_JOURNAL_VERSION = exports.TURN_CONTEXT_VERSION = exports.AttachedTurn = exports.AttachedSpanHandle = exports.startTurn = exports.parseTurnContextToken = exports.assembleTurn = exports.applyTurnJournal = exports.attachTurn = exports.toWireTokenUsage = exports.normalizeTokenUsage = exports.attachResultUsage = exports.TraceHandle = exports.TraceContext = exports.SpanHandle = exports.NoopSpanHandle = exports.Lemma = void 0;
5478
6221
  var client_1 = require_client();
5479
6222
  Object.defineProperty(exports, "Lemma", { enumerable: true, get: function() {
5480
6223
  return client_1.Lemma;
@@ -5547,6 +6290,10 @@ var require_dist = __commonJS({
5547
6290
  Object.defineProperty(exports, "startCodingAgentTurn", { enumerable: true, get: function() {
5548
6291
  return coding_agent_1.startCodingAgentTurn;
5549
6292
  } });
6293
+ var delivery_1 = require_delivery();
6294
+ Object.defineProperty(exports, "IngestError", { enumerable: true, get: function() {
6295
+ return delivery_1.IngestError;
6296
+ } });
5550
6297
  var release_1 = require_release();
5551
6298
  Object.defineProperty(exports, "normalizeRelease", { enumerable: true, get: function() {
5552
6299
  return release_1.normalizeRelease;
@@ -5604,29 +6351,446 @@ var require_dist = __commonJS({
5604
6351
  // src/adapter.ts
5605
6352
  var import_tracing = __toESM(require_dist(), 1);
5606
6353
 
5607
- // src/pending.ts
5608
- import { randomUUID } from "node:crypto";
5609
- import { chmod as chmod2, mkdir as mkdir2, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
6354
+ // ../../packages/ts/tracing/src/coding-agent-queue.ts
6355
+ import { randomUUID as randomUUID2 } from "node:crypto";
6356
+ import {
6357
+ chmod,
6358
+ mkdir as mkdir2,
6359
+ readFile as readFile2,
6360
+ rename as rename2,
6361
+ rm as rm2,
6362
+ stat as stat2,
6363
+ unlink as unlink2,
6364
+ writeFile as writeFile2
6365
+ } from "node:fs/promises";
5610
6366
  import { join as join2 } from "node:path";
5611
6367
 
5612
- // src/storage.ts
5613
- import { existsSync, readFileSync } from "node:fs";
6368
+ // ../../packages/ts/tracing/src/coding-agent-backlog.ts
6369
+ import { createHash, randomUUID } from "node:crypto";
5614
6370
  import {
5615
- chmod,
5616
6371
  mkdir,
5617
6372
  readFile,
6373
+ readdir,
5618
6374
  rename,
6375
+ rm,
6376
+ stat,
5619
6377
  unlink,
5620
6378
  writeFile
5621
6379
  } from "node:fs/promises";
5622
- import { homedir } from "node:os";
5623
- import { dirname, join, resolve } from "node:path";
5624
- var LEMMA_OPENCODE_CREDENTIALS_HELP = "Lemma OpenCode credentials are missing or invalid. Run `pnpm dlx @uselemma/opencode setup` to connect or rotate the scoped credential.";
6380
+ import { dirname, join } from "node:path";
6381
+
6382
+ // ../../packages/ts/tracing/src/coding-agent-delivery.ts
6383
+ function createDeliveryFetch(fetchImplementation, remainingMilliseconds) {
6384
+ return async (request, init) => {
6385
+ const controller = new AbortController();
6386
+ const signal = init?.signal ? AbortSignal.any([init.signal, controller.signal]) : controller.signal;
6387
+ let timeout;
6388
+ const timedOut = new Promise((_, reject) => {
6389
+ timeout = setTimeout(() => {
6390
+ controller.abort();
6391
+ const error = new Error("Lemma trace delivery timed out");
6392
+ error.name = "TimeoutError";
6393
+ reject(error);
6394
+ }, remainingMilliseconds);
6395
+ });
6396
+ const requestAndBody = (async () => {
6397
+ const response = await fetchImplementation(request, { ...init, signal });
6398
+ if (response.ok || !response.body) return response;
6399
+ const body = await response.arrayBuffer();
6400
+ return new Response(body, {
6401
+ status: response.status,
6402
+ statusText: response.statusText,
6403
+ headers: response.headers
6404
+ });
6405
+ })();
6406
+ try {
6407
+ return await Promise.race([requestAndBody, timedOut]);
6408
+ } finally {
6409
+ if (timeout) clearTimeout(timeout);
6410
+ }
6411
+ };
6412
+ }
6413
+ var TraceDeliveryError = class extends Error {
6414
+ status;
6415
+ constructor(status, cause) {
6416
+ super(
6417
+ status !== void 0 ? `Lemma answered HTTP ${status}` : cause instanceof Error && cause.name === "TimeoutError" ? "the request to Lemma timed out" : "Lemma could not be reached",
6418
+ { cause }
6419
+ );
6420
+ this.name = "TraceDeliveryError";
6421
+ this.status = status;
6422
+ }
6423
+ };
6424
+ function rejectedCredentialStatus(error) {
6425
+ if (!(error instanceof TraceDeliveryError)) return void 0;
6426
+ const { status } = error;
6427
+ return status === 401 || status === 403 ? status : void 0;
6428
+ }
6429
+ async function deliverTrace(fetchImplementation, send) {
6430
+ let status;
6431
+ try {
6432
+ await send(async (request, init) => {
6433
+ const response = await fetchImplementation(request, init);
6434
+ status = response.status;
6435
+ return response;
6436
+ });
6437
+ } catch (error) {
6438
+ throw new TraceDeliveryError(status, error);
6439
+ }
6440
+ }
6441
+
6442
+ // ../../packages/ts/tracing/src/coding-agent-backlog.ts
5625
6443
  function isRecord(value) {
5626
6444
  return typeof value === "object" && value !== null && !Array.isArray(value);
5627
6445
  }
6446
+ async function removeIfPresent(path) {
6447
+ return unlink(path).then(
6448
+ () => true,
6449
+ (error) => {
6450
+ if (error.code === "ENOENT") return false;
6451
+ throw error;
6452
+ }
6453
+ );
6454
+ }
6455
+ async function pendingEntryNames(dataDir) {
6456
+ return readdir(join(dataDir, "pending")).then((entries) => entries.filter((name) => name.endsWith(".json")).sort()).catch((error) => {
6457
+ if (error.code === "ENOENT") return [];
6458
+ throw error;
6459
+ });
6460
+ }
6461
+ var MAX_PENDING_TRACES = 200;
6462
+ var REJECTED_CREDENTIAL_FILE = "last-error.json";
6463
+ var DROPPED_TRACES_DIR = "dropped";
6464
+ var DROP_RECORD = /^dropped\/[0-9]+-[0-9a-f-]+\.json$/;
6465
+ function isRejectedCredential(value) {
6466
+ return isRecord(value) && value.version === 1 && typeof value.credentialId === "string" && (value.status === 401 || value.status === 403) && typeof value.rejectedAt === "string";
6467
+ }
6468
+ function isDroppedTraces(value) {
6469
+ return isRecord(value) && value.version === 1 && typeof value.count === "number";
6470
+ }
6471
+ async function writeState(dataDir, name, value) {
6472
+ const path = join(dataDir, name);
6473
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
6474
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
6475
+ await writeFile(temporaryPath, `${JSON.stringify(value)}
6476
+ `, {
6477
+ encoding: "utf8",
6478
+ mode: 384,
6479
+ flag: "wx"
6480
+ });
6481
+ await rename(temporaryPath, path);
6482
+ }
6483
+ async function readState(dataDir, name, isState) {
6484
+ try {
6485
+ const value = JSON.parse(
6486
+ await readFile(join(dataDir, name), "utf8")
6487
+ );
6488
+ return isState(value) ? value : null;
6489
+ } catch (error) {
6490
+ if (error.code === "ENOENT" || error instanceof SyntaxError) {
6491
+ return null;
6492
+ }
6493
+ throw error;
6494
+ }
6495
+ }
6496
+ async function stopOnRejectedCredential(dataDir, credentialId, error) {
6497
+ const status = rejectedCredentialStatus(error);
6498
+ if (!status) return false;
6499
+ await writeState(dataDir, REJECTED_CREDENTIAL_FILE, {
6500
+ version: 1,
6501
+ credentialId,
6502
+ status,
6503
+ rejectedAt: (/* @__PURE__ */ new Date()).toISOString()
6504
+ });
6505
+ return true;
6506
+ }
6507
+ async function dropOldestPendingEntries(dataDir, limit, options = {}) {
6508
+ const pendingDir = join(dataDir, "pending");
6509
+ const names = await pendingEntryNames(dataDir);
6510
+ if (names.length <= limit) return;
6511
+ const entries = await Promise.all(
6512
+ names.map(async (name) => ({
6513
+ name,
6514
+ modified: await stat(join(pendingDir, name)).then(
6515
+ (entry) => entry.mtimeMs,
6516
+ () => Number.POSITIVE_INFINITY
6517
+ )
6518
+ }))
6519
+ );
6520
+ entries.sort(
6521
+ (a, b) => a.modified - b.modified || a.name.localeCompare(b.name)
6522
+ );
6523
+ for (const { name } of entries.slice(0, entries.length - limit)) {
6524
+ const path = join(pendingDir, name);
6525
+ if (options.onDrop) {
6526
+ const value = await readFile(path, "utf8").then((text) => JSON.parse(text)).catch(() => null);
6527
+ const handled = value === null || await options.onDrop(value).then(
6528
+ () => true,
6529
+ () => false
6530
+ );
6531
+ if (!handled) continue;
6532
+ }
6533
+ if (await removeIfPresent(path)) options.counted?.();
6534
+ }
6535
+ }
6536
+ async function prepareFlush(dataDir, credentialId, options = {}) {
6537
+ const recorded = await readState(
6538
+ dataDir,
6539
+ REJECTED_CREDENTIAL_FILE,
6540
+ isRejectedCredential
6541
+ );
6542
+ const rejected = recorded?.credentialId === credentialId;
6543
+ if (recorded && !rejected) {
6544
+ await rm(join(dataDir, REJECTED_CREDENTIAL_FILE), { force: true });
6545
+ }
6546
+ let dropped = 0;
6547
+ try {
6548
+ await dropOldestPendingEntries(dataDir, MAX_PENDING_TRACES, {
6549
+ onDrop: options.onDrop,
6550
+ counted: () => {
6551
+ dropped += 1;
6552
+ }
6553
+ });
6554
+ } finally {
6555
+ if (dropped > 0) {
6556
+ await writeState(
6557
+ dataDir,
6558
+ `${DROPPED_TRACES_DIR}/${Date.now()}-${randomUUID()}.json`,
6559
+ { version: 1, count: dropped }
6560
+ );
6561
+ }
6562
+ }
6563
+ return rejected ? "rejected" : "ready";
6564
+ }
6565
+ async function readDropRecords(dataDir) {
6566
+ const records = await readdir(join(dataDir, DROPPED_TRACES_DIR)).then(
6567
+ (entries) => entries.map((name) => `${DROPPED_TRACES_DIR}/${name}`).filter((record) => DROP_RECORD.test(record)).sort()
6568
+ ).catch((error) => {
6569
+ if (error.code === "ENOENT") return [];
6570
+ throw error;
6571
+ });
6572
+ const values = await Promise.all(
6573
+ records.map((record) => readState(dataDir, record, isDroppedTraces))
6574
+ );
6575
+ return {
6576
+ count: values.reduce((sum, value) => sum + (value?.count ?? 0), 0),
6577
+ records: records.filter((_record, index) => values[index] !== null)
6578
+ };
6579
+ }
6580
+ async function readSessionStartNotice(dataDir, credentialId, options) {
6581
+ const [rejection, dropped] = await Promise.all([
6582
+ readState(dataDir, REJECTED_CREDENTIAL_FILE, isRejectedCredential),
6583
+ readDropRecords(dataDir)
6584
+ ]);
6585
+ const droppedNote = dropped.count > 0 ? `${dropped.count} older ${dropped.count === 1 ? "trace was" : "traces were"} dropped past the ${MAX_PENDING_TRACES}-trace backlog limit.` : "";
6586
+ if (rejection?.credentialId === credentialId) {
6587
+ return {
6588
+ kind: "rejected",
6589
+ id: `rejected:${rejection.rejectedAt}`,
6590
+ message: `Lemma stopped sending ${options.harness} traces: it rejected this plugin's key (HTTP ${rejection.status}), which happens when the key is revoked or the person who approved it leaves the organization. Run \`${options.setupCommand}\` to create a new key; traces queued until then are sent with it.${droppedNote ? ` ${droppedNote}` : ""}`,
6591
+ dropRecords: dropped.records
6592
+ };
6593
+ }
6594
+ if (dropped.count === 0) return null;
6595
+ return {
6596
+ kind: "dropped",
6597
+ id: `dropped:${createHash("sha256").update(dropped.records.join("\n")).digest("hex").slice(0, 16)}`,
6598
+ message: `Lemma could not send ${options.harness} traces for a while: ${droppedNote}`,
6599
+ dropRecords: dropped.records
6600
+ };
6601
+ }
6602
+ async function claimSessionStartNotice(dataDir, notice) {
6603
+ const removed = await Promise.all(
6604
+ notice.dropRecords.filter((record) => DROP_RECORD.test(record)).map((record) => removeIfPresent(join(dataDir, record)))
6605
+ );
6606
+ return notice.kind === "rejected" || removed.some(Boolean);
6607
+ }
6608
+
6609
+ // ../../packages/ts/tracing/src/coding-agent-queue.ts
6610
+ var DEFAULT_FLUSH_TIMEOUT_MS = 1e4;
6611
+ var FLUSH_LOCK_STALE_MS = 3e4;
6612
+ var FLUSH_LOCK_OWNER_FILE = "owner.json";
6613
+ async function readLockOwner(path) {
6614
+ try {
6615
+ const value = JSON.parse(await readFile2(path, "utf8"));
6616
+ if (isRecord(value) && typeof value.pid === "number" && Number.isInteger(value.pid) && value.pid > 0 && typeof value.id === "string" && value.id.length > 0) {
6617
+ return { pid: value.pid, id: value.id };
6618
+ }
6619
+ } catch (error) {
6620
+ if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) {
6621
+ throw error;
6622
+ }
6623
+ }
6624
+ return null;
6625
+ }
6626
+ function processIsRunning(pid) {
6627
+ try {
6628
+ process.kill(pid, 0);
6629
+ return true;
6630
+ } catch (error) {
6631
+ return error.code === "EPERM";
6632
+ }
6633
+ }
6634
+ async function acquireFlushLock(dataDir) {
6635
+ await mkdir2(dataDir, { recursive: true, mode: 448 });
6636
+ const lockPath = join2(dataDir, "flush.lock");
6637
+ const ownerPath = join2(lockPath, FLUSH_LOCK_OWNER_FILE);
6638
+ const owner = { pid: process.pid, id: randomUUID2() };
6639
+ for (let attempt = 0; attempt < 2; attempt += 1) {
6640
+ try {
6641
+ await mkdir2(lockPath, { mode: 448 });
6642
+ await writeFile2(ownerPath, `${JSON.stringify(owner)}
6643
+ `, {
6644
+ encoding: "utf8",
6645
+ mode: 384,
6646
+ flag: "wx"
6647
+ });
6648
+ return async () => {
6649
+ const currentOwner = await readLockOwner(ownerPath);
6650
+ if (currentOwner?.id === owner.id) {
6651
+ await rm2(lockPath, { recursive: true, force: true });
6652
+ }
6653
+ };
6654
+ } catch (error) {
6655
+ if (error.code !== "EEXIST") throw error;
6656
+ if (attempt > 0) return null;
6657
+ const currentOwner = await readLockOwner(ownerPath);
6658
+ if (currentOwner && processIsRunning(currentOwner.pid)) return null;
6659
+ const lockStat = await stat2(lockPath).catch((statError) => {
6660
+ if (statError.code === "ENOENT") return null;
6661
+ throw statError;
6662
+ });
6663
+ if (lockStat && Date.now() - lockStat.mtimeMs <= FLUSH_LOCK_STALE_MS) {
6664
+ return null;
6665
+ }
6666
+ const quarantinePath = join2(dataDir, `flush.lock.stale-${randomUUID2()}`);
6667
+ try {
6668
+ await rename2(lockPath, quarantinePath);
6669
+ } catch (claimError) {
6670
+ if (claimError.code === "ENOENT") {
6671
+ return null;
6672
+ }
6673
+ throw claimError;
6674
+ }
6675
+ await rm2(quarantinePath, { recursive: true, force: true });
6676
+ }
6677
+ }
6678
+ return null;
6679
+ }
6680
+ function isPendingTurn(value, harness) {
6681
+ return isRecord(value) && value.version === 1 && typeof value.apiUrl === "string" && typeof value.projectId === "string" && typeof value.credentialId === "string" && isRecord(value.turn) && value.turn.harness === harness && value.turn.status === "completed";
6682
+ }
6683
+ async function writePendingTurn(dataDir, turn, scope) {
6684
+ const pendingDir = join2(dataDir, "pending");
6685
+ await mkdir2(pendingDir, { recursive: true, mode: 448 });
6686
+ if (process.platform !== "win32") await chmod(pendingDir, 448);
6687
+ const path = join2(
6688
+ pendingDir,
6689
+ `${turn.endedAt.replaceAll(/[^0-9]/g, "")}-${turn.traceId}-${randomUUID2()}.json`
6690
+ );
6691
+ const temporaryPath = `${path}.${process.pid}.${randomUUID2()}.tmp`;
6692
+ const pending = {
6693
+ version: 1,
6694
+ apiUrl: scope.apiUrl,
6695
+ projectId: scope.projectId,
6696
+ credentialId: scope.credentialId,
6697
+ turn
6698
+ };
6699
+ await writeFile2(temporaryPath, `${JSON.stringify(pending)}
6700
+ `, {
6701
+ encoding: "utf8",
6702
+ mode: 384,
6703
+ flag: "wx"
6704
+ });
6705
+ if (process.platform !== "win32") await chmod(temporaryPath, 384);
6706
+ await rename2(temporaryPath, path);
6707
+ }
6708
+ async function flushPendingTurns(options) {
6709
+ const now = options.now ?? Date.now;
6710
+ const pendingDir = join2(options.dataDir, "pending");
6711
+ let sent = 0;
6712
+ const attempted = /* @__PURE__ */ new Set();
6713
+ while (true) {
6714
+ const releaseLock = await acquireFlushLock(options.dataDir);
6715
+ if (!releaseLock) return sent;
6716
+ try {
6717
+ const credentials = await options.credentials();
6718
+ if (!credentials) return sent;
6719
+ if (await prepareFlush(options.dataDir, credentials.credentialId) === "rejected") {
6720
+ return sent;
6721
+ }
6722
+ for (const name of (await pendingEntryNames(options.dataDir)).filter(
6723
+ (entry) => !attempted.has(entry)
6724
+ )) {
6725
+ const remainingMilliseconds = options.deadline - now();
6726
+ if (remainingMilliseconds <= 0) return sent;
6727
+ attempted.add(name);
6728
+ const path = join2(pendingDir, name);
6729
+ const pending = await readFile2(path, "utf8").then((text) => JSON.parse(text)).catch(() => null);
6730
+ if (!isPendingTurn(pending, options.harness)) {
6731
+ options.retained(name, { kind: "invalid" });
6732
+ continue;
6733
+ }
6734
+ if (pending.apiUrl !== credentials.apiUrl || pending.projectId !== credentials.projectId) {
6735
+ options.retained(name, { kind: "otherProject" });
6736
+ continue;
6737
+ }
6738
+ try {
6739
+ await options.send(pending.turn, credentials, remainingMilliseconds);
6740
+ await unlink2(path);
6741
+ sent += 1;
6742
+ } catch (error) {
6743
+ options.retained(name, { kind: "failed", error });
6744
+ if (await stopOnRejectedCredential(
6745
+ options.dataDir,
6746
+ credentials.credentialId,
6747
+ error
6748
+ )) {
6749
+ return sent;
6750
+ }
6751
+ }
6752
+ }
6753
+ } finally {
6754
+ await releaseLock();
6755
+ }
6756
+ const remaining = await pendingEntryNames(options.dataDir);
6757
+ if (!remaining.some((entry) => !attempted.has(entry))) return sent;
6758
+ }
6759
+ }
6760
+ function retainedReason(error) {
6761
+ if (error instanceof SyntaxError) return "the queued trace is not valid JSON";
6762
+ return error instanceof Error ? error.message : String(error);
6763
+ }
6764
+ function describeRetained(reason) {
6765
+ switch (reason.kind) {
6766
+ case "invalid":
6767
+ return "it is not a valid queued trace";
6768
+ case "otherProject":
6769
+ return "it belongs to another Lemma project";
6770
+ case "failed":
6771
+ return retainedReason(reason.error);
6772
+ }
6773
+ }
6774
+
6775
+ // src/storage.ts
6776
+ import { existsSync, readFileSync } from "node:fs";
6777
+ import {
6778
+ chmod as chmod2,
6779
+ mkdir as mkdir3,
6780
+ readFile as readFile3,
6781
+ rename as rename3,
6782
+ unlink as unlink3,
6783
+ writeFile as writeFile3
6784
+ } from "node:fs/promises";
6785
+ import { homedir } from "node:os";
6786
+ import { dirname as dirname2, join as join3, resolve } from "node:path";
6787
+ var LEMMA_OPENCODE_SETUP_COMMAND = "pnpm dlx @uselemma/opencode setup";
6788
+ var LEMMA_OPENCODE_CREDENTIALS_HELP = `Lemma OpenCode credentials are missing or invalid. Run \`${LEMMA_OPENCODE_SETUP_COMMAND}\` to connect or rotate the scoped credential.`;
6789
+ function isRecord2(value) {
6790
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6791
+ }
5628
6792
  function isCredentials(value) {
5629
- return isRecord(value) && value.version === 1 && typeof value.apiUrl === "string" && value.apiUrl.length > 0 && typeof value.projectId === "string" && value.projectId.length > 0 && typeof value.credentialId === "string" && value.credentialId.length > 0 && typeof value.accessToken === "string" && value.accessToken.length > 0;
6793
+ return isRecord2(value) && value.version === 1 && typeof value.apiUrl === "string" && value.apiUrl.length > 0 && typeof value.projectId === "string" && value.projectId.length > 0 && typeof value.credentialId === "string" && value.credentialId.length > 0 && typeof value.accessToken === "string" && value.accessToken.length > 0;
5630
6794
  }
5631
6795
  function resolveConfigDir(options = {}) {
5632
6796
  if (options.configDir) return resolve(options.configDir);
@@ -5635,13 +6799,13 @@ function resolveConfigDir(options = {}) {
5635
6799
  if (configured) return resolve(configured);
5636
6800
  const home = options.homeDir ?? homedir();
5637
6801
  const xdgConfigHome = env.XDG_CONFIG_HOME?.trim();
5638
- return xdgConfigHome ? join(resolve(xdgConfigHome), "opencode") : join(resolve(home), ".config", "opencode");
6802
+ return xdgConfigHome ? join3(resolve(xdgConfigHome), "opencode") : join3(resolve(home), ".config", "opencode");
5639
6803
  }
5640
6804
  function defaultDataDir(options) {
5641
- return join(resolveConfigDir(options), "lemma");
6805
+ return join3(resolveConfigDir(options), "lemma");
5642
6806
  }
5643
6807
  function dataDirLocationPath(options) {
5644
- return join(defaultDataDir(options), "data-dir-location.json");
6808
+ return join3(defaultDataDir(options), "data-dir-location.json");
5645
6809
  }
5646
6810
  function resolveDataDir(options = {}) {
5647
6811
  if (options.dataDir) return resolve(options.dataDir);
@@ -5653,7 +6817,7 @@ function resolveDataDir(options = {}) {
5653
6817
  const value = JSON.parse(
5654
6818
  readFileSync(dataDirLocationPath(options), "utf8")
5655
6819
  );
5656
- if (isRecord(value) && value.version === 1 && typeof value.dataDir === "string" && value.dataDir.trim().length > 0) {
6820
+ if (isRecord2(value) && value.version === 1 && typeof value.dataDir === "string" && value.dataDir.trim().length > 0) {
5657
6821
  return resolve(value.dataDir);
5658
6822
  }
5659
6823
  } catch (error) {
@@ -5662,12 +6826,12 @@ function resolveDataDir(options = {}) {
5662
6826
  return fallback;
5663
6827
  }
5664
6828
  function credentialsPath(options = {}) {
5665
- return join(resolveDataDir(options), "credentials.json");
6829
+ return join3(resolveDataDir(options), "credentials.json");
5666
6830
  }
5667
6831
  async function readCredentials(options = {}) {
5668
6832
  try {
5669
6833
  const value = JSON.parse(
5670
- await readFile(credentialsPath(options), "utf8")
6834
+ await readFile3(credentialsPath(options), "utf8")
5671
6835
  );
5672
6836
  if (!isCredentials(value)) throw new Error(LEMMA_OPENCODE_CREDENTIALS_HELP);
5673
6837
  return value;
@@ -5681,36 +6845,8 @@ async function readCredentials(options = {}) {
5681
6845
  }
5682
6846
 
5683
6847
  // src/pending.ts
5684
- function isPendingOpenCodeTurn(value) {
5685
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
5686
- return false;
5687
- }
5688
- const pending = value;
5689
- const turn = pending.turn;
5690
- return pending.version === 1 && typeof pending.apiUrl === "string" && typeof pending.projectId === "string" && typeof pending.credentialId === "string" && typeof turn === "object" && turn !== null && !Array.isArray(turn) && turn.harness === "opencode" && turn.status === "completed";
5691
- }
5692
- async function writePendingTurn(turn, scope, options = {}) {
5693
- const pendingDir = join2(resolveDataDir(options), "pending");
5694
- await mkdir2(pendingDir, { recursive: true, mode: 448 });
5695
- if (process.platform !== "win32") await chmod2(pendingDir, 448);
5696
- const entry = `${turn.endedAt.replaceAll(/[^0-9]/g, "")}-${turn.traceId}-${randomUUID()}.json`;
5697
- const path = join2(pendingDir, entry);
5698
- const temporaryPath = `${path}.tmp`;
5699
- const pending = {
5700
- version: 1,
5701
- apiUrl: scope.apiUrl,
5702
- projectId: scope.projectId,
5703
- credentialId: scope.credentialId,
5704
- turn
5705
- };
5706
- await writeFile2(temporaryPath, `${JSON.stringify(pending)}
5707
- `, {
5708
- encoding: "utf8",
5709
- mode: 384,
5710
- flag: "wx"
5711
- });
5712
- if (process.platform !== "win32") await chmod2(temporaryPath, 384);
5713
- await rename2(temporaryPath, path);
6848
+ async function writePendingTurn2(turn, scope, options = {}) {
6849
+ await writePendingTurn(resolveDataDir(options), turn, scope);
5714
6850
  return true;
5715
6851
  }
5716
6852
 
@@ -5761,7 +6897,7 @@ var PEM_BLOCK = /-----BEGIN [A-Z0-9 ]*(?:PRIVATE KEY|CERTIFICATE)-----[\s\S]*?(?
5761
6897
  var PROVIDER_TOKEN = /\b(?:sk-(?:ant-)?[A-Za-z0-9_-]{16,}|sk_(?:live|test)_[A-Za-z0-9]{12,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|xox[baprs]-[A-Za-z0-9-]{16,}|npm_[A-Za-z0-9]{16,}|AIza[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16}|lemma_[A-Za-z0-9_-]{16,})\b/g;
5762
6898
  var JWT_TOKEN = /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\b/g;
5763
6899
  var CREDENTIAL_BEARING_URL = /\b([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/:@]+:[^\s/@]+@/gi;
5764
- function isRecord2(value) {
6900
+ function isRecord3(value) {
5765
6901
  return typeof value === "object" && value !== null && !Array.isArray(value);
5766
6902
  }
5767
6903
  function normalizedKey(key) {
@@ -5785,7 +6921,7 @@ function sanitizeValue(value, depth = 0) {
5785
6921
  if (Array.isArray(value)) {
5786
6922
  return value.slice(0, 200).map((item) => sanitizeValue(item, depth + 1));
5787
6923
  }
5788
- if (!isRecord2(value)) return String(value).slice(0, 2e4);
6924
+ if (!isRecord3(value)) return String(value).slice(0, 2e4);
5789
6925
  const sanitized = {};
5790
6926
  for (const [key, item] of Object.entries(value).slice(0, 200)) {
5791
6927
  if (isSensitiveKey(key)) continue;
@@ -5898,7 +7034,7 @@ function createOpenCodeAdapter(dependencies) {
5898
7034
  const finalizingTurns = /* @__PURE__ */ new Map();
5899
7035
  const now = dependencies.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
5900
7036
  const scheduleFlush = dependencies.scheduleFlush ?? (() => void 0);
5901
- const writePending = dependencies.writePending ?? writePendingTurn;
7037
+ const writePending = dependencies.writePending ?? writePendingTurn2;
5902
7038
  const warn = dependencies.warn ?? ((message) => console.warn(message));
5903
7039
  async function sessionMessages(sessionId) {
5904
7040
  const result = await dependencies.client.session.messages({
@@ -6098,53 +7234,11 @@ function createOpenCodeAdapter(dependencies) {
6098
7234
 
6099
7235
  // src/flush.ts
6100
7236
  var import_tracing2 = __toESM(require_dist(), 1);
6101
- import { randomUUID as randomUUID2 } from "node:crypto";
6102
- import {
6103
- mkdir as mkdir3,
6104
- readFile as readFile2,
6105
- readdir,
6106
- rename as rename3,
6107
- rm,
6108
- stat,
6109
- unlink as unlink2,
6110
- writeFile as writeFile3
6111
- } from "node:fs/promises";
6112
- import { join as join3 } from "node:path";
6113
-
6114
- // src/delivery.ts
6115
- function createDeliveryFetch(fetchImplementation, remainingMilliseconds) {
6116
- return async (request, init) => {
6117
- const controller = new AbortController();
6118
- const signal = init?.signal ? AbortSignal.any([init.signal, controller.signal]) : controller.signal;
6119
- let timeout;
6120
- const timedOut = new Promise((_, reject) => {
6121
- timeout = setTimeout(() => {
6122
- controller.abort();
6123
- reject(new Error("Lemma OpenCode trace delivery timed out"));
6124
- }, remainingMilliseconds);
6125
- });
6126
- const requestAndBody = (async () => {
6127
- const response = await fetchImplementation(request, { ...init, signal });
6128
- if (response.ok || !response.body) return response;
6129
- const body = await response.arrayBuffer();
6130
- return new Response(body, {
6131
- status: response.status,
6132
- statusText: response.statusText,
6133
- headers: response.headers
6134
- });
6135
- })();
6136
- try {
6137
- return await Promise.race([requestAndBody, timedOut]);
6138
- } finally {
6139
- if (timeout) clearTimeout(timeout);
6140
- }
6141
- };
6142
- }
6143
7237
 
6144
7238
  // package.json
6145
7239
  var package_default = {
6146
7240
  name: "@uselemma/opencode",
6147
- version: "0.1.3",
7241
+ version: "0.2.0",
6148
7242
  description: "Lemma SDK tracing for OpenCode coding-agent sessions",
6149
7243
  license: "MIT",
6150
7244
  author: "Lemma",
@@ -6205,145 +7299,53 @@ var package_default = {
6205
7299
  var PLUGIN_USER_AGENT = `${package_default.name}/${package_default.version}`;
6206
7300
 
6207
7301
  // src/flush.ts
6208
- var FLUSH_LOCK_STALE_MS = 3e4;
6209
- var FLUSH_LOCK_OWNER_FILE = "owner.json";
6210
- var DEFAULT_FLUSH_TIMEOUT_MS = 1e4;
6211
- function isRecord3(value) {
6212
- return typeof value === "object" && value !== null && !Array.isArray(value);
6213
- }
6214
- async function readLockOwner(path) {
6215
- try {
6216
- const value = JSON.parse(await readFile2(path, "utf8"));
6217
- if (isRecord3(value) && typeof value.pid === "number" && Number.isInteger(value.pid) && value.pid > 0 && typeof value.id === "string" && value.id.length > 0) {
6218
- return { pid: value.pid, id: value.id };
6219
- }
6220
- } catch (error) {
6221
- if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) {
6222
- throw error;
6223
- }
6224
- }
6225
- return null;
6226
- }
6227
- function processIsRunning(pid) {
6228
- try {
6229
- process.kill(pid, 0);
6230
- return true;
6231
- } catch (error) {
6232
- return error.code === "EPERM";
6233
- }
6234
- }
6235
- async function acquireFlushLock(dataDir) {
6236
- await mkdir3(dataDir, { recursive: true, mode: 448 });
6237
- const lockPath = join3(dataDir, "flush.lock");
6238
- const ownerPath = join3(lockPath, FLUSH_LOCK_OWNER_FILE);
6239
- const owner = { pid: process.pid, id: randomUUID2() };
6240
- for (let attempt = 0; attempt < 2; attempt += 1) {
6241
- try {
6242
- await mkdir3(lockPath, { mode: 448 });
6243
- await writeFile3(ownerPath, `${JSON.stringify(owner)}
6244
- `, {
6245
- encoding: "utf8",
6246
- mode: 384,
6247
- flag: "wx"
6248
- });
6249
- return async () => {
6250
- const currentOwner = await readLockOwner(ownerPath);
6251
- if (currentOwner?.id === owner.id) {
6252
- await rm(lockPath, { recursive: true, force: true });
6253
- }
6254
- };
6255
- } catch (error) {
6256
- if (error.code !== "EEXIST") throw error;
6257
- if (attempt > 0) return null;
6258
- const currentOwner = await readLockOwner(ownerPath);
6259
- if (currentOwner && processIsRunning(currentOwner.pid)) return null;
6260
- const lockStat = await stat(lockPath).catch((statError) => {
6261
- if (statError.code === "ENOENT") return null;
6262
- throw statError;
6263
- });
6264
- if (lockStat && Date.now() - lockStat.mtimeMs <= FLUSH_LOCK_STALE_MS) {
6265
- return null;
6266
- }
6267
- const quarantinePath = join3(dataDir, `flush.lock.stale-${randomUUID2()}`);
6268
- try {
6269
- await rename3(lockPath, quarantinePath);
6270
- } catch (claimError) {
6271
- if (claimError.code === "ENOENT") {
6272
- return null;
6273
- }
6274
- throw claimError;
6275
- }
6276
- await rm(quarantinePath, { recursive: true, force: true });
6277
- }
6278
- }
6279
- return null;
6280
- }
6281
- async function pendingEntryNames(dataDir) {
6282
- return readdir(join3(dataDir, "pending")).then((entries) => entries.filter((name) => name.endsWith(".json")).sort()).catch((error) => {
6283
- if (error.code === "ENOENT") return [];
6284
- throw error;
6285
- });
7302
+ async function startupNotice(options = {}) {
7303
+ const dataDir = resolveDataDir(options);
7304
+ const credentials = await readCredentials({ ...options, dataDir });
7305
+ if (!credentials) return null;
7306
+ const notice = await readSessionStartNotice(
7307
+ dataDir,
7308
+ credentials.credentialId,
7309
+ { harness: "OpenCode", setupCommand: LEMMA_OPENCODE_SETUP_COMMAND }
7310
+ );
7311
+ if (!notice || !await claimSessionStartNotice(dataDir, notice)) return null;
7312
+ return notice.message;
6286
7313
  }
6287
- async function flushPendingTurns(options = {}) {
7314
+ async function flushPendingTurns2(options = {}) {
6288
7315
  const dataDir = resolveDataDir(options);
6289
7316
  const now = options.now ?? Date.now;
6290
- const deadline = options.deadline ?? now() + (options.timeoutMilliseconds ?? DEFAULT_FLUSH_TIMEOUT_MS);
6291
- let sent = 0;
6292
- const attemptedEntries = /* @__PURE__ */ new Set();
6293
- while (true) {
6294
- const releaseLock = await acquireFlushLock(dataDir);
6295
- if (!releaseLock) return sent;
6296
- try {
7317
+ return flushPendingTurns({
7318
+ dataDir,
7319
+ harness: "opencode",
7320
+ now,
7321
+ deadline: options.deadline ?? now() + (options.timeoutMilliseconds ?? DEFAULT_FLUSH_TIMEOUT_MS),
7322
+ credentials: async () => {
6297
7323
  const credentials = await readCredentials({ ...options, dataDir });
6298
7324
  if (!credentials) throw new Error(LEMMA_OPENCODE_CREDENTIALS_HELP);
6299
- const pendingDir = join3(dataDir, "pending");
6300
- for (const entry of (await pendingEntryNames(dataDir)).filter(
6301
- (name) => !attemptedEntries.has(name)
6302
- )) {
6303
- const remainingMilliseconds = deadline - now();
6304
- if (remainingMilliseconds <= 0) return sent;
6305
- attemptedEntries.add(entry);
6306
- const path = join3(pendingDir, entry);
6307
- try {
6308
- const pending = JSON.parse(await readFile2(path, "utf8"));
6309
- if (!isPendingOpenCodeTurn(pending)) {
6310
- throw new Error("invalid pending turn");
6311
- }
6312
- if (pending.apiUrl !== credentials.apiUrl || pending.projectId !== credentials.projectId) {
6313
- throw new Error(
6314
- "pending turn belongs to a different scoped credential"
6315
- );
6316
- }
6317
- const trace = (0, import_tracing2.codingAgentTurnTrace)(pending.turn);
6318
- await new import_tracing2.Lemma({
6319
- apiKey: credentials.accessToken,
6320
- projectId: credentials.projectId,
6321
- baseUrl: credentials.apiUrl,
6322
- fetch: createDeliveryFetch(
6323
- options.fetch ?? fetch,
6324
- remainingMilliseconds
6325
- ),
6326
- userAgent: PLUGIN_USER_AGENT
6327
- }).ingest(trace.context, {
6328
- startedAt: new Date(trace.startedAt),
6329
- endedAt: new Date(trace.endedAt)
6330
- });
6331
- await unlink2(path);
6332
- sent += 1;
6333
- } catch {
6334
- options.warn?.(
6335
- `Lemma OpenCode retained a trace for retry (${entry}).`
6336
- );
6337
- }
6338
- }
6339
- } finally {
6340
- await releaseLock();
6341
- }
6342
- const remainingEntries = await pendingEntryNames(dataDir);
6343
- if (!remainingEntries.some((entry) => !attemptedEntries.has(entry))) {
6344
- return sent;
7325
+ return credentials;
7326
+ },
7327
+ send: async (turn, credentials, remainingMilliseconds) => {
7328
+ const trace = (0, import_tracing2.codingAgentTurnTrace)(turn);
7329
+ await deliverTrace(
7330
+ createDeliveryFetch(options.fetch ?? fetch, remainingMilliseconds),
7331
+ (deliveryFetch) => new import_tracing2.Lemma({
7332
+ apiKey: credentials.accessToken,
7333
+ projectId: credentials.projectId,
7334
+ baseUrl: credentials.apiUrl,
7335
+ fetch: deliveryFetch,
7336
+ userAgent: PLUGIN_USER_AGENT
7337
+ }).ingest(trace.context, {
7338
+ startedAt: new Date(trace.startedAt),
7339
+ endedAt: new Date(trace.endedAt)
7340
+ })
7341
+ );
7342
+ },
7343
+ retained: (name, reason) => {
7344
+ options.warn?.(
7345
+ `Lemma OpenCode retained a trace for retry (${name}): ${describeRetained(reason)}.`
7346
+ );
6345
7347
  }
6346
- }
7348
+ });
6347
7349
  }
6348
7350
 
6349
7351
  // src/plugin-entry.ts
@@ -6358,7 +7360,7 @@ var LemmaPlugin = async ({ client, directory }) => {
6358
7360
  flushPromise = (async () => {
6359
7361
  do {
6360
7362
  flushRequested = false;
6361
- await flushPendingTurns({ warn, deadline });
7363
+ await flushPendingTurns2({ warn, deadline });
6362
7364
  } while (flushRequested && !disposing);
6363
7365
  })().catch((error) => {
6364
7366
  console.warn(
@@ -6379,6 +7381,11 @@ var LemmaPlugin = async ({ client, directory }) => {
6379
7381
  scheduleFlush
6380
7382
  });
6381
7383
  scheduleFlush();
7384
+ void startupNotice().then(async (message) => {
7385
+ if (!message) return;
7386
+ const result = await client.tui?.showToast({ body: { message, variant: "warning" } }).catch(() => void 0);
7387
+ if (result?.data !== true) warn(message);
7388
+ }).catch(() => void 0);
6382
7389
  return {
6383
7390
  "chat.message": async (_input, output) => {
6384
7391
  await adapter.chatMessage(output.message, output.parts);