@uselemma/opencode 0.1.3 → 0.2.1

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
@@ -38,9 +38,8 @@ var require_debug_delivery = __commonJS({
38
38
  "../../packages/ts/tracing/dist/debug-delivery.js"(exports) {
39
39
  "use strict";
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
- exports.INGEST_STATUS_POLL_TIMEOUT_MS = exports.INGEST_STATUS_POLL_INTERVAL_MS = exports.EXPECTED_INGEST_SUCCESS_STATUS = exports.INGEST_STATUS_PATH = exports.INGEST_PATH = exports.PRODUCTION_BASE_URL = void 0;
42
- exports.isSuccessfulIngestStatus = isSuccessfulIngestStatus;
43
- exports.parseIngestStatus = parseIngestStatus;
41
+ exports.EXPECTED_INGEST_SUCCESS_STATUS = exports.INGEST_PATH = exports.PRODUCTION_BASE_URL = void 0;
42
+ exports.smokeTestConfirmHint = smokeTestConfirmHint;
44
43
  exports.isValidProjectId = isValidProjectId;
45
44
  exports.apiKeySuffix = apiKeySuffix;
46
45
  exports.buildConfigWarnings = buildConfigWarnings;
@@ -48,23 +47,9 @@ var require_debug_delivery = __commonJS({
48
47
  exports.pickResponseHeadersFromRecord = pickResponseHeadersFromRecord;
49
48
  exports.PRODUCTION_BASE_URL = "https://api.uselemma.ai";
50
49
  exports.INGEST_PATH = "/traces/ingest";
51
- exports.INGEST_STATUS_PATH = "/traces/ingest-status";
52
50
  exports.EXPECTED_INGEST_SUCCESS_STATUS = 201;
53
- exports.INGEST_STATUS_POLL_INTERVAL_MS = 1e3;
54
- exports.INGEST_STATUS_POLL_TIMEOUT_MS = 15e3;
55
- var SUCCESS_INGEST_STATUSES = /* @__PURE__ */ new Set([
56
- "enqueued",
57
- "ingested",
58
- "ready"
59
- ]);
60
- function isSuccessfulIngestStatus(status) {
61
- return status != null && SUCCESS_INGEST_STATUSES.has(status);
62
- }
63
- function parseIngestStatus(value) {
64
- if (value === "enqueued" || value === "ingested" || value === "ready" || value === "not_found") {
65
- return value;
66
- }
67
- return null;
51
+ function smokeTestConfirmHint(traceId) {
52
+ return `ingest returned 201; confirm it arrived on your project's Traces page in the Lemma dashboard (trace lemma-debug-smoke-test, ID ${traceId})`;
68
53
  }
69
54
  var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
70
55
  function isValidProjectId(projectId) {
@@ -107,19 +92,38 @@ var require_debug_delivery = __commonJS({
107
92
  }
108
93
  });
109
94
 
95
+ // ../../packages/ts/tracing/dist/env.js
96
+ var require_env = __commonJS({
97
+ "../../packages/ts/tracing/dist/env.js"(exports) {
98
+ "use strict";
99
+ Object.defineProperty(exports, "__esModule", { value: true });
100
+ exports.readEnv = readEnv;
101
+ function readEnv(read) {
102
+ try {
103
+ return read();
104
+ } catch {
105
+ return void 0;
106
+ }
107
+ }
108
+ }
109
+ });
110
+
110
111
  // ../../packages/ts/tracing/dist/debug-mode.js
111
112
  var require_debug_mode = __commonJS({
112
113
  "../../packages/ts/tracing/dist/debug-mode.js"(exports) {
113
114
  "use strict";
114
115
  Object.defineProperty(exports, "__esModule", { value: true });
116
+ exports.DEBUG_VERIFY_REMOVED_MESSAGE = void 0;
115
117
  exports.enableDebugMode = enableDebugMode;
116
118
  exports.disableDebugMode = disableDebugMode;
117
119
  exports.isDebugModeEnabled = isDebugModeEnabled;
118
120
  exports.isDebugVerifyEnabled = isDebugVerifyEnabled;
121
+ exports.noteDebugVerifyRemovedOnce = noteDebugVerifyRemovedOnce;
122
+ exports.resetDebugVerifyNotice = resetDebugVerifyNotice;
119
123
  exports.lemmaDebug = lemmaDebug;
124
+ var env_1 = require_env();
120
125
  var debugModeEnabled = false;
121
- function isEnvFlagEnabled(name) {
122
- const value = process.env[name];
126
+ function isFlagOn(value) {
123
127
  return value === "1" || value === "true";
124
128
  }
125
129
  function enableDebugMode() {
@@ -129,10 +133,21 @@ var require_debug_mode = __commonJS({
129
133
  debugModeEnabled = false;
130
134
  }
131
135
  function isDebugModeEnabled() {
132
- return debugModeEnabled || isEnvFlagEnabled("LEMMA_DEBUG");
136
+ return debugModeEnabled || isFlagOn((0, env_1.readEnv)(() => process.env.LEMMA_DEBUG));
133
137
  }
134
138
  function isDebugVerifyEnabled() {
135
- return isEnvFlagEnabled("LEMMA_DEBUG_VERIFY");
139
+ return isFlagOn((0, env_1.readEnv)(() => process.env.LEMMA_DEBUG_VERIFY));
140
+ }
141
+ exports.DEBUG_VERIFY_REMOVED_MESSAGE = `arrival verification was removed, so LEMMA_DEBUG_VERIFY makes no request. A "trace sent" line with status 201 means Lemma ingest accepted the trace; confirm it on your project's Traces page in the Lemma dashboard.`;
142
+ var debugVerifyRemovedNoted = false;
143
+ function noteDebugVerifyRemovedOnce() {
144
+ if (debugVerifyRemovedNoted || !isDebugModeEnabled())
145
+ return;
146
+ debugVerifyRemovedNoted = true;
147
+ lemmaDebug("verify", exports.DEBUG_VERIFY_REMOVED_MESSAGE);
148
+ }
149
+ function resetDebugVerifyNotice() {
150
+ debugVerifyRemovedNoted = false;
136
151
  }
137
152
  function lemmaDebug(prefix, msg, data) {
138
153
  if (!isDebugModeEnabled())
@@ -154,6 +169,7 @@ var require_error_message = __commonJS({
154
169
  exports.errorMessage = errorMessage;
155
170
  exports.describeError = describeError;
156
171
  exports.failureMessage = failureMessage;
172
+ exports.failOpenGenerations = failOpenGenerations;
157
173
  function errorMessage(error) {
158
174
  if (error == null)
159
175
  return null;
@@ -224,6 +240,12 @@ var require_error_message = __commonJS({
224
240
  }
225
241
  }
226
242
  var GENERIC_ERROR_NAME = "Error";
243
+ function failOpenGenerations(handles, runError, endedAt) {
244
+ if (!runError)
245
+ return;
246
+ for (const handle of handles)
247
+ handle?.failUnfinished(runError, endedAt);
248
+ }
227
249
  }
228
250
  });
229
251
 
@@ -232,7 +254,7 @@ var require_delivery = __commonJS({
232
254
  "../../packages/ts/tracing/dist/delivery.js"(exports) {
233
255
  "use strict";
234
256
  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;
257
+ 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
258
  exports.ingestFailureHint = ingestFailureHint;
237
259
  exports.isRetryableIngestStatus = isRetryableIngestStatus;
238
260
  exports.parseRetryAfterMs = parseRetryAfterMs;
@@ -247,10 +269,30 @@ var require_delivery = __commonJS({
247
269
  exports.INGEST_STRICT_ATTEMPTS = 1;
248
270
  exports.INGEST_MAX_ATTEMPTS = 3;
249
271
  exports.INGEST_REQUEST_TIMEOUT_MS = 1e4;
272
+ exports.AWAITED_INGEST_REQUEST_TIMEOUT_MS = 4e3;
273
+ exports.AWAITED_INGEST_TOTAL_TIMEOUT_MS = 1e4;
250
274
  exports.INGEST_RETRY_BASE_DELAY_MS = 500;
251
275
  exports.INGEST_RETRY_MAX_DELAY_MS = 2e3;
252
- function ingestFailureHint(status) {
276
+ var IngestError = class extends Error {
277
+ /** The HTTP status ingest answered with. */
278
+ status;
279
+ /** Whether resending the same payload can succeed (408, 429 and 5xx). */
280
+ retryable;
281
+ /** The response body, often JSON with a `detail` naming the problem. */
282
+ body;
283
+ constructor(status, body) {
284
+ super(`@uselemma/tracing: failed to ingest trace (${status})${body ? `: ${body}` : ""}`);
285
+ this.name = "IngestError";
286
+ this.status = status;
287
+ this.retryable = isRetryableIngestStatus(status);
288
+ this.body = body;
289
+ }
290
+ };
291
+ exports.IngestError = IngestError;
292
+ function ingestFailureHint(status, body) {
253
293
  switch (status) {
294
+ case 400:
295
+ return responseDetail(body) ?? "ingest rejected the payload as invalid";
254
296
  case 401:
255
297
  return "check LEMMA_API_KEY";
256
298
  case 403:
@@ -263,6 +305,15 @@ var require_delivery = __commonJS({
263
305
  return void 0;
264
306
  }
265
307
  }
308
+ function responseDetail(body) {
309
+ try {
310
+ const parsed = JSON.parse(body);
311
+ const detail = typeof parsed === "object" && parsed !== null && "detail" in parsed ? parsed.detail : void 0;
312
+ return typeof detail === "string" && detail ? detail : void 0;
313
+ } catch {
314
+ return void 0;
315
+ }
316
+ }
266
317
  function isRetryableIngestStatus(status) {
267
318
  return status === 408 || status === 429 || status >= 500;
268
319
  }
@@ -277,19 +328,34 @@ var require_delivery = __commonJS({
277
328
  const jittered = backoff / 2 + random() * (backoff / 2);
278
329
  return Math.min(exports.INGEST_RETRY_MAX_DELAY_MS, Math.max(jittered, retryAfterMs ?? 0));
279
330
  }
331
+ exports.AWAITED_DELIVERY = {
332
+ maxAttempts: exports.INGEST_MAX_ATTEMPTS,
333
+ requestTimeoutMs: exports.AWAITED_INGEST_REQUEST_TIMEOUT_MS,
334
+ totalTimeoutMs: exports.AWAITED_INGEST_TOTAL_TIMEOUT_MS
335
+ };
336
+ exports.BACKGROUND_DELIVERY = {
337
+ maxAttempts: exports.INGEST_MAX_ATTEMPTS,
338
+ requestTimeoutMs: exports.INGEST_REQUEST_TIMEOUT_MS,
339
+ totalTimeoutMs: Number.POSITIVE_INFINITY
340
+ };
341
+ exports.STRICT_DELIVERY = {
342
+ maxAttempts: exports.INGEST_STRICT_ATTEMPTS,
343
+ requestTimeoutMs: exports.INGEST_REQUEST_TIMEOUT_MS,
344
+ totalTimeoutMs: Number.POSITIVE_INFINITY
345
+ };
280
346
  function sleep(ms) {
281
347
  return new Promise((resolve2) => setTimeout(resolve2, ms));
282
348
  }
283
- async function withIngestTimeout(run) {
349
+ async function withIngestTimeout(run, timeoutMs = exports.INGEST_REQUEST_TIMEOUT_MS) {
284
350
  const controller = new AbortController();
285
351
  let timer;
286
352
  const timedOut = new Promise((_, reject) => {
287
353
  timer = setTimeout(() => {
288
- const error = new Error(`ingest request timed out after ${exports.INGEST_REQUEST_TIMEOUT_MS}ms`);
354
+ const error = new Error(`ingest request timed out after ${timeoutMs}ms`);
289
355
  error.name = "TimeoutError";
290
356
  controller.abort(error);
291
357
  reject(error);
292
- }, exports.INGEST_REQUEST_TIMEOUT_MS);
358
+ }, timeoutMs);
293
359
  });
294
360
  try {
295
361
  return await Promise.race([run(controller.signal), timedOut]);
@@ -300,21 +366,34 @@ var require_delivery = __commonJS({
300
366
  function failedBeforeSending(error) {
301
367
  return { ok: false, error, cause: `before sending: ${(0, error_message_1.describeError)(error)}` };
302
368
  }
303
- function failedAfter(attempts, attempt) {
369
+ function failedAfter(attempts, attempt, stop, totalTimeoutMs) {
370
+ const ceiling = stop === "ceiling" ? ` (${totalTimeoutMs}ms delivery ceiling reached)` : "";
304
371
  return {
305
372
  ok: false,
306
373
  error: attempt.error,
307
- cause: `after ${attempts} attempt${attempts === 1 ? "" : "s"}: ${attempt.reason}`
374
+ cause: `after ${attempts} attempt${attempts === 1 ? "" : "s"}: ${attempt.reason}${ceiling}`
308
375
  };
309
376
  }
310
- async function sendOnce(post, log) {
377
+ function stopReason(attempt, attempts, maxAttempts, timing) {
378
+ if (!attempt.retryable)
379
+ return "rejected";
380
+ const now = Date.now();
381
+ if (now >= timing.deadline)
382
+ return "ceiling";
383
+ if (attempts >= maxAttempts)
384
+ return "attempts";
385
+ if (now + timing.delayMs >= timing.deadline)
386
+ return "ceiling";
387
+ return void 0;
388
+ }
389
+ async function sendOnce(post, log, timeoutMs) {
311
390
  try {
312
391
  return await withIngestTimeout(async (signal) => {
313
392
  const response = await post(signal);
314
393
  if (response.ok)
315
394
  return { ok: true, response };
316
395
  const body = await response.text().catch(() => "");
317
- const hint = ingestFailureHint(response.status);
396
+ const hint = ingestFailureHint(response.status, body);
318
397
  (0, debug_mode_1.lemmaDebug)("client", "trace ingest failed", {
319
398
  ...log,
320
399
  status: response.status,
@@ -322,14 +401,15 @@ var require_delivery = __commonJS({
322
401
  ...(0, debug_delivery_1.pickResponseHeaders)(response.headers),
323
402
  ...hint ? { hint } : {}
324
403
  });
404
+ const error = new IngestError(response.status, body);
325
405
  return {
326
406
  ok: false,
327
- error: new Error(`@uselemma/tracing: failed to ingest trace (${response.status})${body ? `: ${body}` : ""}`),
407
+ error,
328
408
  reason: `ingest returned ${response.status}${hint ? ` (${hint})` : ""}`,
329
- retryable: isRetryableIngestStatus(response.status),
409
+ retryable: error.retryable,
330
410
  retryAfterMs: parseRetryAfterMs(response.headers.get("retry-after"))
331
411
  };
332
- });
412
+ }, timeoutMs);
333
413
  } catch (error) {
334
414
  (0, debug_mode_1.lemmaDebug)("client", "trace ingest failed", {
335
415
  ...log,
@@ -344,15 +424,21 @@ var require_delivery = __commonJS({
344
424
  };
345
425
  }
346
426
  }
347
- async function deliver(post, log, maxAttempts) {
427
+ async function deliver(post, log, budget) {
428
+ const { maxAttempts, requestTimeoutMs, totalTimeoutMs } = budget;
429
+ const deadline = Date.now() + totalTimeoutMs;
348
430
  for (let attempts = 1; ; attempts += 1) {
349
- const attempt = await sendOnce(post, log);
431
+ const timeoutMs = Math.min(requestTimeoutMs, deadline - Date.now());
432
+ const attempt = await sendOnce(post, log, timeoutMs);
350
433
  if (attempt.ok)
351
434
  return { ok: true, response: attempt.response };
352
- if (!attempt.retryable || attempts >= maxAttempts) {
353
- return failedAfter(attempts, attempt);
354
- }
355
435
  const delayMs = ingestRetryDelayMs(attempts, attempt.retryAfterMs);
436
+ const stop = stopReason(attempt, attempts, maxAttempts, {
437
+ deadline,
438
+ delayMs
439
+ });
440
+ if (stop)
441
+ return failedAfter(attempts, attempt, stop, totalTimeoutMs);
356
442
  (0, debug_mode_1.lemmaDebug)("client", "retrying trace ingest", {
357
443
  ...log,
358
444
  attempt: attempts,
@@ -426,6 +512,223 @@ var require_release = __commonJS({
426
512
  }
427
513
  });
428
514
 
515
+ // ../../packages/ts/tracing/dist/serialize.js
516
+ var require_serialize = __commonJS({
517
+ "../../packages/ts/tracing/dist/serialize.js"(exports) {
518
+ "use strict";
519
+ Object.defineProperty(exports, "__esModule", { value: true });
520
+ exports.TRACE_STRING_MAX_LENGTH = void 0;
521
+ exports.stringifyTraceJson = stringifyTraceJson;
522
+ function stringifyTraceJson(value) {
523
+ return JSON.stringify(toJsonSafe(value, "", []));
524
+ }
525
+ exports.TRACE_STRING_MAX_LENGTH = 65536;
526
+ function capString(value) {
527
+ if (value.length <= exports.TRACE_STRING_MAX_LENGTH)
528
+ return value;
529
+ let end = exports.TRACE_STRING_MAX_LENGTH;
530
+ const last = value.charCodeAt(end - 1);
531
+ if (last >= 55296 && last <= 56319)
532
+ end -= 1;
533
+ return `${value.slice(0, end)}\u2026[truncated ${value.length - end} chars]`;
534
+ }
535
+ function unserializable(value) {
536
+ return `[unserializable: ${typeName(value)}]`;
537
+ }
538
+ function typeName(value) {
539
+ try {
540
+ const name = value.constructor?.name;
541
+ return typeof name === "string" && name ? name : "Object";
542
+ } catch {
543
+ return "Object";
544
+ }
545
+ }
546
+ function binaryByteLength(value) {
547
+ if (value === null || typeof value !== "object")
548
+ return void 0;
549
+ if (ArrayBuffer.isView(value))
550
+ return value.byteLength;
551
+ const tag = Object.prototype.toString.call(value);
552
+ if (tag === "[object ArrayBuffer]" || tag === "[object SharedArrayBuffer]") {
553
+ const { byteLength } = value;
554
+ if (typeof byteLength === "number")
555
+ return byteLength;
556
+ }
557
+ if (typeof Blob !== "undefined" && value instanceof Blob)
558
+ return value.size;
559
+ return void 0;
560
+ }
561
+ function toJsonSafe(value, key, ancestors) {
562
+ let json;
563
+ try {
564
+ json = toJsonValue(value, key);
565
+ } catch {
566
+ return unserializable(value);
567
+ }
568
+ if (typeof json === "bigint")
569
+ return unserializable(json);
570
+ if (typeof json === "function" || typeof json === "symbol")
571
+ return void 0;
572
+ if (json === null || typeof json !== "object")
573
+ return json;
574
+ if (ancestors.includes(json))
575
+ return unserializable(json);
576
+ ancestors.push(json);
577
+ try {
578
+ return childrenToJsonSafe(json, ancestors);
579
+ } catch {
580
+ return unserializable(json);
581
+ } finally {
582
+ ancestors.pop();
583
+ }
584
+ }
585
+ function toJsonValue(value, key) {
586
+ if (value === null || typeof value !== "object" && typeof value !== "function" && typeof value !== "bigint") {
587
+ return compactLeaf(value);
588
+ }
589
+ if (binaryByteLength(value) !== void 0)
590
+ return compactLeaf(value);
591
+ const toJSON = value.toJSON;
592
+ const json = typeof toJSON === "function" ? toJSON.call(value, key) : value;
593
+ const unboxed = json instanceof Number || json instanceof String || json instanceof Boolean || json instanceof BigInt ? json.valueOf() : json;
594
+ return compactLeaf(unboxed);
595
+ }
596
+ function compactLeaf(value) {
597
+ if (typeof value === "string")
598
+ return capString(value);
599
+ const bytes = binaryByteLength(value);
600
+ return bytes === void 0 ? value : `[binary ${bytes} bytes]`;
601
+ }
602
+ function childrenToJsonSafe(json, ancestors) {
603
+ if (Array.isArray(json)) {
604
+ const items = [];
605
+ for (let index = 0; index < json.length; index += 1) {
606
+ items.push(toJsonSafe(json[index], String(index), ancestors));
607
+ }
608
+ return items;
609
+ }
610
+ const result = /* @__PURE__ */ Object.create(null);
611
+ for (const name of Object.keys(json)) {
612
+ result[name] = toJsonSafe(json[name], name, ancestors);
613
+ }
614
+ return result;
615
+ }
616
+ }
617
+ });
618
+
619
+ // ../../packages/ts/tracing/dist/stream-result.js
620
+ var require_stream_result = __commonJS({
621
+ "../../packages/ts/tracing/dist/stream-result.js"(exports) {
622
+ "use strict";
623
+ Object.defineProperty(exports, "__esModule", { value: true });
624
+ exports.wrapReturnedStream = wrapReturnedStream;
625
+ exports.holdTraceForStream = holdTraceForStream;
626
+ var debug_mode_1 = require_debug_mode();
627
+ function wrapReturnedStream(value) {
628
+ const kind = streamKind(value);
629
+ if (!kind)
630
+ return void 0;
631
+ let settle;
632
+ const ended = new Promise((resolve2) => {
633
+ settle = resolve2;
634
+ });
635
+ let finished = false;
636
+ const finish = (failure) => {
637
+ if (finished)
638
+ return;
639
+ finished = true;
640
+ settle(failure);
641
+ };
642
+ const stream = kind === "readable" ? readableEndingWith(value, finish) : iterate(value, finish);
643
+ return { stream, ended };
644
+ }
645
+ function holdTraceForStream(value, context, send) {
646
+ const wrapped = wrapReturnedStream(value);
647
+ if (!wrapped)
648
+ return void 0;
649
+ const sent = wrapped.ended.then((failure) => {
650
+ if (failure)
651
+ context.fail(failure.error);
652
+ return send();
653
+ });
654
+ (0, debug_mode_1.lemmaDebug)("client", "trace stays open until the returned stream ends", {
655
+ traceId: context.id
656
+ });
657
+ return { stream: wrapped.stream, sent };
658
+ }
659
+ function streamKind(value) {
660
+ if (typeof value !== "object" || value === null)
661
+ return void 0;
662
+ try {
663
+ if (typeof ReadableStream !== "undefined" && Object.getPrototypeOf(value) === ReadableStream.prototype && !value.locked) {
664
+ return "readable";
665
+ }
666
+ if (Object.prototype.toString.call(value) === "[object AsyncGenerator]") {
667
+ return "generator";
668
+ }
669
+ } catch {
670
+ }
671
+ return void 0;
672
+ }
673
+ function readableEndingWith(source, finish) {
674
+ const reader = source.getReader();
675
+ return new ReadableStream(
676
+ {
677
+ async pull(controller) {
678
+ const chunk = await reader.read().catch((error) => {
679
+ finish({ error });
680
+ throw error;
681
+ });
682
+ if (chunk.done) {
683
+ finish(void 0);
684
+ controller.close();
685
+ } else {
686
+ controller.enqueue(chunk.value);
687
+ }
688
+ },
689
+ async cancel(reason) {
690
+ finish(void 0);
691
+ await reader.cancel(reason);
692
+ }
693
+ },
694
+ // Reads from the source only when the caller reads.
695
+ { highWaterMark: 0 }
696
+ );
697
+ }
698
+ function iterate(source, finish) {
699
+ let started = false;
700
+ const wrapper = (async function* () {
701
+ started = true;
702
+ try {
703
+ return yield* source;
704
+ } catch (error) {
705
+ finish({ error });
706
+ throw error;
707
+ } finally {
708
+ finish(void 0);
709
+ }
710
+ })();
711
+ const close = wrapper.return;
712
+ const raise = wrapper.throw;
713
+ wrapper.return = async (value) => {
714
+ if (!started) {
715
+ finish(void 0);
716
+ await source.return(await value);
717
+ }
718
+ return close.call(wrapper, value);
719
+ };
720
+ wrapper.throw = async (error) => {
721
+ if (!started) {
722
+ finish({ error });
723
+ await source.return(void 0);
724
+ }
725
+ return raise.call(wrapper, error);
726
+ };
727
+ return wrapper;
728
+ }
729
+ }
730
+ });
731
+
429
732
  // ../../packages/ts/tracing/dist/usage.js
430
733
  var require_usage = __commonJS({
431
734
  "../../packages/ts/tracing/dist/usage.js"(exports) {
@@ -659,7 +962,7 @@ var require_version = __commonJS({
659
962
  "use strict";
660
963
  Object.defineProperty(exports, "__esModule", { value: true });
661
964
  exports.SDK_USER_AGENT = void 0;
662
- exports.SDK_USER_AGENT = "@uselemma/tracing/7.14.0";
965
+ exports.SDK_USER_AGENT = "@uselemma/tracing/7.15.1";
663
966
  }
664
967
  });
665
968
 
@@ -669,12 +972,16 @@ var require_client = __commonJS({
669
972
  "use strict";
670
973
  Object.defineProperty(exports, "__esModule", { value: true });
671
974
  exports.Lemma = exports.TraceHandle = exports.TraceContext = exports.NoopSpanHandle = exports.SpanHandle = exports.toWireTokenUsage = exports.normalizeTokenUsage = exports.attachResultUsage = void 0;
975
+ exports.startBackgroundTrace = startBackgroundTrace;
672
976
  var debug_delivery_1 = require_debug_delivery();
673
977
  var debug_mode_1 = require_debug_mode();
674
978
  var delivery_1 = require_delivery();
675
979
  var dropped_traces_1 = require_dropped_traces();
980
+ var env_1 = require_env();
676
981
  var error_message_1 = require_error_message();
677
982
  var release_1 = require_release();
983
+ var serialize_1 = require_serialize();
984
+ var stream_result_1 = require_stream_result();
678
985
  var usage_1 = require_usage();
679
986
  var version_1 = require_version();
680
987
  var usage_2 = require_usage();
@@ -733,11 +1040,7 @@ var require_client = __commonJS({
733
1040
  return value;
734
1041
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean")
735
1042
  return value;
736
- try {
737
- return JSON.stringify(value);
738
- } catch {
739
- return String(value);
740
- }
1043
+ return (0, serialize_1.stringifyTraceJson)(value);
741
1044
  }
742
1045
  function addDefined(attributes, key, value) {
743
1046
  if (value !== void 0)
@@ -840,6 +1143,12 @@ var require_client = __commonJS({
840
1143
  ...usage ? { usage } : {}
841
1144
  };
842
1145
  }
1146
+ function payloadBody(payload) {
1147
+ const body = (0, serialize_1.stringifyTraceJson)(payload);
1148
+ if (body === void 0)
1149
+ throw new Error("trace payload is empty");
1150
+ return body;
1151
+ }
843
1152
  function warnNoop(message) {
844
1153
  console.warn(`@uselemma/tracing: ${message}`);
845
1154
  }
@@ -891,6 +1200,19 @@ var require_client = __commonJS({
891
1200
  this.trace.spanEnded(this.payload);
892
1201
  this.trace.changed();
893
1202
  }
1203
+ /**
1204
+ * Close this span as failed if it is still open. A no-op once ended, so a
1205
+ * completed span is never rewritten. The end is never before the start.
1206
+ *
1207
+ * @internal
1208
+ */
1209
+ failUnfinished(error, endedAt) {
1210
+ if (this.ended)
1211
+ return;
1212
+ const startedMs = timestampMs(this.payload.started_at);
1213
+ const closedAt = startedMs != null && startedMs > endedAt.getTime() ? new Date(startedMs) : endedAt;
1214
+ this.end({ status: "ERROR", error, endedAt: closedAt });
1215
+ }
894
1216
  /**
895
1217
  * Fill input or output after end() when a child model call finishes later.
896
1218
  * Input is written only while this span still has none. Output is replaced
@@ -985,6 +1307,9 @@ var require_client = __commonJS({
985
1307
  id = "";
986
1308
  end() {
987
1309
  }
1310
+ /** @internal */
1311
+ failUnfinished(_error, _endedAt) {
1312
+ }
988
1313
  ensureEndedAt(_endedAt) {
989
1314
  }
990
1315
  startSpan() {
@@ -1017,8 +1342,11 @@ var require_client = __commonJS({
1017
1342
  onChange;
1018
1343
  spans = [];
1019
1344
  spanHandles = /* @__PURE__ */ new Map();
1020
- traceOutput;
1345
+ /** Boxed, so an output set to undefined still counts as set. */
1346
+ rootOutput;
1021
1347
  traceError = null;
1348
+ /** Set by {@link markPayloadFinal}; cleared by the first change after it. */
1349
+ sent = false;
1022
1350
  id;
1023
1351
  constructor(options, onChange) {
1024
1352
  this.options = options;
@@ -1026,16 +1354,24 @@ var require_client = __commonJS({
1026
1354
  this.options.name ??= "trace";
1027
1355
  this.options.id ??= crypto.randomUUID();
1028
1356
  this.id = this.options.id;
1029
- this.traceOutput = options.output;
1357
+ this.rootOutput = options.output === void 0 ? void 0 : { value: options.output };
1030
1358
  }
1031
1359
  input(value) {
1032
1360
  this.options.input = value;
1033
1361
  this.changed();
1034
1362
  }
1035
1363
  output(value) {
1036
- this.traceOutput = value;
1364
+ this.rootOutput = { value };
1037
1365
  this.changed();
1038
1366
  }
1367
+ /**
1368
+ * Whether the root output was set through options or `output()`.
1369
+ *
1370
+ * @internal
1371
+ */
1372
+ get hasOutput() {
1373
+ return this.rootOutput !== void 0;
1374
+ }
1039
1375
  threadId(value) {
1040
1376
  this.options.threadId = value;
1041
1377
  this.changed();
@@ -1070,8 +1406,25 @@ var require_client = __commonJS({
1070
1406
  return this.spans.some((span) => span.id === id);
1071
1407
  }
1072
1408
  changed() {
1409
+ if (this.sent) {
1410
+ this.sent = false;
1411
+ (0, debug_mode_1.lemmaDebug)("client", "trace changed after its final payload was built; not delivered", {
1412
+ traceId: this.id
1413
+ });
1414
+ }
1073
1415
  this.onChange?.();
1074
1416
  }
1417
+ /**
1418
+ * Marks that this trace's payload won't be built again: an automatic send
1419
+ * builds it once and never rebuilds it, and a strict send can be retried
1420
+ * with a rebuilt payload until it succeeds. Debug mode then logs the first
1421
+ * later change, which isn't delivered.
1422
+ *
1423
+ * @internal
1424
+ */
1425
+ markPayloadFinal() {
1426
+ this.sent = true;
1427
+ }
1075
1428
  setChangeHandler(onChange) {
1076
1429
  this.onChange = onChange;
1077
1430
  }
@@ -1166,7 +1519,7 @@ var require_client = __commonJS({
1166
1519
  id: this.options.id,
1167
1520
  name: this.options.name ?? "trace",
1168
1521
  input: this.options.input,
1169
- output: this.traceOutput,
1522
+ output: this.rootOutput?.value,
1170
1523
  metadata: this.options.metadata,
1171
1524
  thread_id: this.options.threadId,
1172
1525
  user_id: this.options.userId,
@@ -1183,43 +1536,62 @@ var require_client = __commonJS({
1183
1536
  exports.TraceContext = TraceContext;
1184
1537
  var TraceHandle = class extends TraceContext {
1185
1538
  sendFn;
1186
- sendPromise = Promise.resolve();
1187
- ended = false;
1539
+ /** The send `end()` started; cleared when a strict send fails. */
1540
+ sending;
1541
+ /** Set by the first `end()`; a retry reuses its output and root timing. */
1542
+ rootTiming;
1188
1543
  startedAt;
1189
1544
  constructor(options, sendFn, startedAt) {
1190
1545
  super(options);
1191
1546
  this.sendFn = sendFn;
1192
1547
  this.startedAt = startedAt ?? coerceDate(options.startedAt) ?? /* @__PURE__ */ new Date();
1193
1548
  }
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);
1549
+ end(outputOrOptions) {
1550
+ if (this.sending)
1551
+ return this.sending;
1552
+ this.rootTiming ??= this.applyEnd(outputOrOptions, arguments.length > 0);
1553
+ const { startedAt, endedAt } = this.rootTiming;
1554
+ const sending = this.startSend(startedAt, endedAt);
1555
+ this.sending = sending;
1556
+ sending.catch(() => {
1557
+ this.sending = void 0;
1558
+ });
1559
+ return sending;
1560
+ }
1561
+ /** Apply the first `end()`'s output and duration, and fix the root timing. */
1562
+ applyEnd(outputOrOptions, hasArgument) {
1563
+ if (!isTraceEndOptions(outputOrOptions)) {
1564
+ if (hasArgument)
1565
+ this.output(outputOrOptions);
1566
+ return { startedAt: this.startedAt, endedAt: /* @__PURE__ */ new Date() };
1567
+ }
1568
+ if ("output" in outputOrOptions)
1569
+ this.output(outputOrOptions.output);
1570
+ if (outputOrOptions.durationMs != null) {
1571
+ this.duration(outputOrOptions.durationMs);
1572
+ }
1573
+ return {
1574
+ startedAt: coerceDate(outputOrOptions.startedAt) ?? this.startedAt,
1575
+ endedAt: coerceDate(outputOrOptions.endedAt) ?? /* @__PURE__ */ new Date()
1576
+ };
1577
+ }
1578
+ /** A sendFn that throws synchronously rejects instead of throwing. */
1579
+ startSend(startedAt, endedAt) {
1580
+ try {
1581
+ return this.sendFn(this, startedAt, endedAt);
1582
+ } catch (error) {
1583
+ return Promise.reject(error);
1210
1584
  }
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;
1216
1585
  }
1217
- /** Whether this trace has already been delivered via `end()`. */
1586
+ /** Whether `end()` has sent this trace, or is sending it. */
1218
1587
  get isEnded() {
1219
- return this.ended;
1588
+ return this.sending !== void 0;
1220
1589
  }
1221
1590
  };
1222
1591
  exports.TraceHandle = TraceHandle;
1592
+ function startBackgroundTrace(lemma, options) {
1593
+ return lemma.startTrace(options, delivery_1.BACKGROUND_DELIVERY);
1594
+ }
1223
1595
  var Lemma2 = class {
1224
1596
  apiKey;
1225
1597
  projectId;
@@ -1229,22 +1601,26 @@ var require_client = __commonJS({
1229
1601
  baseHeaders;
1230
1602
  release;
1231
1603
  traces = /* @__PURE__ */ new Map();
1604
+ /** Sends in flight, and callback traces held open by a returned stream. */
1605
+ pending = /* @__PURE__ */ new Set();
1232
1606
  configLogged = false;
1233
1607
  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;
1608
+ this.apiKey = required(options.apiKey ?? (0, env_1.readEnv)(() => process.env.LEMMA_API_KEY), "LEMMA_API_KEY");
1609
+ this.projectId = required(options.projectId ?? (0, env_1.readEnv)(() => process.env.LEMMA_PROJECT_ID), "LEMMA_PROJECT_ID");
1610
+ this.baseUrl = (options.baseUrl ?? ((0, env_1.readEnv)(() => process.env.LEMMA_BASE_URL)?.trim() || debug_delivery_1.PRODUCTION_BASE_URL)).replace(/\/+$/, "");
1611
+ const customFetch = options.fetch;
1612
+ this.fetchImpl = (input, init) => (customFetch ?? fetch)(input, init);
1238
1613
  this.baseHeaders = {
1239
1614
  "User-Agent": options.userAgent ?? version_1.SDK_USER_AGENT,
1240
1615
  Authorization: `Bearer ${this.apiKey}`
1241
1616
  };
1242
- this.release = (0, release_1.normalizeRelease)(options.release ?? process.env.LEMMA_RELEASE);
1617
+ this.release = (0, release_1.normalizeRelease)(options.release ?? (0, env_1.readEnv)(() => process.env.LEMMA_RELEASE));
1243
1618
  this.logInitConfigOnce();
1244
1619
  }
1245
1620
  /**
1246
- * Run a one-call delivery diagnostic: config check, minimal ingest, and
1247
- * per-trace ingest-status poll (enqueued / ingested / ready).
1621
+ * Run a one-call delivery diagnostic: config check and a minimal ingest.
1622
+ * `ok` means ingest returned 201 for the smoke trace; confirm it arrived
1623
+ * on the project's Traces page in the Lemma dashboard.
1248
1624
  */
1249
1625
  async debugSmokeTest() {
1250
1626
  const configWarnings = (0, debug_delivery_1.buildConfigWarnings)(this.baseUrl, this.projectId);
@@ -1266,7 +1642,7 @@ var require_client = __commonJS({
1266
1642
  context.output("ok");
1267
1643
  const startedAt = /* @__PURE__ */ new Date();
1268
1644
  const payload = this.stampRelease(context.toPayload(this.projectId, startedAt, /* @__PURE__ */ new Date()));
1269
- const body = JSON.stringify(payload);
1645
+ const body = payloadBody(payload);
1270
1646
  const url = `${this.baseUrl}${debug_delivery_1.INGEST_PATH}`;
1271
1647
  let response;
1272
1648
  try {
@@ -1283,7 +1659,8 @@ var require_client = __commonJS({
1283
1659
  const ingestWarnings = [];
1284
1660
  if (response.status !== debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS) {
1285
1661
  ingestWarnings.push(`expected status ${debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS}, got ${response.status}`);
1286
- const hint = (0, delivery_1.ingestFailureHint)(response.status);
1662
+ const failureBody = await (0, delivery_1.withIngestTimeout)(() => response.text()).catch(() => "");
1663
+ const hint = (0, delivery_1.ingestFailureHint)(response.status, failureBody);
1287
1664
  if (hint)
1288
1665
  hints.push(hint);
1289
1666
  }
@@ -1307,37 +1684,20 @@ var require_client = __commonJS({
1307
1684
  hints
1308
1685
  };
1309
1686
  }
1310
- const ingestStatus = await this.pollIngestStatus(traceId);
1311
- if (ingestStatus === null) {
1312
- hints.push("ingest-status check failed after ingest (status/network)");
1313
- } else if (!(0, debug_delivery_1.isSuccessfulIngestStatus)(ingestStatus)) {
1314
- hints.push(`ingest returned 201 but ingest-status=not_found after ${debug_delivery_1.INGEST_STATUS_POLL_TIMEOUT_MS / 1e3}s \u2014 may be processing lag or downstream issue`);
1315
- }
1687
+ const ok = response.status === debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS;
1688
+ if (ok)
1689
+ hints.push((0, debug_delivery_1.smokeTestConfirmHint)(traceId));
1316
1690
  return {
1317
- ok: response.status === debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS && (0, debug_delivery_1.isSuccessfulIngestStatus)(ingestStatus),
1691
+ ok,
1318
1692
  config,
1319
1693
  ingest,
1320
- ingestStatus: ingestStatus ?? void 0,
1321
1694
  hints
1322
1695
  };
1323
1696
  }
1324
1697
  trace(options = {}, fn) {
1325
1698
  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
- }
1699
+ if (!fn)
1700
+ return this.startTrace(traceOptions, delivery_1.AWAITED_DELIVERY);
1341
1701
  const context = new TraceContext(traceOptions);
1342
1702
  const startedAt = /* @__PURE__ */ new Date();
1343
1703
  (0, debug_mode_1.lemmaDebug)("client", "trace started", {
@@ -1350,16 +1710,63 @@ var require_client = __commonJS({
1350
1710
  result = await fn(context);
1351
1711
  } catch (error) {
1352
1712
  context.fail(error);
1353
- await this.flushTraceAutomatic(context, startedAt, /* @__PURE__ */ new Date());
1713
+ await this.flushTraceAutomatic(context, startedAt, /* @__PURE__ */ new Date(), delivery_1.AWAITED_DELIVERY);
1354
1714
  throw error;
1355
1715
  }
1356
- if (traceOptions.output === void 0) {
1716
+ const held = (0, stream_result_1.holdTraceForStream)(result, context, () => this.flushTraceAutomatic(context, startedAt, /* @__PURE__ */ new Date(), delivery_1.BACKGROUND_DELIVERY));
1717
+ if (held) {
1718
+ this.track(held.sent);
1719
+ return held.stream;
1720
+ }
1721
+ if (!context.hasOutput) {
1357
1722
  context.output(result);
1358
1723
  }
1359
- await this.flushTraceAutomatic(context, startedAt, /* @__PURE__ */ new Date());
1724
+ await this.flushTraceAutomatic(context, startedAt, /* @__PURE__ */ new Date(), delivery_1.AWAITED_DELIVERY);
1360
1725
  return result;
1361
1726
  })();
1362
1727
  }
1728
+ /**
1729
+ * Wait until every trace this client has started sending is delivered or
1730
+ * dropped, including each callback trace whose returned stream is still
1731
+ * being read. Never rejects. A trace handle that hasn't been ended yet is
1732
+ * not waited for.
1733
+ *
1734
+ * Pass it to the runtime so delivery outlives the response:
1735
+ * `ctx.waitUntil(lemma.flush())` on Cloudflare Workers,
1736
+ * `after(() => lemma.flush())` in Next.js. On AWS Lambda, await it before
1737
+ * the handler returns.
1738
+ */
1739
+ async flush() {
1740
+ await Promise.allSettled(Array.from(this.pending));
1741
+ }
1742
+ track(promise) {
1743
+ this.pending.add(promise);
1744
+ const forget = () => this.pending.delete(promise);
1745
+ promise.then(forget, forget);
1746
+ return promise;
1747
+ }
1748
+ /**
1749
+ * A trace handle whose `end()` delivers within `budget`. A caller's
1750
+ * `lemma.trace()` handle uses `AWAITED_DELIVERY`; `startBackgroundTrace()`
1751
+ * uses `BACKGROUND_DELIVERY`.
1752
+ *
1753
+ * @internal
1754
+ */
1755
+ startTrace(options, budget) {
1756
+ const handle = new TraceHandle(options, async (trace, startedAt, endedAt) => {
1757
+ try {
1758
+ await this.flushTraceAutomatic(trace, startedAt, endedAt, budget);
1759
+ } finally {
1760
+ this.traces.delete(trace.id);
1761
+ }
1762
+ });
1763
+ this.traces.set(handle.id, handle);
1764
+ (0, debug_mode_1.lemmaDebug)("client", "trace handle created", {
1765
+ traceId: handle.id,
1766
+ name: options.name ?? "trace"
1767
+ });
1768
+ return handle;
1769
+ }
1363
1770
  /**
1364
1771
  * Deliver a trace you assembled yourself, in a single request.
1365
1772
  *
@@ -1375,13 +1782,15 @@ var require_client = __commonJS({
1375
1782
  * fields do not preserve prior values, and after Lemma processes the trace
1376
1783
  * once, a later re-delivery does not re-run issue extraction (late new span
1377
1784
  * 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.
1785
+ * safe: already-stored span IDs are skipped. Throws an `IngestError` on
1786
+ * a non-2xx response, and never mutates the trace's status, so a failed send
1787
+ * can be retried as-is.
1380
1788
  */
1381
1789
  async ingest(context, options) {
1382
- const failure = await this.sendTrace(context, options.startedAt, options.endedAt ?? /* @__PURE__ */ new Date(), delivery_1.INGEST_STRICT_ATTEMPTS);
1790
+ const failure = await this.sendTrace(context, options.startedAt, options.endedAt ?? /* @__PURE__ */ new Date(), delivery_1.STRICT_DELIVERY);
1383
1791
  if (failure)
1384
1792
  throw failure.error;
1793
+ context.markPayloadFinal();
1385
1794
  }
1386
1795
  recordSpan(options) {
1387
1796
  const context = this.detachedTraceFor(options.traceId, "span");
@@ -1518,53 +1927,6 @@ var require_client = __commonJS({
1518
1927
  ...warnings.length ? { warnings } : {}
1519
1928
  });
1520
1929
  }
1521
- async fetchIngestStatus(otelTraceId) {
1522
- const url = `${this.baseUrl}${debug_delivery_1.INGEST_STATUS_PATH}?project_id=${encodeURIComponent(this.projectId)}&otel_trace_id=${encodeURIComponent(otelTraceId)}`;
1523
- try {
1524
- return await (0, delivery_1.withIngestTimeout)(async (signal) => {
1525
- const response = await this.fetchImpl(url, {
1526
- headers: { ...this.baseHeaders },
1527
- signal
1528
- });
1529
- if (!response.ok)
1530
- return null;
1531
- const data = await response.json();
1532
- return (0, debug_delivery_1.parseIngestStatus)(data.status);
1533
- });
1534
- } catch {
1535
- return null;
1536
- }
1537
- }
1538
- /**
1539
- * Poll ingest-status immediately, then every 1s until success, hard failure,
1540
- * or the 15s timeout.
1541
- */
1542
- async pollIngestStatus(otelTraceId) {
1543
- const deadline = Date.now() + debug_delivery_1.INGEST_STATUS_POLL_TIMEOUT_MS;
1544
- for (; ; ) {
1545
- const status = await this.fetchIngestStatus(otelTraceId);
1546
- if (status === null)
1547
- return null;
1548
- if ((0, debug_delivery_1.isSuccessfulIngestStatus)(status))
1549
- return status;
1550
- const remaining = deadline - Date.now();
1551
- if (remaining <= 0)
1552
- return status;
1553
- await (0, delivery_1.sleep)(Math.min(debug_delivery_1.INGEST_STATUS_POLL_INTERVAL_MS, remaining));
1554
- }
1555
- }
1556
- async verifyIngestDelivery(otelTraceId) {
1557
- const result = await this.pollIngestStatus(otelTraceId);
1558
- if (result === null) {
1559
- (0, debug_mode_1.lemmaDebug)("verify", "ingest accepted (201), ingest-status check failed (status/network)");
1560
- return;
1561
- }
1562
- if ((0, debug_delivery_1.isSuccessfulIngestStatus)(result)) {
1563
- (0, debug_mode_1.lemmaDebug)("verify", `ingest accepted (201), trace ${result === "enqueued" ? "enqueued" : `visible (${result})`} (status=${result})`);
1564
- return;
1565
- }
1566
- (0, debug_mode_1.lemmaDebug)("verify", `ingest accepted (201), ingest-status=not_found after ${debug_delivery_1.INGEST_STATUS_POLL_TIMEOUT_MS / 1e3}s \u2014 may be processing lag or downstream issue`);
1567
- }
1568
1930
  stampRelease(payload) {
1569
1931
  if (this.release)
1570
1932
  payload.trace.release = this.release;
@@ -1576,21 +1938,27 @@ var require_client = __commonJS({
1576
1938
  * {@link Lemma.ingest} sends once and throws, because queue/plugin producers
1577
1939
  * keep their own retry backlog.
1578
1940
  */
1579
- async flushTraceAutomatic(context, startedAt, endedAt) {
1580
- const failure = await this.sendTrace(context, startedAt, endedAt, delivery_1.INGEST_MAX_ATTEMPTS);
1941
+ async flushTraceAutomatic(context, startedAt, endedAt, budget) {
1942
+ const sending = this.sendTrace(context, startedAt, endedAt, budget);
1943
+ context.markPayloadFinal();
1944
+ const failure = await sending;
1581
1945
  if (failure)
1582
1946
  (0, dropped_traces_1.reportDroppedTrace)(context.id, failure.cause);
1583
1947
  }
1948
+ /** {@link Lemma.buildAndSend}, tracked so `flush()` waits for it. */
1949
+ sendTrace(context, startedAt, endedAt, budget) {
1950
+ return this.track(this.buildAndSend(context, startedAt, endedAt, budget));
1951
+ }
1584
1952
  /**
1585
1953
  * Build, send, and check one trace; undefined when it was delivered. A
1586
1954
  * payload that cannot be built comes back as a failure, so strict and
1587
1955
  * automatic delivery handle it once.
1588
1956
  */
1589
- async sendTrace(context, startedAt, endedAt, maxAttempts) {
1957
+ async buildAndSend(context, startedAt, endedAt, budget) {
1590
1958
  const built = this.buildIngestBody(context, startedAt, endedAt);
1591
1959
  if (!built.ok)
1592
1960
  return built;
1593
- const result = await (0, delivery_1.deliver)((signal) => this.postIngest(built.body, signal), { traceId: context.id, projectId: this.projectId }, maxAttempts);
1961
+ const result = await (0, delivery_1.deliver)((signal) => this.postIngest(built.body, signal), { traceId: context.id, projectId: this.projectId }, budget);
1594
1962
  if (!result.ok)
1595
1963
  return result;
1596
1964
  try {
@@ -1607,7 +1975,7 @@ var require_client = __commonJS({
1607
1975
  buildIngestBody(context, startedAt, endedAt) {
1608
1976
  try {
1609
1977
  const payload = this.stampRelease(context.toPayload(this.projectId, startedAt, endedAt));
1610
- const body = JSON.stringify(payload);
1978
+ const body = payloadBody(payload);
1611
1979
  (0, debug_mode_1.lemmaDebug)("client", "sending trace", {
1612
1980
  traceId: payload.trace.id,
1613
1981
  name: payload.trace.name,
@@ -1648,8 +2016,8 @@ var require_client = __commonJS({
1648
2016
  ...responseHeaders,
1649
2017
  ...sentWarnings.length ? { warnings: sentWarnings } : {}
1650
2018
  });
1651
- if ((0, debug_mode_1.isDebugModeEnabled)() && (0, debug_mode_1.isDebugVerifyEnabled)() && payload.trace.id) {
1652
- await this.verifyIngestDelivery(payload.trace.id);
2019
+ if ((0, debug_mode_1.isDebugModeEnabled)() && (0, debug_mode_1.isDebugVerifyEnabled)()) {
2020
+ (0, debug_mode_1.noteDebugVerifyRemovedOnce)();
1653
2021
  }
1654
2022
  }
1655
2023
  };
@@ -1968,6 +2336,7 @@ var require_coding_agent = __commonJS({
1968
2336
  exports.startCodingAgentTurn = startCodingAgentTurn2;
1969
2337
  exports.recordCodingAgentToolStart = recordCodingAgentToolStart2;
1970
2338
  exports.recordCodingAgentToolResult = recordCodingAgentToolResult2;
2339
+ exports.reopenCodingAgentTurn = reopenCodingAgentTurn;
1971
2340
  exports.completeCodingAgentTurn = completeCodingAgentTurn2;
1972
2341
  exports.codingAgentTurnTrace = codingAgentTurnTrace2;
1973
2342
  var node_crypto_1 = __require("node:crypto");
@@ -2062,6 +2431,35 @@ var require_coding_agent = __commonJS({
2062
2431
  tools[existingIndex] = completed;
2063
2432
  return { ...open, tools };
2064
2433
  }
2434
+ function reopenCodingAgentTurn(turn) {
2435
+ if (turn.status === "open")
2436
+ return turn;
2437
+ const response = {
2438
+ generationId: turn.generationId,
2439
+ response: turn.response,
2440
+ model: turn.model,
2441
+ provider: turn.provider,
2442
+ generationStartedAt: turn.generationStartedAt,
2443
+ generationEndedAt: turn.generationEndedAt
2444
+ };
2445
+ const earlierResponses = [...turn.earlierResponses ?? [], response];
2446
+ const base = {
2447
+ version: turn.version,
2448
+ harness: turn.harness,
2449
+ sessionId: turn.sessionId,
2450
+ turnId: turn.turnId,
2451
+ traceId: turn.traceId,
2452
+ generationId: deterministicUuid(`lemma-coding-agent-continuation\0${turn.traceId}\0${earlierResponses.length}`),
2453
+ prompt: turn.prompt,
2454
+ model: turn.model,
2455
+ provider: turn.provider,
2456
+ metadata: turn.metadata,
2457
+ startedAt: turn.startedAt,
2458
+ tools: turn.tools.map(({ resultMissing: _resultMissing, ...tool }) => tool),
2459
+ earlierResponses
2460
+ };
2461
+ return { ...base, status: "open" };
2462
+ }
2065
2463
  function completeCodingAgentTurn2(turn, event) {
2066
2464
  if (turn.status === "completed")
2067
2465
  return turn;
@@ -2120,21 +2518,23 @@ var require_coding_agent = __commonJS({
2120
2518
  }
2121
2519
  });
2122
2520
  }
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
- });
2521
+ for (const response of [...turn.earlierResponses ?? [], turn]) {
2522
+ const timingMissing = response.generationStartedAt === void 0;
2523
+ context.recordGeneration({
2524
+ id: response.generationId,
2525
+ name: `${turn.harness} response`,
2526
+ input: turn.prompt,
2527
+ output: response.response,
2528
+ model: response.model,
2529
+ llmProvider: response.provider,
2530
+ llmInputMessages: [{ role: "user", content: turn.prompt }],
2531
+ llmOutputMessages: [{ role: "assistant", content: response.response }],
2532
+ startedAt: response.generationStartedAt ?? null,
2533
+ endedAt: response.generationEndedAt ?? null,
2534
+ attributes,
2535
+ metadata: timingMissing ? { timing_missing: true } : void 0
2536
+ });
2537
+ }
2138
2538
  return {
2139
2539
  context,
2140
2540
  startedAt: turn.startedAt,
@@ -2144,6 +2544,74 @@ var require_coding_agent = __commonJS({
2144
2544
  }
2145
2545
  });
2146
2546
 
2547
+ // ../../packages/ts/tracing/dist/langchain-context.js
2548
+ var require_langchain_context = __commonJS({
2549
+ "../../packages/ts/tracing/dist/langchain-context.js"(exports) {
2550
+ "use strict";
2551
+ Object.defineProperty(exports, "__esModule", { value: true });
2552
+ exports.ensureLangChainAsyncContext = ensureLangChainAsyncContext;
2553
+ var LANGCHAIN_ASYNC_LOCAL_STORAGE = Symbol.for("ls:tracing_async_local_storage");
2554
+ function ensureLangChainAsyncContext() {
2555
+ const runtime = globalThis;
2556
+ if (runtime[LANGCHAIN_ASYNC_LOCAL_STORAGE] !== void 0)
2557
+ return;
2558
+ const Storage = runtime.AsyncLocalStorage ?? runtime.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage;
2559
+ if (Storage)
2560
+ runtime[LANGCHAIN_ASYNC_LOCAL_STORAGE] = new Storage();
2561
+ }
2562
+ }
2563
+ });
2564
+
2565
+ // ../../packages/ts/tracing/dist/langchain-eviction.js
2566
+ var require_langchain_eviction = __commonJS({
2567
+ "../../packages/ts/tracing/dist/langchain-eviction.js"(exports) {
2568
+ "use strict";
2569
+ Object.defineProperty(exports, "__esModule", { value: true });
2570
+ exports.IdleTraceSweeper = void 0;
2571
+ var DEFAULT_OPEN_TRACE_TTL_MS = 2 * 60 * 60 * 1e3;
2572
+ var DEFAULT_EVICTION_INTERVAL_MS = 5 * 60 * 1e3;
2573
+ var IdleTraceSweeper = class {
2574
+ ttlMs;
2575
+ intervalMs;
2576
+ lastSweepAt = Number.NEGATIVE_INFINITY;
2577
+ constructor({ openTraceTtlMs = DEFAULT_OPEN_TRACE_TTL_MS, evictionIntervalMs = DEFAULT_EVICTION_INTERVAL_MS }) {
2578
+ this.ttlMs = openTraceTtlMs;
2579
+ this.intervalMs = evictionIntervalMs;
2580
+ }
2581
+ /**
2582
+ * Pass each open trace idle past the TTL to `evict`, with one warning that
2583
+ * lists their root run IDs. Runs at most once per interval.
2584
+ */
2585
+ sweep(traces, runs, evict) {
2586
+ if (this.ttlMs === null)
2587
+ return;
2588
+ const now = Date.now();
2589
+ if (now - this.lastSweepAt < this.intervalMs)
2590
+ return;
2591
+ this.lastSweepAt = now;
2592
+ const latestRunStart = /* @__PURE__ */ new Map();
2593
+ for (const run of runs) {
2594
+ const startedAt = run.startedAt.getTime();
2595
+ const seen = latestRunStart.get(run.owningTraceId) ?? 0;
2596
+ if (startedAt > seen)
2597
+ latestRunStart.set(run.owningTraceId, startedAt);
2598
+ }
2599
+ const cutoff = now - this.ttlMs;
2600
+ const stale = Array.from(traces).filter(([id, trace]) => {
2601
+ const lastActivity = Math.max(trace.openedAt.getTime(), trace.latestEnd?.getTime() ?? 0, latestRunStart.get(id) ?? 0);
2602
+ return !trace.ended && lastActivity < cutoff;
2603
+ });
2604
+ if (stale.length === 0)
2605
+ return;
2606
+ 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(", ")}`);
2607
+ for (const [rootRunId, trace] of stale)
2608
+ evict(rootRunId, trace);
2609
+ }
2610
+ };
2611
+ exports.IdleTraceSweeper = IdleTraceSweeper;
2612
+ }
2613
+ });
2614
+
2147
2615
  // ../../packages/ts/tracing/dist/schedule.js
2148
2616
  var require_schedule = __commonJS({
2149
2617
  "../../packages/ts/tracing/dist/schedule.js"(exports) {
@@ -2427,6 +2895,8 @@ var require_langchain = __commonJS({
2427
2895
  exports.langGraph = langGraph;
2428
2896
  var client_1 = require_client();
2429
2897
  var error_message_1 = require_error_message();
2898
+ var langchain_context_1 = require_langchain_context();
2899
+ var langchain_eviction_1 = require_langchain_eviction();
2430
2900
  var schedule_1 = require_schedule();
2431
2901
  var tool_result_1 = require_tool_result();
2432
2902
  var model_1 = require_model();
@@ -2815,20 +3285,6 @@ var require_langchain = __commonJS({
2815
3285
  }
2816
3286
  return messages.length ? messages : void 0;
2817
3287
  }
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
3288
  function providerFromId(id) {
2833
3289
  if (!Array.isArray(id))
2834
3290
  return void 0;
@@ -2968,13 +3424,23 @@ var require_langchain = __commonJS({
2968
3424
  ignore_chain = false;
2969
3425
  ignore_agent = false;
2970
3426
  ignore_retriever = false;
3427
+ /**
3428
+ * Callbacks only record in memory and schedule delivery, so LangChain runs
3429
+ * them inline instead of on its process-wide callback queue (concurrency 1).
3430
+ * A root's end callback has therefore run before `invoke()` resolves, and
3431
+ * `flush()` sees its send.
3432
+ */
3433
+ awaitHandlers = true;
2971
3434
  lemma;
2972
3435
  runs = /* @__PURE__ */ new Map();
2973
3436
  traces = /* @__PURE__ */ new Map();
2974
3437
  pending = /* @__PURE__ */ new Set();
3438
+ idleTraces;
2975
3439
  constructor(options = {}) {
2976
3440
  this.options = options;
3441
+ (0, langchain_context_1.ensureLangChainAsyncContext)();
2977
3442
  this.lemma = options.lemma;
3443
+ this.idleTraces = new langchain_eviction_1.IdleTraceSweeper(options);
2978
3444
  }
2979
3445
  getLemma() {
2980
3446
  this.lemma ??= new client_1.Lemma({
@@ -3043,7 +3509,7 @@ var require_langchain = __commonJS({
3043
3509
  }
3044
3510
  createOwnedTrace(runId, name, input, kind, metadata, tags) {
3045
3511
  const startedAt = /* @__PURE__ */ new Date();
3046
- const handle = this.getLemma().trace({
3512
+ const handle = (0, client_1.startBackgroundTrace)(this.getLemma(), {
3047
3513
  name,
3048
3514
  input: rootTraceInput(input),
3049
3515
  metadata: {
@@ -3134,8 +3600,14 @@ var require_langchain = __commonJS({
3134
3600
  });
3135
3601
  }
3136
3602
  async finalizeTrace(owningTraceId, stored) {
3137
- this.traces.delete(owningTraceId);
3138
- this.forgetTraceRuns(owningTraceId);
3603
+ const ownsRuns = this.traces.get(owningTraceId) === stored;
3604
+ if (ownsRuns)
3605
+ this.traces.delete(owningTraceId);
3606
+ if (!stored.ended && ownsRuns) {
3607
+ (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());
3608
+ }
3609
+ if (ownsRuns)
3610
+ this.forgetTraceRuns(owningTraceId);
3139
3611
  if (stored.ended)
3140
3612
  return;
3141
3613
  stored.ended = true;
@@ -3146,40 +3618,36 @@ var require_langchain = __commonJS({
3146
3618
  endedAt,
3147
3619
  durationMs: durationMs(startedAt, endedAt)
3148
3620
  };
3149
- if (stored.rootError) {
3621
+ if (stored.rootError)
3150
3622
  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
3623
+ const output = stored.rootError ? void 0 : stored.rootOutput;
3624
+ const sent = stored.handle.end(output === void 0 ? timing : { output, ...timing });
3625
+ this.trackPending(sent);
3626
+ await sent;
3627
+ }
3628
+ /** Send the partial trace of each root idle past `openTraceTtlMs`, and forget it. */
3629
+ evictIdleTraces() {
3630
+ this.idleTraces.sweep(this.traces, this.runs.values(), (rootRunId, stored) => {
3631
+ void this.finalizeTrace(rootRunId, stored);
3165
3632
  });
3166
- this.trackPending(promise);
3167
- await promise;
3168
3633
  }
3169
- maybeFinalizeOwner(run, endedAt) {
3634
+ /**
3635
+ * Send an owner's trace on a later macrotask and track it in `pending`.
3636
+ * Callbacks never await delivery, and recordResult(invoke return) can still
3637
+ * stamp usage onto generations whose callback event omitted it.
3638
+ */
3639
+ maybeFinalizeOwner(run) {
3170
3640
  if (!run.ownsTrace)
3171
3641
  return;
3172
3642
  const stored = this.traces.get(run.owningTraceId);
3173
3643
  if (!stored || stored.ended)
3174
3644
  return;
3175
- this.noteBounds(stored, run.startedAt, endedAt);
3176
3645
  const promise = new Promise((resolve2, reject) => {
3177
3646
  (0, schedule_1.scheduleMacrotask)(() => {
3178
3647
  this.finalizeTrace(run.owningTraceId, stored).then(resolve2, reject);
3179
3648
  });
3180
3649
  });
3181
3650
  this.trackPending(promise);
3182
- return promise;
3183
3651
  }
3184
3652
  /**
3185
3653
  * Copy token usage from an `invoke` / chain result onto generation spans
@@ -3198,6 +3666,7 @@ var require_langchain = __commonJS({
3198
3666
  return this.options.agentName ?? serializedName(serialized, fallback);
3199
3667
  }
3200
3668
  handleChainStart(serialized, inputs, runId, parentRunId, tags, metadata, runType, name) {
3669
+ this.evictIdleTraces();
3201
3670
  const startedAt = /* @__PURE__ */ new Date();
3202
3671
  const chainName = name ?? serializedName(serialized, "langchain-chain");
3203
3672
  const parent = this.parentRun(parentRunId);
@@ -3230,7 +3699,7 @@ var require_langchain = __commonJS({
3230
3699
  ownsTrace: false
3231
3700
  });
3232
3701
  }
3233
- async handleChainEnd(outputs, runId) {
3702
+ handleChainEnd(outputs, runId) {
3234
3703
  const run = this.runs.get(runId);
3235
3704
  if (!run)
3236
3705
  return;
@@ -3248,11 +3717,9 @@ var require_langchain = __commonJS({
3248
3717
  }
3249
3718
  }
3250
3719
  this.runs.delete(runId);
3251
- if (run.ownsTrace && stored) {
3252
- await this.finalizeTrace(run.owningTraceId, stored);
3253
- }
3720
+ this.maybeFinalizeOwner(run);
3254
3721
  }
3255
- async handleChainError(error, runId) {
3722
+ handleChainError(error, runId) {
3256
3723
  const run = this.runs.get(runId);
3257
3724
  if (!run)
3258
3725
  return;
@@ -3272,11 +3739,10 @@ var require_langchain = __commonJS({
3272
3739
  }
3273
3740
  }
3274
3741
  this.runs.delete(runId);
3275
- if (run.ownsTrace && stored) {
3276
- await this.finalizeTrace(run.owningTraceId, stored);
3277
- }
3742
+ this.maybeFinalizeOwner(run);
3278
3743
  }
3279
3744
  handleLLMStart(serialized, prompts, runId, parentRunId, extraParams, tags, metadata, _runName) {
3745
+ this.evictIdleTraces();
3280
3746
  const startedAt = /* @__PURE__ */ new Date();
3281
3747
  const attachment = this.resolveAttachment(runId, parentRunId, () => this.createOwnedTrace(runId, this.traceName(serialized, "langchain-llm"), prompts, "llm", metadata, tags));
3282
3748
  if (attachment.ownsTrace) {
@@ -3308,6 +3774,7 @@ var require_langchain = __commonJS({
3308
3774
  });
3309
3775
  }
3310
3776
  handleChatModelStart(serialized, messages, runId, parentRunId, extraParams, tags, metadata, _runName) {
3777
+ this.evictIdleTraces();
3311
3778
  const startedAt = /* @__PURE__ */ new Date();
3312
3779
  const flatMessages = messages.flat();
3313
3780
  const normalized = normalizeMessages(flatMessages);
@@ -3340,15 +3807,7 @@ var require_langchain = __commonJS({
3340
3807
  ownsTrace: attachment.ownsTrace
3341
3808
  });
3342
3809
  }
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) {
3810
+ handleLLMEnd(output, runId) {
3352
3811
  const run = this.runs.get(runId);
3353
3812
  if (!run?.handle)
3354
3813
  return;
@@ -3356,7 +3815,6 @@ var require_langchain = __commonJS({
3356
3815
  const structured = llmStructuredOutput(output);
3357
3816
  const outputMessages = llmOutputMessages(output);
3358
3817
  const softError = (0, tool_result_1.toolResultError)(structured);
3359
- const awaitingTools = !softError && hasToolCalls(structured);
3360
3818
  const model = (0, model_1.pickGenerationModelIdentity)(output);
3361
3819
  this.endStoredRun(run, {
3362
3820
  output: softError ? void 0 : structured,
@@ -3380,33 +3838,10 @@ var require_langchain = __commonJS({
3380
3838
  this.noteRootOutput(stored, structured);
3381
3839
  }
3382
3840
  }
3383
- if (awaitingTools) {
3384
- if (run.ownsTrace)
3385
- run.deferFinalize = true;
3386
- return;
3387
- }
3388
3841
  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);
3842
+ this.maybeFinalizeOwner(run);
3408
3843
  }
3409
- async handleLLMError(error, runId) {
3844
+ handleLLMError(error, runId) {
3410
3845
  const run = this.runs.get(runId);
3411
3846
  if (!run)
3412
3847
  return;
@@ -3425,13 +3860,10 @@ var require_langchain = __commonJS({
3425
3860
  this.noteRootError(stored, message);
3426
3861
  }
3427
3862
  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);
3863
+ this.maybeFinalizeOwner(run);
3433
3864
  }
3434
3865
  handleToolStart(serialized, input, runId, parentRunId, tags, metadata, _runName, _toolCallId) {
3866
+ this.evictIdleTraces();
3435
3867
  const startedAt = /* @__PURE__ */ new Date();
3436
3868
  const attachment = this.resolveAttachment(runId, parentRunId, () => this.createOwnedTrace(runId, this.traceName(serialized, "langchain-tool"), input, "tool", metadata, tags));
3437
3869
  if (attachment.ownsTrace) {
@@ -3459,7 +3891,7 @@ var require_langchain = __commonJS({
3459
3891
  ownsTrace: attachment.ownsTrace
3460
3892
  });
3461
3893
  }
3462
- async handleToolEnd(output, runId) {
3894
+ handleToolEnd(output, runId) {
3463
3895
  const run = this.runs.get(runId);
3464
3896
  if (!run)
3465
3897
  return;
@@ -3490,9 +3922,9 @@ var require_langchain = __commonJS({
3490
3922
  }
3491
3923
  }
3492
3924
  this.runs.delete(runId);
3493
- void this.maybeFinalizeOwner(run, endedAt);
3925
+ this.maybeFinalizeOwner(run);
3494
3926
  }
3495
- async handleToolError(error, runId) {
3927
+ handleToolError(error, runId) {
3496
3928
  const run = this.runs.get(runId);
3497
3929
  if (!run)
3498
3930
  return;
@@ -3511,13 +3943,10 @@ var require_langchain = __commonJS({
3511
3943
  this.noteRootError(stored, message);
3512
3944
  }
3513
3945
  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);
3946
+ this.maybeFinalizeOwner(run);
3519
3947
  }
3520
3948
  handleRetrieverStart(serialized, query, runId, parentRunId, tags, metadata, _name) {
3949
+ this.evictIdleTraces();
3521
3950
  const startedAt = /* @__PURE__ */ new Date();
3522
3951
  const attachment = this.resolveAttachment(runId, parentRunId, () => this.createOwnedTrace(runId, this.traceName(serialized, "langchain-retriever"), query, "retriever", metadata, tags));
3523
3952
  if (attachment.ownsTrace) {
@@ -3543,7 +3972,7 @@ var require_langchain = __commonJS({
3543
3972
  ownsTrace: attachment.ownsTrace
3544
3973
  });
3545
3974
  }
3546
- async handleRetrieverEnd(documents, runId) {
3975
+ handleRetrieverEnd(documents, runId) {
3547
3976
  const run = this.runs.get(runId);
3548
3977
  if (!run)
3549
3978
  return;
@@ -3560,9 +3989,9 @@ var require_langchain = __commonJS({
3560
3989
  this.noteRootOutput(stored, documents);
3561
3990
  }
3562
3991
  this.runs.delete(runId);
3563
- void this.maybeFinalizeOwner(run, endedAt);
3992
+ this.maybeFinalizeOwner(run);
3564
3993
  }
3565
- async handleRetrieverError(error, runId) {
3994
+ handleRetrieverError(error, runId) {
3566
3995
  const run = this.runs.get(runId);
3567
3996
  if (!run)
3568
3997
  return;
@@ -3581,18 +4010,22 @@ var require_langchain = __commonJS({
3581
4010
  this.noteRootError(stored, message);
3582
4011
  }
3583
4012
  this.runs.delete(runId);
3584
- void this.maybeFinalizeOwner(run, endedAt);
4013
+ this.maybeFinalizeOwner(run);
3585
4014
  }
3586
- /** Send completed traces and await ingest delivery. */
4015
+ /**
4016
+ * Await delivery of every trace whose root run already ended. One handler
4017
+ * serves every concurrent run, so a trace whose root is still running stays
4018
+ * open; `shutdown()` sends those.
4019
+ */
3587
4020
  async flush() {
4021
+ await Promise.all(this.pending);
4022
+ }
4023
+ /** Finalize and send every trace, open ones included, and reset state. */
4024
+ async shutdown() {
3588
4025
  await Promise.all([
3589
4026
  ...Array.from(this.traces.entries(), ([id, stored]) => this.finalizeTrace(id, stored)),
3590
4027
  ...Array.from(this.pending)
3591
4028
  ]);
3592
- }
3593
- /** Finalize open traces and reset integration state. */
3594
- async shutdown() {
3595
- await this.flush();
3596
4029
  this.runs.clear();
3597
4030
  this.traces.clear();
3598
4031
  }
@@ -3608,6 +4041,43 @@ var require_langchain = __commonJS({
3608
4041
  }
3609
4042
  });
3610
4043
 
4044
+ // ../../packages/ts/tracing/dist/integration-client.js
4045
+ var require_integration_client = __commonJS({
4046
+ "../../packages/ts/tracing/dist/integration-client.js"(exports) {
4047
+ "use strict";
4048
+ Object.defineProperty(exports, "__esModule", { value: true });
4049
+ exports.integrationClientGetter = integrationClientGetter;
4050
+ exports.resetIntegrationClientErrors = resetIntegrationClientErrors;
4051
+ var client_1 = require_client();
4052
+ var error_message_1 = require_error_message();
4053
+ var reportedIntegrations = /* @__PURE__ */ new Set();
4054
+ function integrationClientGetter(integration, options) {
4055
+ const { lemma: provided, ...clientOptions } = options;
4056
+ let lemma = provided;
4057
+ return () => {
4058
+ if (lemma)
4059
+ return lemma;
4060
+ try {
4061
+ lemma = new client_1.Lemma(clientOptions);
4062
+ } catch (error) {
4063
+ reportClientError(integration, error);
4064
+ }
4065
+ return lemma;
4066
+ };
4067
+ }
4068
+ function reportClientError(integration, error) {
4069
+ if (reportedIntegrations.has(integration))
4070
+ return;
4071
+ reportedIntegrations.add(integration);
4072
+ const cause = (0, error_message_1.describeError)(error).replace(/^@uselemma\/tracing:\s*/, "");
4073
+ 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.`);
4074
+ }
4075
+ function resetIntegrationClientErrors() {
4076
+ reportedIntegrations.clear();
4077
+ }
4078
+ }
4079
+ });
4080
+
3611
4081
  // ../../packages/ts/tracing/dist/mastra.js
3612
4082
  var require_mastra = __commonJS({
3613
4083
  "../../packages/ts/tracing/dist/mastra.js"(exports) {
@@ -3616,7 +4086,10 @@ var require_mastra = __commonJS({
3616
4086
  exports.LemmaMastraExporter = void 0;
3617
4087
  exports.mastra = mastra;
3618
4088
  var client_1 = require_client();
4089
+ var delivery_1 = require_delivery();
4090
+ var dropped_traces_1 = require_dropped_traces();
3619
4091
  var error_message_1 = require_error_message();
4092
+ var integration_client_1 = require_integration_client();
3620
4093
  var schedule_1 = require_schedule();
3621
4094
  var model_1 = require_model();
3622
4095
  var tool_result_1 = require_tool_result();
@@ -3787,26 +4260,26 @@ var require_mastra = __commonJS({
3787
4260
  return fromOutput;
3788
4261
  return (0, usage_1.normalizeTokenUsage)(span.attributes?.usage) ?? (0, usage_1.normalizeTokenUsage)(span.attributes);
3789
4262
  }
4263
+ function nextMacrotask() {
4264
+ return new Promise((resolve2) => (0, schedule_1.scheduleMacrotask)(resolve2));
4265
+ }
3790
4266
  var LemmaMastraExporter = class {
3791
4267
  options;
3792
4268
  name = "lemma";
3793
- lemma;
4269
+ getLemma;
3794
4270
  buffers = /* @__PURE__ */ new Map();
3795
4271
  pending = /* @__PURE__ */ new Set();
3796
4272
  pendingUsage;
3797
4273
  constructor(options = {}) {
3798
4274
  this.options = options;
3799
- this.lemma = options.lemma;
4275
+ this.getLemma = (0, integration_client_1.integrationClientGetter)("LemmaMastraExporter", options);
3800
4276
  }
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;
4277
+ track(promise) {
4278
+ this.pending.add(promise);
4279
+ const settle = () => {
4280
+ this.pending.delete(promise);
4281
+ };
4282
+ promise.then(settle, settle);
3810
4283
  }
3811
4284
  bufferFor(traceId) {
3812
4285
  const existing = this.buffers.get(traceId);
@@ -3890,10 +4363,22 @@ var require_mastra = __commonJS({
3890
4363
  trace.recordSpan(base);
3891
4364
  }
3892
4365
  deliver(root, children) {
4366
+ const lemma = this.getLemma();
4367
+ if (!lemma) {
4368
+ throw new Error(`@uselemma/tracing: trace ${root.traceId} not sent: no client`);
4369
+ }
4370
+ try {
4371
+ return this.send(lemma, root, children);
4372
+ } catch (error) {
4373
+ (0, dropped_traces_1.reportDroppedTrace)(root.traceId, (0, delivery_1.failedBeforeSending)(error).cause);
4374
+ throw error;
4375
+ }
4376
+ }
4377
+ send(lemma, root, children) {
3893
4378
  const startedAt = toDate(root.startTime) ?? /* @__PURE__ */ new Date();
3894
4379
  const endedAt = toDate(root.endTime) ?? /* @__PURE__ */ new Date();
3895
4380
  const recordedIds = new Set(children.map((child) => child.id));
3896
- const trace = this.getLemma().trace({
4381
+ const trace = (0, client_1.startBackgroundTrace)(lemma, {
3897
4382
  id: root.traceId,
3898
4383
  name: this.options.agentName ?? resolveAgentName(root),
3899
4384
  input: rootTraceInput(root.input),
@@ -3920,14 +4405,11 @@ var require_mastra = __commonJS({
3920
4405
  if (rootError) {
3921
4406
  trace.fail(rootError);
3922
4407
  }
3923
- const endPromise = trace.end(rootError ? { durationMs: durationMs(startedAt, endedAt), endedAt } : {
4408
+ return trace.end(rootError ? { durationMs: durationMs(startedAt, endedAt), endedAt } : {
3924
4409
  output: root.output,
3925
4410
  durationMs: durationMs(startedAt, endedAt),
3926
4411
  endedAt
3927
4412
  });
3928
- this.pending.add(endPromise);
3929
- void endPromise.finally(() => this.pending.delete(endPromise));
3930
- return endPromise;
3931
4413
  }
3932
4414
  async exportTracingEvent(event) {
3933
4415
  if (event.type === "span_updated")
@@ -3943,13 +4425,7 @@ var require_mastra = __commonJS({
3943
4425
  const buffer = this.buffers.get(span.traceId);
3944
4426
  const children = buffer?.children ?? [];
3945
4427
  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));
4428
+ this.track(nextMacrotask().then(() => this.deliver(span, children)));
3953
4429
  return;
3954
4430
  }
3955
4431
  this.pushChild(span);
@@ -3962,9 +4438,12 @@ var require_mastra = __commonJS({
3962
4438
  this.pendingUsage = result;
3963
4439
  return 0;
3964
4440
  }
3965
- /** Send completed traces and await ingest delivery. */
4441
+ /**
4442
+ * Send completed traces and await ingest delivery. A trace that could not
4443
+ * be sent was already reported, so it never rejects into the caller.
4444
+ */
3966
4445
  async flush() {
3967
- await Promise.all(Array.from(this.pending));
4446
+ await Promise.allSettled(Array.from(this.pending));
3968
4447
  }
3969
4448
  async shutdown() {
3970
4449
  await this.flush();
@@ -4217,6 +4696,7 @@ var require_openai_agents = __commonJS({
4217
4696
  var openai_agents_containers_1 = require_openai_agents_containers();
4218
4697
  var model_1 = require_model();
4219
4698
  var reply_text_1 = require_reply_text();
4699
+ var serialize_1 = require_serialize();
4220
4700
  var INTEGRATION_ATTRS = {
4221
4701
  "lemma.sdk.integration": "openai-agents"
4222
4702
  };
@@ -4295,8 +4775,8 @@ var require_openai_agents = __commonJS({
4295
4775
  "openai.agents.span_id": span.spanId,
4296
4776
  "openai.agents.parent_id": span.parentId,
4297
4777
  "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))
4778
+ "openai.agents.trace_metadata": span.traceMetadata ? (0, serialize_1.stringifyTraceJson)(span.traceMetadata) : void 0,
4779
+ "openai.agents.span_data": (0, serialize_1.stringifyTraceJson)((0, openai_agents_generation_1.spanDataForAttribute)(span.spanData))
4300
4780
  }).filter(([, value]) => value !== void 0 && value !== null));
4301
4781
  }
4302
4782
  function coerceDate(value) {
@@ -4399,7 +4879,7 @@ var require_openai_agents = __commonJS({
4399
4879
  applyIdentity(existing, trace.groupId, trace.metadata);
4400
4880
  return existing;
4401
4881
  }
4402
- const handle = lemma.trace({
4882
+ const handle = (0, client_1.startBackgroundTrace)(lemma, {
4403
4883
  name: trace.name || "openai-agents-trace",
4404
4884
  metadata: {
4405
4885
  ...options.metadata,
@@ -4577,9 +5057,6 @@ var require_openai_agents = __commonJS({
4577
5057
  ...timing
4578
5058
  });
4579
5059
  }
4580
- async function finalizeAll() {
4581
- await Promise.all(Array.from(traces.entries(), ([traceId, stored]) => finalizeTrace(traceId, stored)));
4582
- }
4583
5060
  return {
4584
5061
  onTraceStart: async (trace) => {
4585
5062
  ensureTrace(trace);
@@ -4610,14 +5087,13 @@ var require_openai_agents = __commonJS({
4610
5087
  endSpan(span);
4611
5088
  },
4612
5089
  recordResult,
4613
- // Shutdown/forceFlush finalize any still-open traces (a one-time terminal
4614
- // send for traces that never received onTraceEnd), then drop them.
5090
+ // The one-time terminal send for traces that never received onTraceEnd.
4615
5091
  shutdown: async () => {
4616
- await finalizeAll();
5092
+ await Promise.all(Array.from(traces.entries(), ([traceId, stored]) => finalizeTrace(traceId, stored)));
4617
5093
  await Promise.all(pending);
4618
5094
  },
4619
5095
  forceFlush: async () => {
4620
- await finalizeAll();
5096
+ await new Promise((resolve2) => (0, schedule_1.scheduleMacrotask)(resolve2));
4621
5097
  await Promise.all(pending);
4622
5098
  }
4623
5099
  };
@@ -4625,33 +5101,81 @@ var require_openai_agents = __commonJS({
4625
5101
  }
4626
5102
  });
4627
5103
 
4628
- // ../../packages/ts/tracing/dist/vercel-ai.js
4629
- var require_vercel_ai = __commonJS({
4630
- "../../packages/ts/tracing/dist/vercel-ai.js"(exports) {
5104
+ // ../../packages/ts/tracing/dist/vercel-ai-events.js
5105
+ var require_vercel_ai_events = __commonJS({
5106
+ "../../packages/ts/tracing/dist/vercel-ai-events.js"(exports) {
4631
5107
  "use strict";
4632
5108
  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();
5109
+ exports.UNKEYED_RUN = void 0;
5110
+ exports.finishReasonError = finishReasonError;
5111
+ exports.eventOutput = eventOutput;
5112
+ exports.generationOutcome = generationOutcome;
5113
+ exports.errorName = errorName;
5114
+ exports.isCallerStop = isCallerStop;
5115
+ exports.reportedError = reportedError;
5116
+ exports.addMs = addMs;
5117
+ exports.subtractMs = subtractMs;
5118
+ exports.isV7StepStart = isV7StepStart;
5119
+ exports.isV7StepEnd = isV7StepEnd;
5120
+ exports.toolOutput = toolOutput2;
5121
+ exports.v6ToolOutput = v6ToolOutput;
5122
+ exports.resolveDurationMs = resolveDurationMs;
5123
+ exports.siblingSystem = siblingSystem;
5124
+ exports.resolveSystemForMessages = resolveSystemForMessages;
5125
+ exports.withSystemMessage = withSystemMessage;
5126
+ exports.v6NormalizedMessages = v6NormalizedMessages;
5127
+ exports.v6Input = v6Input;
5128
+ exports.rootTraceInput = rootTraceInput;
5129
+ exports.eventTraceInput = eventTraceInput;
5130
+ exports.eventMetadata = eventMetadata;
5131
+ exports.readIdentity = readIdentity;
5132
+ exports.eventIdentity = eventIdentity;
5133
+ exports.traceName = traceName;
5134
+ exports.eventUsage = eventUsage;
5135
+ exports.withIntegrationAttrs = withIntegrationAttrs;
5136
+ exports.runKey = runKey;
4637
5137
  var tool_result_1 = require_tool_result();
4638
5138
  var usage_1 = require_usage();
4639
5139
  var INTEGRATION_ATTRS = {
4640
5140
  "lemma.sdk.integration": "vercel-ai"
4641
5141
  };
4642
- var CONCURRENT_REUSE_ERROR = "vercelAI() is already tracing a run. Create a new vercelAI() integration per concurrent AI SDK operation.";
5142
+ var FINISH_REASON_ERROR = 'Model call ended with finishReason "error"';
5143
+ function finishReasonError(event) {
5144
+ return event.finishReason === "error" ? FINISH_REASON_ERROR : void 0;
5145
+ }
5146
+ function eventOutput(event) {
5147
+ return structuredAssistantOutput(event.text, event.content);
5148
+ }
5149
+ function generationOutcome(event) {
5150
+ const kept = event.error == null ? eventOutput(event) : void 0;
5151
+ return {
5152
+ output: kept,
5153
+ llmOutputMessages: kept === void 0 ? void 0 : [{ role: "assistant", content: kept }],
5154
+ error: event.error ?? finishReasonError(event)
5155
+ };
5156
+ }
5157
+ function errorName(value) {
5158
+ return typeof value === "object" && value !== null ? value.name : void 0;
5159
+ }
5160
+ function isCallerStop(error) {
5161
+ const name = errorName(error);
5162
+ return name === "AbortError" || name === "ResponseAborted";
5163
+ }
5164
+ function reportedError(event) {
5165
+ return typeof event === "object" && event !== null && "error" in event ? event.error : event;
5166
+ }
4643
5167
  function addMs(startedAt, durationMs) {
4644
5168
  return typeof durationMs === "number" ? new Date(startedAt.getTime() + durationMs) : /* @__PURE__ */ new Date();
4645
5169
  }
4646
5170
  function subtractMs(endedAt, durationMs) {
4647
5171
  return typeof durationMs === "number" ? new Date(endedAt.getTime() - durationMs) : endedAt;
4648
5172
  }
4649
- function v7StepKey(callId, stepNumber) {
4650
- return `${callId}:${stepNumber}`;
4651
- }
4652
5173
  function isV7StepStart(event) {
4653
5174
  return "callId" in event && "provider" in event && "modelId" in event;
4654
5175
  }
5176
+ function isV7StepEnd(event) {
5177
+ return "callId" in event;
5178
+ }
4655
5179
  function stringifyContent(content) {
4656
5180
  const text = content.map((part) => {
4657
5181
  if (!part || typeof part !== "object")
@@ -4826,17 +5350,21 @@ var require_vercel_ai = __commonJS({
4826
5350
  function eventMetadata(event) {
4827
5351
  return event && "metadata" in event ? event.metadata ?? void 0 : void 0;
4828
5352
  }
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";
5353
+ function readIdentity(sources, options) {
5354
+ return {
5355
+ threadId: lookupString(sources, [options.threadIdKey ?? "threadId"]),
5356
+ userId: lookupString(sources, [options.userIdKey ?? "userId"])
5357
+ };
4834
5358
  }
4835
- function v6Output(event) {
4836
- return structuredAssistantOutput(event.text, event.content);
5359
+ function eventIdentity(event, options) {
5360
+ const runtimeContext = event && "runtimeContext" in event ? event.runtimeContext : void 0;
5361
+ return readIdentity([runtimeContext, eventMetadata(event)], options);
4837
5362
  }
4838
- function endOutput(event) {
4839
- return structuredAssistantOutput(event.text, event.content);
5363
+ function traceName(agentName, event) {
5364
+ if (agentName)
5365
+ return agentName;
5366
+ const functionId = event && "functionId" in event && typeof event.functionId === "string" ? event.functionId : void 0;
5367
+ return functionId || "vercel-ai-agent";
4840
5368
  }
4841
5369
  function eventUsage(event) {
4842
5370
  return (0, usage_1.normalizeTokenUsage)(event.usage) ?? (0, usage_1.normalizeTokenUsage)(event.totalUsage);
@@ -4844,624 +5372,795 @@ var require_vercel_ai = __commonJS({
4844
5372
  function withIntegrationAttrs(attributes) {
4845
5373
  return { ...INTEGRATION_ATTRS, ...attributes ?? {} };
4846
5374
  }
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)
5375
+ exports.UNKEYED_RUN = void 0;
5376
+ function runKey(event) {
5377
+ const callId = typeof event === "object" && event !== null ? event.callId : void 0;
5378
+ return typeof callId === "string" && callId ? callId : exports.UNKEYED_RUN;
5379
+ }
5380
+ }
5381
+ });
5382
+
5383
+ // ../../packages/ts/tracing/dist/vercel-ai-run.js
5384
+ var require_vercel_ai_run = __commonJS({
5385
+ "../../packages/ts/tracing/dist/vercel-ai-run.js"(exports) {
5386
+ "use strict";
5387
+ Object.defineProperty(exports, "__esModule", { value: true });
5388
+ exports.VercelAIRun = exports.CANCELLED_METADATA_KEY = void 0;
5389
+ exports.endableTrace = endableTrace;
5390
+ var client_1 = require_client();
5391
+ var error_message_1 = require_error_message();
5392
+ var schedule_1 = require_schedule();
5393
+ var vercel_ai_events_1 = require_vercel_ai_events();
5394
+ exports.CANCELLED_METADATA_KEY = "lemma.cancelled";
5395
+ function signalOutcome(reason) {
5396
+ return (0, vercel_ai_events_1.errorName)(reason) === "TimeoutError" ? { kind: "failed", error: reason } : { kind: "cancelled", reason };
5397
+ }
5398
+ function outcomeValue(outcome) {
5399
+ if (outcome.kind === "failed")
5400
+ return outcome.error;
5401
+ return outcome.kind === "cancelled" ? outcome.reason : void 0;
5402
+ }
5403
+ function replaces(current, next) {
5404
+ if (current.kind === "cancelled")
5405
+ return false;
5406
+ if (next.kind === "failed")
5407
+ return true;
5408
+ return next.kind === "cancelled" && current.kind === "failed" && current.error === next.reason;
5409
+ }
5410
+ function endableTrace(options) {
5411
+ const trace = options.trace;
5412
+ return trace && typeof trace.end === "function" ? trace : void 0;
5413
+ }
5414
+ var VercelAIRun = class {
5415
+ ctx;
5416
+ startedAt = /* @__PURE__ */ new Date();
5417
+ /** The operation's start event; its system prompt backs later steps. */
5418
+ startEvent;
5419
+ /** AI SDK 7 model call in flight; one at a time per operation. */
5420
+ openModelCall;
5421
+ v7Steps = /* @__PURE__ */ new Map();
5422
+ v6Steps = /* @__PURE__ */ new Map();
5423
+ generationSpanIdsByToolCallId = /* @__PURE__ */ new Map();
5424
+ generationHandlesById = /* @__PURE__ */ new Map();
5425
+ toolExecutions = /* @__PURE__ */ new Map();
5426
+ /** The generation a tool without a known parent nests under. */
5427
+ latestGenerationId;
5428
+ managedTrace;
5429
+ recordedV6Step = false;
5430
+ /** The managed trace's metadata object; the cancelled marker goes here. */
5431
+ runMetadata;
5432
+ /** The latest finished step: a stopped run's partial output. */
5433
+ lastStep;
5434
+ signal;
5435
+ stopWatchingAbort;
5436
+ state = { phase: "active" };
5437
+ /**
5438
+ * The integration's threadId and userId, replaced key by key by the latest
5439
+ * event that carries the call's own: only some events carry them.
5440
+ */
5441
+ identity;
5442
+ constructor(ctx) {
5443
+ this.ctx = ctx;
5444
+ this.identity = (0, vercel_ai_events_1.readIdentity)([ctx.options.metadata], ctx.options);
5445
+ }
5446
+ get phase() {
5447
+ return this.state.phase;
5448
+ }
5449
+ get options() {
5450
+ return this.ctx.options;
5451
+ }
5452
+ /** The caller's trace, or the one this run started. */
5453
+ get rootTrace() {
5454
+ return this.options.trace ?? this.managedTrace;
5455
+ }
5456
+ /** `signal` is the call's, from withAbortSignal(); AI SDK 6 sends its own. */
5457
+ start(event, signal) {
5458
+ this.watchAbort(event.abortSignal ?? signal);
5459
+ this.startEvent = { event, startedAt: /* @__PURE__ */ new Date() };
5460
+ this.resolveTrace(event);
5461
+ }
5462
+ stepStart(event) {
5463
+ if ((0, vercel_ai_events_1.isV7StepStart)(event)) {
5464
+ this.startV7Generation(event);
5465
+ return;
5466
+ }
5467
+ if (this.v6Steps.has(event.stepNumber))
5468
+ return;
5469
+ const stored = this.startV6Generation(event);
5470
+ if (stored)
5471
+ this.v6Steps.set(event.stepNumber, stored);
5472
+ }
5473
+ stepEnd(event) {
5474
+ this.lastStep = event;
5475
+ if ((0, vercel_ai_events_1.isV7StepEnd)(event)) {
5476
+ this.endV7Generation(event);
5477
+ return;
5478
+ }
5479
+ this.recordedV6Step = true;
5480
+ const stored = this.v6Steps.get(event.stepNumber);
5481
+ this.v6Steps.delete(event.stepNumber);
5482
+ this.recordV6Generation(event, stored);
5483
+ }
5484
+ modelCallStart(event) {
5485
+ const trace = this.resolveTrace(event);
5486
+ if (!trace)
5487
+ return;
5488
+ if (this.latestGenerationId) {
5489
+ this.openModelCall = { event, startedAt: /* @__PURE__ */ new Date() };
5490
+ return;
5491
+ }
5492
+ const startedAt = /* @__PURE__ */ new Date();
5493
+ const handle = trace.startGeneration({
5494
+ name: this.generationName({
5495
+ callId: event.callId,
5496
+ provider: event.provider,
5497
+ modelId: event.modelId,
5498
+ content: [],
5499
+ performance: {}
5500
+ }),
5501
+ input: event.messages,
5502
+ metadata: this.options.metadata,
5503
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
5504
+ model: event.modelId,
5505
+ startedAt,
5506
+ llmProvider: event.provider,
5507
+ llmInputMessages: event.messages,
5508
+ llmTools: event.tools
5509
+ });
5510
+ this.openModelCall = { event, startedAt, handle };
5511
+ this.latestGenerationId = handle.id;
5512
+ this.trackGeneration(handle);
5513
+ }
5514
+ modelCallEnd(event) {
5515
+ const stored = this.openModelCall;
5516
+ this.openModelCall = void 0;
5517
+ if (!stored?.handle)
4891
5518
  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
5519
+ const endedAt = /* @__PURE__ */ new Date();
5520
+ const durationMs = (0, vercel_ai_events_1.resolveDurationMs)(stored.startedAt, endedAt, event.performance.responseTimeMs);
5521
+ stored.handle.end({
5522
+ model: event.modelId,
5523
+ durationMs,
5524
+ endedAt: (0, vercel_ai_events_1.addMs)(stored.startedAt, durationMs),
5525
+ llmProvider: event.provider,
5526
+ usage: (0, vercel_ai_events_1.eventUsage)(event),
5527
+ ...(0, vercel_ai_events_1.generationOutcome)(event)
4901
5528
  });
4902
- return lemma;
4903
5529
  }
4904
- function resolveThreadId(metadata) {
4905
- const key = options.threadIdKey ?? "threadId";
4906
- return lookupString([metadata, options.metadata], [key]);
5530
+ toolStart(event) {
5531
+ const trace = this.resolveTrace();
5532
+ if (!trace)
5533
+ return;
5534
+ const parentId = this.resolveToolParentId(event.toolCall.toolCallId);
5535
+ const startedAt = /* @__PURE__ */ new Date();
5536
+ const handle = trace.startTool({
5537
+ name: this.toolSpanName({
5538
+ ...event,
5539
+ toolExecutionMs: void 0,
5540
+ toolOutput: { type: "tool-result" }
5541
+ }),
5542
+ parentId,
5543
+ input: event.toolCall.input,
5544
+ metadata: this.options.metadata,
5545
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
5546
+ startedAt,
5547
+ toolName: event.toolCall.toolName
5548
+ });
5549
+ if (event.toolCall.toolCallId) {
5550
+ this.toolExecutions.set(event.toolCall.toolCallId, {
5551
+ handle,
5552
+ startedAt,
5553
+ parentId
5554
+ });
5555
+ }
4907
5556
  }
4908
- function resolveUserId(metadata) {
4909
- const key = options.userIdKey ?? "userId";
4910
- return lookupString([metadata, options.metadata], [key]);
5557
+ /** AI SDK 7 tool end. */
5558
+ toolEnd(event) {
5559
+ this.endTool(event, {
5560
+ name: this.toolSpanName(event),
5561
+ reportedMs: event.toolExecutionMs,
5562
+ outcome: (0, vercel_ai_events_1.toolOutput)(event)
5563
+ });
4911
5564
  }
4912
- function mergedMetadata(metadata) {
4913
- return {
4914
- ...options.metadata,
4915
- ...metadata ?? {}
4916
- };
5565
+ /** AI SDK 6 tool end. */
5566
+ v6ToolEnd(event) {
5567
+ this.endTool(event, {
5568
+ name: this.toolSpanName(event),
5569
+ reportedMs: event.durationMs,
5570
+ outcome: (0, vercel_ai_events_1.v6ToolOutput)(event)
5571
+ });
4917
5572
  }
4918
- function beginActivity() {
4919
- if (phase === "idle") {
4920
- phase = "active";
4921
- runStartedAt = /* @__PURE__ */ new Date();
5573
+ /** AI SDK 6 terminal event. */
5574
+ finish(event) {
5575
+ if (this.phase === "active" && !this.recordedV6Step) {
5576
+ this.recordV6Generation(event, this.startEvent);
4922
5577
  }
5578
+ this.end(event);
4923
5579
  }
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();
5580
+ /** AI SDK terminal event; one that carries an error fails the run. */
5581
+ end(event) {
5582
+ this.settle(event.error != null ? { kind: "failed", error: event.error } : { kind: "completed", event });
4931
5583
  }
4932
- function hasExplicitEndableTrace() {
4933
- const trace = options.trace;
4934
- return Boolean(trace && typeof trace.end === "function");
5584
+ /** The call's abort signal fired. */
5585
+ abort(reason) {
5586
+ this.settle(signalOutcome(reason));
4935
5587
  }
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);
5588
+ /** A thrown error: a failure, or a stop when it is the caller's abort. */
5589
+ stop(error) {
5590
+ this.settle((0, vercel_ai_events_1.isCallerStop)(error) ? { kind: "cancelled", reason: error } : { kind: "failed", error });
4943
5591
  }
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
- }
5592
+ /**
5593
+ * Stop an AI SDK 6 run whose signal was already aborted, which gets no
5594
+ * terminal event.
5595
+ */
5596
+ stopIfAborted() {
5597
+ if (this.phase === "active" && this.signal?.aborted) {
5598
+ this.abort(this.signal.reason);
4976
5599
  }
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
5600
  }
4984
- function ensureManagedTrace(event) {
4985
- if (options.trace || managedTrace)
5601
+ /** End an unfinished run for shutdown, closing its open spans. */
5602
+ close() {
5603
+ if (this.phase !== "active")
4986
5604
  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
- });
5605
+ this.closeOpenSpans({ endedAt: /* @__PURE__ */ new Date() });
5606
+ this.end({});
5607
+ }
5608
+ /** Send the ended run's trace now; resolves at once for an active run. */
5609
+ deliver() {
5610
+ const { state } = this;
5611
+ if (state.phase === "active")
5612
+ return Promise.resolve();
5613
+ if (state.phase === "sent")
5614
+ return state.sending;
5615
+ if (state.ownedTrace) {
5616
+ this.closeSpansFor(state.outcome, state.timing.endedAt);
5617
+ }
5618
+ this.ctx.release();
5619
+ const sending = Promise.resolve(state.ownedTrace?.end(state.timing));
5620
+ this.state = { phase: "sent", sending };
5621
+ return sending;
4995
5622
  }
4996
- async function endOwnedTrace(event) {
4997
- if (phase === "idle")
5623
+ /**
5624
+ * Record how the run ended. The first outcome ends an active run and
5625
+ * schedules its delivery a macrotask later, so a caller's recordResult()
5626
+ * can still stamp usage on its generations; see replaces() for what may
5627
+ * follow while delivery is pending.
5628
+ */
5629
+ settle(reported) {
5630
+ const { state } = this;
5631
+ const next = state.phase === "active" ? this.bySignal(reported) : reported;
5632
+ this.ctx.claim(outcomeValue(next));
5633
+ this.ctx.claim(outcomeValue(reported));
5634
+ if (state.phase === "sent")
4998
5635
  return;
4999
- if (phase === "ending")
5636
+ if (state.phase === "ending") {
5637
+ if (!replaces(state.outcome, next))
5638
+ return;
5639
+ const replaced = state.outcome;
5640
+ state.outcome = next;
5641
+ this.writeOutcome(next, replaced);
5000
5642
  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
5643
  }
5644
+ this.stopWatchingAbort?.();
5645
+ const endable = endableTrace(this.options);
5646
+ const terminalEvent = next.kind === "completed" ? next.event : void 0;
5647
+ this.noteIdentity(terminalEvent);
5648
+ const ownedTrace = this.options.trace ? endable : this.managedTrace ?? this.startManagedTrace(terminalEvent);
5026
5649
  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)
5650
+ if (!ownedTrace)
5651
+ this.closeSpansFor(next, endedAt);
5652
+ if (this.rootTrace)
5653
+ this.applyIdentity(this.rootTrace);
5654
+ const durationMs = Math.max(0, endedAt.getTime() - this.startedAt.getTime());
5655
+ this.state = {
5656
+ phase: "ending",
5657
+ outcome: next,
5658
+ ownedTrace,
5659
+ // Explicit handles already own startedAt from construction; only pass
5660
+ // durationMs for managed traces started with this run's startedAt.
5661
+ timing: endable ? { endedAt } : { durationMs, endedAt }
5662
+ };
5663
+ this.writeOutcome(next);
5664
+ this.ctx.trackPending(new Promise((resolve2) => (0, schedule_1.scheduleMacrotask)(resolve2)).then(() => this.deliver()));
5665
+ }
5666
+ /**
5667
+ * Write an outcome to the root. Written at once rather than at delivery: a
5668
+ * callback-form context is sent when its callback returns, and a failed
5669
+ * stream never throws there. Output is written only to a trace this run
5670
+ * ends.
5671
+ */
5672
+ writeOutcome(outcome, replaced) {
5673
+ const root = this.rootTrace;
5674
+ if (!root || this.state.phase !== "ending")
5675
+ return;
5676
+ const owned = this.state.ownedTrace !== void 0;
5677
+ switch (outcome.kind) {
5678
+ case "completed": {
5679
+ const { event } = outcome;
5680
+ const failure = (0, vercel_ai_events_1.finishReasonError)(event);
5681
+ if (failure)
5682
+ root.fail(failure);
5683
+ const output = (0, vercel_ai_events_1.eventOutput)(event);
5684
+ if (owned && output !== void 0)
5685
+ root.output(output);
5034
5686
  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
5687
  }
5058
- };
5059
- deliverOwnedTrace = deliver;
5060
- trackPending(new Promise((resolve2, reject) => {
5688
+ case "failed":
5689
+ root.fail((0, error_message_1.describeError)(outcome.error));
5690
+ root.output(void 0);
5691
+ return;
5692
+ case "cancelled":
5693
+ if (replaced?.kind === "failed")
5694
+ root.fail(void 0);
5695
+ if (owned)
5696
+ root.output((0, vercel_ai_events_1.eventOutput)(this.lastStep ?? {}));
5697
+ if (this.runMetadata)
5698
+ this.runMetadata[exports.CANCELLED_METADATA_KEY] = true;
5699
+ return;
5700
+ }
5701
+ }
5702
+ recordResult(result) {
5703
+ return this.rootTrace?.applyGenerationUsage(result) ?? 0;
5704
+ }
5705
+ /**
5706
+ * AI SDK 6 sends no abort callback, and AI SDK 7 never passes the signal to
5707
+ * telemetry, so the run listens to it.
5708
+ */
5709
+ watchAbort(signal) {
5710
+ if (!signal)
5711
+ return;
5712
+ this.signal = signal;
5713
+ if (signal.aborted) {
5714
+ let live = true;
5061
5715
  (0, schedule_1.scheduleMacrotask)(() => {
5062
- deliver().then(resolve2, reject);
5716
+ if (live)
5717
+ this.abort(signal.reason);
5063
5718
  });
5064
- }));
5719
+ this.stopWatchingAbort = () => {
5720
+ live = false;
5721
+ };
5722
+ return;
5723
+ }
5724
+ const onAbort = () => this.abort(signal.reason);
5725
+ signal.addEventListener("abort", onAbort, { once: true });
5726
+ this.stopWatchingAbort = () => signal.removeEventListener("abort", onAbort);
5065
5727
  }
5066
- function recordResult(result) {
5067
- const trace = options.trace ?? managedTrace;
5068
- if (!trace)
5069
- return 0;
5070
- return trace.applyGenerationUsage(result);
5728
+ /**
5729
+ * A failure reported once the call's signal has aborted is the signal's
5730
+ * outcome, whatever value its reason is: AI SDK 7 rethrows the reason, and
5731
+ * reports it before the scheduled stop of a signal aborted at start.
5732
+ */
5733
+ bySignal(reported) {
5734
+ return reported.kind === "failed" && this.signal?.aborted ? signalOutcome(this.signal.reason) : reported;
5735
+ }
5736
+ /**
5737
+ * A stop or failure ends the spans still open, at the time the run ended
5738
+ * rather than when it is delivered; a completion leaves them.
5739
+ */
5740
+ closeSpansFor(outcome, endedAt) {
5741
+ if (outcome.kind === "completed")
5742
+ return;
5743
+ const error = outcome.kind === "failed" ? (0, error_message_1.describeError)(outcome.error) : void 0;
5744
+ this.closeOpenSpans({ error, endedAt });
5745
+ }
5746
+ /** End spans still open when a run stops early, so none is sent open. */
5747
+ closeOpenSpans({ error, endedAt }) {
5748
+ const generations = [
5749
+ ...[...this.v7Steps.values()].map((step) => step.handle),
5750
+ ...[...this.v6Steps.values()].map((step) => step.handle),
5751
+ this.openModelCall?.handle
5752
+ ];
5753
+ for (const handle of generations)
5754
+ handle?.end({ error, endedAt });
5755
+ for (const tool of this.toolExecutions.values()) {
5756
+ tool.handle.end({ endedAt });
5757
+ }
5758
+ }
5759
+ trackGeneration(handle) {
5760
+ this.generationHandlesById.set(handle.id, handle);
5761
+ }
5762
+ coverParent(parentId, endedAt) {
5763
+ if (!parentId)
5764
+ return;
5765
+ this.generationHandlesById.get(parentId)?.ensureEndedAt(endedAt);
5766
+ }
5767
+ noteIdentity(event) {
5768
+ const own = (0, vercel_ai_events_1.eventIdentity)(event, this.options);
5769
+ this.identity = {
5770
+ threadId: own.threadId ?? this.identity.threadId,
5771
+ userId: own.userId ?? this.identity.userId
5772
+ };
5773
+ }
5774
+ applyIdentity(trace) {
5775
+ const { threadId, userId } = this.identity;
5776
+ if (threadId)
5777
+ trace.threadId(threadId);
5778
+ if (userId)
5779
+ trace.userId(userId);
5071
5780
  }
5072
- function recordV6Generation(event, stored) {
5073
- const resolved = resolveTrace(stored?.event);
5074
- if (!resolved)
5781
+ generationName(event) {
5782
+ return typeof this.options.generationName === "function" ? this.options.generationName(event) : this.options.generationName ?? "vercel-ai-generation";
5783
+ }
5784
+ toolSpanName(event) {
5785
+ return typeof this.options.toolName === "function" ? this.options.toolName(event) : this.options.toolName ?? event.toolCall.toolName;
5786
+ }
5787
+ /** Start the run's managed trace; undefined when there is no client. */
5788
+ startManagedTrace(event, input) {
5789
+ const metadata = (0, vercel_ai_events_1.eventMetadata)(event);
5790
+ this.runMetadata = { ...this.options.metadata, ...metadata ?? {} };
5791
+ const lemma = this.ctx.getLemma();
5792
+ this.managedTrace = lemma ? (0, client_1.startBackgroundTrace)(lemma, {
5793
+ name: (0, vercel_ai_events_1.traceName)(this.options.agentName, event),
5794
+ input,
5795
+ metadata: this.runMetadata,
5796
+ threadId: this.identity.threadId,
5797
+ userId: this.identity.userId,
5798
+ startedAt: this.startedAt
5799
+ }) : void 0;
5800
+ return this.managedTrace;
5801
+ }
5802
+ resolveTrace(event) {
5803
+ if (this.phase !== "active")
5804
+ return this.rootTrace;
5805
+ this.noteIdentity(event);
5806
+ if (this.options.trace) {
5807
+ this.applyIdentity(this.options.trace);
5808
+ return this.options.trace;
5809
+ }
5810
+ if (!this.managedTrace) {
5811
+ return this.startManagedTrace(event, (0, vercel_ai_events_1.rootTraceInput)((0, vercel_ai_events_1.eventTraceInput)(event)));
5812
+ }
5813
+ this.applyIdentity(this.managedTrace);
5814
+ const rawInput = (0, vercel_ai_events_1.eventTraceInput)(event);
5815
+ if (rawInput !== void 0) {
5816
+ this.managedTrace.input((0, vercel_ai_events_1.rootTraceInput)(rawInput));
5817
+ }
5818
+ return this.managedTrace;
5819
+ }
5820
+ fallbackSystem() {
5821
+ return (0, vercel_ai_events_1.siblingSystem)(this.startEvent?.event);
5822
+ }
5823
+ recordV6Generation(event, stored) {
5824
+ const trace = this.resolveTrace(stored?.event);
5825
+ if (!trace)
5075
5826
  return;
5076
- const { trace } = resolved;
5077
5827
  const startedAt = stored?.startedAt ?? /* @__PURE__ */ new Date();
5078
5828
  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);
5829
+ const fallbackSystem = this.fallbackSystem();
5085
5830
  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(),
5831
+ name: this.generationName(event),
5832
+ input: stored?.event && (0, vercel_ai_events_1.v6Input)(stored.event, fallbackSystem),
5833
+ metadata: this.options.metadata,
5834
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
5091
5835
  model: event.model.modelId,
5092
5836
  startedAt,
5093
5837
  endedAt,
5094
- durationMs,
5838
+ durationMs: (0, vercel_ai_events_1.resolveDurationMs)(startedAt, endedAt, void 0),
5095
5839
  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 }],
5840
+ llmInputMessages: stored?.event ? (0, vercel_ai_events_1.v6NormalizedMessages)(stored.event, fallbackSystem) : void 0,
5098
5841
  llmTools: stored?.event.tools,
5099
- status: generationError ? "ERROR" : void 0,
5100
- error: generationError,
5101
- usage: eventUsage(event)
5842
+ usage: (0, vercel_ai_events_1.eventUsage)(event),
5843
+ ...(0, vercel_ai_events_1.generationOutcome)(event)
5102
5844
  };
5103
5845
  if (stored?.handle) {
5104
5846
  stored.handle.end(generation);
5105
- latestV6GenerationId = stored.handle.id;
5106
- trackGeneration(stored.handle);
5847
+ this.latestGenerationId = stored.handle.id;
5848
+ this.trackGeneration(stored.handle);
5107
5849
  return;
5108
5850
  }
5109
- trace.recordGeneration({
5110
- id,
5111
- ...generation
5112
- });
5113
- latestV6GenerationId = id;
5851
+ const id = crypto.randomUUID();
5852
+ trace.recordGeneration({ id, ...generation });
5853
+ this.latestGenerationId = id;
5114
5854
  }
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)
5855
+ startV7Generation(event) {
5856
+ const trace = this.resolveTrace(event);
5857
+ if (!trace)
5124
5858
  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
5859
  const startedAt = /* @__PURE__ */ new Date();
5134
- const messages = withSystemMessage(resolveSystemForMessages(event, event.messages, siblingSystem(v6Starts.at(-1)?.event)), event.messages);
5860
+ const messages = (0, vercel_ai_events_1.withSystemMessage)((0, vercel_ai_events_1.resolveSystemForMessages)(event, event.messages, this.fallbackSystem()), event.messages);
5135
5861
  const handle = trace.startGeneration({
5136
- name,
5862
+ name: this.generationName({
5863
+ callId: event.callId,
5864
+ provider: event.provider,
5865
+ modelId: event.modelId,
5866
+ content: [],
5867
+ performance: {}
5868
+ }),
5137
5869
  input: messages,
5138
- metadata: options.metadata,
5139
- attributes: withIntegrationAttrs(),
5870
+ metadata: this.options.metadata,
5871
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
5140
5872
  model: event.modelId,
5141
5873
  startedAt,
5142
5874
  llmProvider: event.provider,
5143
5875
  llmInputMessages: messages,
5144
5876
  llmTools: event.tools
5145
5877
  });
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)
5878
+ this.v7Steps.set(event.stepNumber, { event, startedAt, handle });
5879
+ this.latestGenerationId = handle.id;
5880
+ this.trackGeneration(handle);
5881
+ }
5882
+ startV6Generation(event) {
5883
+ const trace = this.resolveTrace(event);
5884
+ if (!trace)
5154
5885
  return void 0;
5155
- const { trace } = resolved;
5156
5886
  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);
5887
+ const fallbackSystem = this.fallbackSystem();
5163
5888
  const handle = trace.startGeneration({
5164
- name,
5165
- input,
5166
- metadata: options.metadata,
5167
- attributes: withIntegrationAttrs(),
5889
+ name: this.generationName({
5890
+ stepNumber: event.stepNumber,
5891
+ model: event.model
5892
+ }),
5893
+ input: (0, vercel_ai_events_1.v6Input)(event, fallbackSystem),
5894
+ metadata: this.options.metadata,
5895
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
5168
5896
  model: event.model.modelId,
5169
5897
  startedAt,
5170
5898
  llmProvider: event.model.provider,
5171
- llmInputMessages: v6NormalizedMessages(event, fallbackSystem),
5899
+ llmInputMessages: (0, vercel_ai_events_1.v6NormalizedMessages)(event, fallbackSystem),
5172
5900
  llmTools: event.tools
5173
5901
  });
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);
5902
+ this.latestGenerationId = handle.id;
5903
+ this.trackGeneration(handle);
5904
+ return { event, startedAt, handle };
5905
+ }
5906
+ endV7Generation(event) {
5907
+ const stored = this.v7Steps.get(event.stepNumber);
5908
+ this.v7Steps.delete(event.stepNumber);
5182
5909
  if (!stored)
5183
5910
  return;
5184
5911
  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;
5912
+ const durationMs = (0, vercel_ai_events_1.resolveDurationMs)(stored.startedAt, endedAt, event.performance?.stepTimeMs ?? event.performance?.responseTimeMs);
5188
5913
  for (const toolCall of event.toolCalls ?? []) {
5189
5914
  if (toolCall.toolCallId) {
5190
- generationSpanIdsByToolCallId.set(toolCall.toolCallId, stored.handle.id);
5915
+ this.generationSpanIdsByToolCallId.set(toolCall.toolCallId, stored.handle.id);
5191
5916
  }
5192
5917
  }
5193
5918
  stored.handle.end({
5194
- output: generationError ? void 0 : output,
5195
5919
  model: event.model.modelId,
5196
5920
  durationMs,
5197
- endedAt: addMs(stored.startedAt, durationMs),
5921
+ endedAt: (0, vercel_ai_events_1.addMs)(stored.startedAt, durationMs),
5198
5922
  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)
5923
+ usage: (0, vercel_ai_events_1.eventUsage)(event),
5924
+ ...(0, vercel_ai_events_1.generationOutcome)(event)
5203
5925
  });
5204
5926
  }
5205
- function resolveToolParentId(callId, toolCallId) {
5206
- return toolCallId && generationSpanIdsByToolCallId.get(toolCallId) || (callId ? generationSpanIdsByCallId.get(callId) : void 0) || latestV6GenerationId;
5927
+ resolveToolParentId(toolCallId) {
5928
+ return toolCallId && this.generationSpanIdsByToolCallId.get(toolCallId) || this.latestGenerationId;
5207
5929
  }
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);
5214
- }
5215
- }
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;
5223
- }
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
5930
+ endTool(event, { name, reportedMs, outcome }) {
5931
+ const trace = this.resolveTrace();
5932
+ if (!trace)
5933
+ return;
5934
+ const { toolCallId, toolName } = event.toolCall;
5935
+ const storedTool = toolCallId ? this.toolExecutions.get(toolCallId) : void 0;
5936
+ if (toolCallId)
5937
+ this.toolExecutions.delete(toolCallId);
5938
+ if (storedTool) {
5939
+ const endedAt2 = (0, vercel_ai_events_1.addMs)(storedTool.startedAt, reportedMs);
5940
+ const durationMs2 = (0, vercel_ai_events_1.resolveDurationMs)(storedTool.startedAt, endedAt2, reportedMs);
5941
+ const toolEndedAt = (0, vercel_ai_events_1.addMs)(storedTool.startedAt, durationMs2);
5942
+ storedTool.handle.end({
5943
+ durationMs: durationMs2,
5944
+ endedAt: toolEndedAt,
5945
+ toolName,
5946
+ ...outcome
5242
5947
  });
5243
- modelCalls.set(event.callId, { event, startedAt, handle });
5244
- generationSpanIdsByCallId.set(event.callId, handle.id);
5245
- trackGeneration(handle);
5246
- },
5247
- 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
- });
5266
- },
5267
- 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
- }
5295
- },
5296
- onToolCallStart(event) {
5297
- integration.onToolExecutionStart?.(event);
5298
- },
5299
- 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);
5948
+ this.coverParent(storedTool.parentId, toolEndedAt);
5949
+ return;
5950
+ }
5951
+ const endedAt = /* @__PURE__ */ new Date();
5952
+ const durationMs = (0, vercel_ai_events_1.resolveDurationMs)((0, vercel_ai_events_1.subtractMs)(endedAt, reportedMs), endedAt, reportedMs);
5953
+ const parentId = this.resolveToolParentId(toolCallId);
5954
+ trace.recordTool({
5955
+ name,
5956
+ parentId,
5957
+ toolName,
5958
+ input: event.toolCall.input,
5959
+ metadata: this.options.metadata,
5960
+ attributes: (0, vercel_ai_events_1.withIntegrationAttrs)(),
5961
+ durationMs,
5962
+ startedAt: (0, vercel_ai_events_1.subtractMs)(endedAt, durationMs),
5963
+ endedAt,
5964
+ ...outcome
5965
+ });
5966
+ this.coverParent(parentId, endedAt);
5967
+ }
5968
+ };
5969
+ exports.VercelAIRun = VercelAIRun;
5970
+ }
5971
+ });
5972
+
5973
+ // ../../packages/ts/tracing/dist/vercel-ai.js
5974
+ var require_vercel_ai = __commonJS({
5975
+ "../../packages/ts/tracing/dist/vercel-ai.js"(exports) {
5976
+ "use strict";
5977
+ Object.defineProperty(exports, "__esModule", { value: true });
5978
+ exports.CANCELLED_METADATA_KEY = void 0;
5979
+ exports.vercelAI = vercelAI;
5980
+ var integration_client_1 = require_integration_client();
5981
+ var vercel_ai_events_1 = require_vercel_ai_events();
5982
+ var vercel_ai_run_1 = require_vercel_ai_run();
5983
+ var vercel_ai_run_2 = require_vercel_ai_run();
5984
+ Object.defineProperty(exports, "CANCELLED_METADATA_KEY", { enumerable: true, get: function() {
5985
+ return vercel_ai_run_2.CANCELLED_METADATA_KEY;
5986
+ } });
5987
+ 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.";
5988
+ var CALL_EVENT_CALLBACKS = {
5989
+ onStepStart: true,
5990
+ onStepEnd: true,
5991
+ onStepFinish: true,
5992
+ onLanguageModelCallStart: true,
5993
+ onLanguageModelCallEnd: true,
5994
+ onToolExecutionStart: true,
5995
+ onToolCallStart: true,
5996
+ onToolExecutionEnd: true,
5997
+ onToolCallFinish: true,
5998
+ onFinish: true,
5999
+ onEnd: true,
6000
+ onAbort: true,
6001
+ onError: true
6002
+ };
6003
+ function resultCallId(result) {
6004
+ const steps = typeof result === "object" && result !== null ? result.steps : void 0;
6005
+ return Array.isArray(steps) ? (0, vercel_ai_events_1.runKey)(steps[0]) : void 0;
6006
+ }
6007
+ function vercelAI(options = {}) {
6008
+ const getLemma = (0, integration_client_1.integrationClientGetter)("vercelAI()", options);
6009
+ const pending = /* @__PURE__ */ new Set();
6010
+ const runs = /* @__PURE__ */ new Map();
6011
+ let runsOpened = 0;
6012
+ const claims = /* @__PURE__ */ new WeakMap();
6013
+ let lastPrimitiveClaim;
6014
+ let warnedConcurrentV6 = false;
6015
+ function trackPending(delivery) {
6016
+ pending.add(delivery);
6017
+ void delivery.finally(() => pending.delete(delivery));
6018
+ }
6019
+ function newRun(key) {
6020
+ runsOpened += 1;
6021
+ const run = new vercel_ai_run_1.VercelAIRun({
6022
+ options,
6023
+ getLemma,
6024
+ trackPending,
6025
+ release: () => {
6026
+ if (runs.get(key) === run)
6027
+ runs.delete(key);
6028
+ },
6029
+ claim: (value) => {
6030
+ if (typeof value === "object" && value !== null) {
6031
+ claims.set(value, run);
6032
+ } else if (value !== void 0) {
6033
+ lastPrimitiveClaim = { value, run };
6034
+ }
5308
6035
  }
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;
6036
+ });
6037
+ runs.set(key, run);
6038
+ return run;
6039
+ }
6040
+ function openRun(event) {
6041
+ const key = (0, vercel_ai_events_1.runKey)(event);
6042
+ return runs.get(key) ?? newRun(key);
6043
+ }
6044
+ function existingRun(event) {
6045
+ return runs.get((0, vercel_ai_events_1.runKey)(event));
6046
+ }
6047
+ function terminalRun(event) {
6048
+ return existingRun(event) ?? ((0, vercel_ai_run_1.endableTrace)(options) ? newRun((0, vercel_ai_events_1.runKey)(event)) : void 0);
6049
+ }
6050
+ function onlyRunEver() {
6051
+ return runsOpened === 1 ? runs.values().next().value : void 0;
6052
+ }
6053
+ function claimant(value) {
6054
+ if (typeof value === "object" && value !== null)
6055
+ return claims.get(value);
6056
+ const primitive = lastPrimitiveClaim;
6057
+ return primitive && primitive.value === value ? primitive.run : void 0;
6058
+ }
6059
+ function startRun(event, signal) {
6060
+ const key = (0, vercel_ai_events_1.runKey)(event);
6061
+ const current = runs.get(key);
6062
+ current?.stopIfAborted();
6063
+ if (current?.phase === "active") {
6064
+ if (key === vercel_ai_events_1.UNKEYED_RUN && !warnedConcurrentV6) {
6065
+ console.warn(CONCURRENT_V6_WARNING);
6066
+ warnedConcurrentV6 = true;
5320
6067
  }
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);
5338
- },
6068
+ return void 0;
6069
+ }
6070
+ void current?.deliver();
6071
+ const run = newRun(key);
6072
+ run.start(event, signal);
6073
+ return run;
6074
+ }
6075
+ const integration = {
5339
6076
  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);
6077
+ startRun(event);
5345
6078
  },
5346
6079
  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);
6080
+ openRun(event).stepStart(event);
5358
6081
  },
6082
+ // AI SDK 7 sends each step end to onStepEnd and to the deprecated
6083
+ // onStepFinish; the first ends the step's open generation and the second
6084
+ // finds nothing left to end.
5359
6085
  onStepEnd(event) {
5360
- if (phase !== "active" && phase !== "ending")
5361
- return;
5362
- endV7Generation(event);
6086
+ existingRun(event)?.stepEnd(event);
5363
6087
  },
5364
6088
  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);
6089
+ existingRun(event)?.stepEnd(event);
5372
6090
  },
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);
6091
+ onLanguageModelCallStart(event) {
6092
+ openRun(event).modelCallStart(event);
5388
6093
  },
5389
- async onEnd(event) {
5390
- if (phase === "idle") {
5391
- if (!hasExplicitEndableTrace())
5392
- return;
5393
- beginActivity();
5394
- }
5395
- await endOwnedTrace(event);
6094
+ onLanguageModelCallEnd(event) {
6095
+ existingRun(event)?.modelCallEnd(event);
6096
+ },
6097
+ // A tool event with no run in flight trails a run already sent.
6098
+ onToolExecutionStart(event) {
6099
+ existingRun(event)?.toolStart(event);
6100
+ },
6101
+ onToolCallStart(event) {
6102
+ existingRun(event)?.toolStart(event);
6103
+ },
6104
+ onToolExecutionEnd(event) {
6105
+ existingRun(event)?.toolEnd(event);
5396
6106
  },
5397
6107
  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);
6108
+ existingRun(event)?.v6ToolEnd(event);
6109
+ },
6110
+ onFinish(event) {
6111
+ terminalRun(event)?.finish(event);
6112
+ },
6113
+ onEnd(event) {
6114
+ terminalRun(event)?.end(event);
6115
+ },
6116
+ // Neither handler awaits delivery: the AI SDK awaits them before it
6117
+ // closes the stream or rethrows to the caller.
6118
+ onAbort(event) {
6119
+ terminalRun(event)?.abort(event.reason);
6120
+ },
6121
+ onError(event) {
6122
+ openRun(event).stop((0, vercel_ai_events_1.reportedError)(event));
5437
6123
  },
5438
6124
  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();
6125
+ 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));
6126
+ run?.stop(error);
6127
+ await run?.deliver();
5452
6128
  },
5453
- recordResult,
6129
+ recordResult(result) {
6130
+ const key = resultCallId(result);
6131
+ const run = key ? runs.get(key) : runs.get(vercel_ai_events_1.UNKEYED_RUN) ?? onlyRunEver();
6132
+ if (run)
6133
+ return run.recordResult(result);
6134
+ return options.trace?.applyGenerationUsage(result) ?? 0;
6135
+ },
6136
+ // Each ended run's delivery waits a macrotask for its caller's
6137
+ // recordResult(); flushing early would send other requests' runs first.
5454
6138
  async flush() {
5455
- if (deliverOwnedTrace)
5456
- await deliverOwnedTrace();
5457
6139
  await Promise.all(Array.from(pending));
5458
6140
  },
5459
6141
  async shutdown() {
5460
- if (phase === "active") {
5461
- await endOwnedTrace({});
5462
- }
6142
+ for (const run of [...runs.values()])
6143
+ run.close();
5463
6144
  await integration.flush();
5464
- resetRunState();
6145
+ },
6146
+ withAbortSignal(signal) {
6147
+ const opened = /* @__PURE__ */ new Map();
6148
+ const callbacks = {
6149
+ onStart(event) {
6150
+ const run = startRun(event, signal);
6151
+ if (run)
6152
+ opened.set((0, vercel_ai_events_1.runKey)(event), run);
6153
+ }
6154
+ };
6155
+ for (const name of Object.keys(CALL_EVENT_CALLBACKS)) {
6156
+ const callback = integration[name];
6157
+ callbacks[name] = (event) => {
6158
+ if (opened.get((0, vercel_ai_events_1.runKey)(event))?.phase !== "sent") {
6159
+ return callback(event);
6160
+ }
6161
+ };
6162
+ }
6163
+ return callbacks;
5465
6164
  }
5466
6165
  };
5467
6166
  return integration;
@@ -5474,7 +6173,7 @@ var require_dist = __commonJS({
5474
6173
  "../../packages/ts/tracing/dist/index.js"(exports) {
5475
6174
  "use strict";
5476
6175
  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;
6176
+ 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
6177
  var client_1 = require_client();
5479
6178
  Object.defineProperty(exports, "Lemma", { enumerable: true, get: function() {
5480
6179
  return client_1.Lemma;
@@ -5547,6 +6246,10 @@ var require_dist = __commonJS({
5547
6246
  Object.defineProperty(exports, "startCodingAgentTurn", { enumerable: true, get: function() {
5548
6247
  return coding_agent_1.startCodingAgentTurn;
5549
6248
  } });
6249
+ var delivery_1 = require_delivery();
6250
+ Object.defineProperty(exports, "IngestError", { enumerable: true, get: function() {
6251
+ return delivery_1.IngestError;
6252
+ } });
5550
6253
  var release_1 = require_release();
5551
6254
  Object.defineProperty(exports, "normalizeRelease", { enumerable: true, get: function() {
5552
6255
  return release_1.normalizeRelease;
@@ -5604,29 +6307,446 @@ var require_dist = __commonJS({
5604
6307
  // src/adapter.ts
5605
6308
  var import_tracing = __toESM(require_dist(), 1);
5606
6309
 
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";
6310
+ // ../../packages/ts/tracing/src/coding-agent-queue.ts
6311
+ import { randomUUID as randomUUID2 } from "node:crypto";
6312
+ import {
6313
+ chmod,
6314
+ mkdir as mkdir2,
6315
+ readFile as readFile2,
6316
+ rename as rename2,
6317
+ rm as rm2,
6318
+ stat as stat2,
6319
+ unlink as unlink2,
6320
+ writeFile as writeFile2
6321
+ } from "node:fs/promises";
5610
6322
  import { join as join2 } from "node:path";
5611
6323
 
5612
- // src/storage.ts
5613
- import { existsSync, readFileSync } from "node:fs";
6324
+ // ../../packages/ts/tracing/src/coding-agent-backlog.ts
6325
+ import { createHash, randomUUID } from "node:crypto";
5614
6326
  import {
5615
- chmod,
5616
6327
  mkdir,
5617
6328
  readFile,
6329
+ readdir,
5618
6330
  rename,
6331
+ rm,
6332
+ stat,
5619
6333
  unlink,
5620
6334
  writeFile
5621
6335
  } 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.";
6336
+ import { dirname, join } from "node:path";
6337
+
6338
+ // ../../packages/ts/tracing/src/coding-agent-delivery.ts
6339
+ function createDeliveryFetch(fetchImplementation, remainingMilliseconds) {
6340
+ return async (request, init) => {
6341
+ const controller = new AbortController();
6342
+ const signal = init?.signal ? AbortSignal.any([init.signal, controller.signal]) : controller.signal;
6343
+ let timeout;
6344
+ const timedOut = new Promise((_, reject) => {
6345
+ timeout = setTimeout(() => {
6346
+ controller.abort();
6347
+ const error = new Error("Lemma trace delivery timed out");
6348
+ error.name = "TimeoutError";
6349
+ reject(error);
6350
+ }, remainingMilliseconds);
6351
+ });
6352
+ const requestAndBody = (async () => {
6353
+ const response = await fetchImplementation(request, { ...init, signal });
6354
+ if (response.ok || !response.body) return response;
6355
+ const body = await response.arrayBuffer();
6356
+ return new Response(body, {
6357
+ status: response.status,
6358
+ statusText: response.statusText,
6359
+ headers: response.headers
6360
+ });
6361
+ })();
6362
+ try {
6363
+ return await Promise.race([requestAndBody, timedOut]);
6364
+ } finally {
6365
+ if (timeout) clearTimeout(timeout);
6366
+ }
6367
+ };
6368
+ }
6369
+ var TraceDeliveryError = class extends Error {
6370
+ status;
6371
+ constructor(status, cause) {
6372
+ super(
6373
+ status !== void 0 ? `Lemma answered HTTP ${status}` : cause instanceof Error && cause.name === "TimeoutError" ? "the request to Lemma timed out" : "Lemma could not be reached",
6374
+ { cause }
6375
+ );
6376
+ this.name = "TraceDeliveryError";
6377
+ this.status = status;
6378
+ }
6379
+ };
6380
+ function rejectedCredentialStatus(error) {
6381
+ if (!(error instanceof TraceDeliveryError)) return void 0;
6382
+ const { status } = error;
6383
+ return status === 401 || status === 403 ? status : void 0;
6384
+ }
6385
+ async function deliverTrace(fetchImplementation, send) {
6386
+ let status;
6387
+ try {
6388
+ await send(async (request, init) => {
6389
+ const response = await fetchImplementation(request, init);
6390
+ status = response.status;
6391
+ return response;
6392
+ });
6393
+ } catch (error) {
6394
+ throw new TraceDeliveryError(status, error);
6395
+ }
6396
+ }
6397
+
6398
+ // ../../packages/ts/tracing/src/coding-agent-backlog.ts
5625
6399
  function isRecord(value) {
5626
6400
  return typeof value === "object" && value !== null && !Array.isArray(value);
5627
6401
  }
6402
+ async function removeIfPresent(path) {
6403
+ return unlink(path).then(
6404
+ () => true,
6405
+ (error) => {
6406
+ if (error.code === "ENOENT") return false;
6407
+ throw error;
6408
+ }
6409
+ );
6410
+ }
6411
+ async function pendingEntryNames(dataDir) {
6412
+ return readdir(join(dataDir, "pending")).then((entries) => entries.filter((name) => name.endsWith(".json")).sort()).catch((error) => {
6413
+ if (error.code === "ENOENT") return [];
6414
+ throw error;
6415
+ });
6416
+ }
6417
+ var MAX_PENDING_TRACES = 200;
6418
+ var REJECTED_CREDENTIAL_FILE = "last-error.json";
6419
+ var DROPPED_TRACES_DIR = "dropped";
6420
+ var DROP_RECORD = /^dropped\/[0-9]+-[0-9a-f-]+\.json$/;
6421
+ function isRejectedCredential(value) {
6422
+ return isRecord(value) && value.version === 1 && typeof value.credentialId === "string" && (value.status === 401 || value.status === 403) && typeof value.rejectedAt === "string";
6423
+ }
6424
+ function isDroppedTraces(value) {
6425
+ return isRecord(value) && value.version === 1 && typeof value.count === "number";
6426
+ }
6427
+ async function writeState(dataDir, name, value) {
6428
+ const path = join(dataDir, name);
6429
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
6430
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
6431
+ await writeFile(temporaryPath, `${JSON.stringify(value)}
6432
+ `, {
6433
+ encoding: "utf8",
6434
+ mode: 384,
6435
+ flag: "wx"
6436
+ });
6437
+ await rename(temporaryPath, path);
6438
+ }
6439
+ async function readState(dataDir, name, isState) {
6440
+ try {
6441
+ const value = JSON.parse(
6442
+ await readFile(join(dataDir, name), "utf8")
6443
+ );
6444
+ return isState(value) ? value : null;
6445
+ } catch (error) {
6446
+ if (error.code === "ENOENT" || error instanceof SyntaxError) {
6447
+ return null;
6448
+ }
6449
+ throw error;
6450
+ }
6451
+ }
6452
+ async function stopOnRejectedCredential(dataDir, credentialId, error) {
6453
+ const status = rejectedCredentialStatus(error);
6454
+ if (!status) return false;
6455
+ await writeState(dataDir, REJECTED_CREDENTIAL_FILE, {
6456
+ version: 1,
6457
+ credentialId,
6458
+ status,
6459
+ rejectedAt: (/* @__PURE__ */ new Date()).toISOString()
6460
+ });
6461
+ return true;
6462
+ }
6463
+ async function dropOldestPendingEntries(dataDir, limit, options = {}) {
6464
+ const pendingDir = join(dataDir, "pending");
6465
+ const names = await pendingEntryNames(dataDir);
6466
+ if (names.length <= limit) return;
6467
+ const entries = await Promise.all(
6468
+ names.map(async (name) => ({
6469
+ name,
6470
+ modified: await stat(join(pendingDir, name)).then(
6471
+ (entry) => entry.mtimeMs,
6472
+ () => Number.POSITIVE_INFINITY
6473
+ )
6474
+ }))
6475
+ );
6476
+ entries.sort(
6477
+ (a, b) => a.modified - b.modified || a.name.localeCompare(b.name)
6478
+ );
6479
+ for (const { name } of entries.slice(0, entries.length - limit)) {
6480
+ const path = join(pendingDir, name);
6481
+ if (options.onDrop) {
6482
+ const value = await readFile(path, "utf8").then((text) => JSON.parse(text)).catch(() => null);
6483
+ const handled = value === null || await options.onDrop(value).then(
6484
+ () => true,
6485
+ () => false
6486
+ );
6487
+ if (!handled) continue;
6488
+ }
6489
+ if (await removeIfPresent(path)) options.counted?.();
6490
+ }
6491
+ }
6492
+ async function prepareFlush(dataDir, credentialId, options = {}) {
6493
+ const recorded = await readState(
6494
+ dataDir,
6495
+ REJECTED_CREDENTIAL_FILE,
6496
+ isRejectedCredential
6497
+ );
6498
+ const rejected = recorded?.credentialId === credentialId;
6499
+ if (recorded && !rejected) {
6500
+ await rm(join(dataDir, REJECTED_CREDENTIAL_FILE), { force: true });
6501
+ }
6502
+ let dropped = 0;
6503
+ try {
6504
+ await dropOldestPendingEntries(dataDir, MAX_PENDING_TRACES, {
6505
+ onDrop: options.onDrop,
6506
+ counted: () => {
6507
+ dropped += 1;
6508
+ }
6509
+ });
6510
+ } finally {
6511
+ if (dropped > 0) {
6512
+ await writeState(
6513
+ dataDir,
6514
+ `${DROPPED_TRACES_DIR}/${Date.now()}-${randomUUID()}.json`,
6515
+ { version: 1, count: dropped }
6516
+ );
6517
+ }
6518
+ }
6519
+ return rejected ? "rejected" : "ready";
6520
+ }
6521
+ async function readDropRecords(dataDir) {
6522
+ const records = await readdir(join(dataDir, DROPPED_TRACES_DIR)).then(
6523
+ (entries) => entries.map((name) => `${DROPPED_TRACES_DIR}/${name}`).filter((record) => DROP_RECORD.test(record)).sort()
6524
+ ).catch((error) => {
6525
+ if (error.code === "ENOENT") return [];
6526
+ throw error;
6527
+ });
6528
+ const values = await Promise.all(
6529
+ records.map((record) => readState(dataDir, record, isDroppedTraces))
6530
+ );
6531
+ return {
6532
+ count: values.reduce((sum, value) => sum + (value?.count ?? 0), 0),
6533
+ records: records.filter((_record, index) => values[index] !== null)
6534
+ };
6535
+ }
6536
+ async function readSessionStartNotice(dataDir, credentialId, options) {
6537
+ const [rejection, dropped] = await Promise.all([
6538
+ readState(dataDir, REJECTED_CREDENTIAL_FILE, isRejectedCredential),
6539
+ readDropRecords(dataDir)
6540
+ ]);
6541
+ const droppedNote = dropped.count > 0 ? `${dropped.count} older ${dropped.count === 1 ? "trace was" : "traces were"} dropped past the ${MAX_PENDING_TRACES}-trace backlog limit.` : "";
6542
+ if (rejection?.credentialId === credentialId) {
6543
+ return {
6544
+ kind: "rejected",
6545
+ id: `rejected:${rejection.rejectedAt}`,
6546
+ 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}` : ""}`,
6547
+ dropRecords: dropped.records
6548
+ };
6549
+ }
6550
+ if (dropped.count === 0) return null;
6551
+ return {
6552
+ kind: "dropped",
6553
+ id: `dropped:${createHash("sha256").update(dropped.records.join("\n")).digest("hex").slice(0, 16)}`,
6554
+ message: `Lemma could not send ${options.harness} traces for a while: ${droppedNote}`,
6555
+ dropRecords: dropped.records
6556
+ };
6557
+ }
6558
+ async function claimSessionStartNotice(dataDir, notice) {
6559
+ const removed = await Promise.all(
6560
+ notice.dropRecords.filter((record) => DROP_RECORD.test(record)).map((record) => removeIfPresent(join(dataDir, record)))
6561
+ );
6562
+ return notice.kind === "rejected" || removed.some(Boolean);
6563
+ }
6564
+
6565
+ // ../../packages/ts/tracing/src/coding-agent-queue.ts
6566
+ var DEFAULT_FLUSH_TIMEOUT_MS = 1e4;
6567
+ var FLUSH_LOCK_STALE_MS = 3e4;
6568
+ var FLUSH_LOCK_OWNER_FILE = "owner.json";
6569
+ async function readLockOwner(path) {
6570
+ try {
6571
+ const value = JSON.parse(await readFile2(path, "utf8"));
6572
+ if (isRecord(value) && typeof value.pid === "number" && Number.isInteger(value.pid) && value.pid > 0 && typeof value.id === "string" && value.id.length > 0) {
6573
+ return { pid: value.pid, id: value.id };
6574
+ }
6575
+ } catch (error) {
6576
+ if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) {
6577
+ throw error;
6578
+ }
6579
+ }
6580
+ return null;
6581
+ }
6582
+ function processIsRunning(pid) {
6583
+ try {
6584
+ process.kill(pid, 0);
6585
+ return true;
6586
+ } catch (error) {
6587
+ return error.code === "EPERM";
6588
+ }
6589
+ }
6590
+ async function acquireFlushLock(dataDir) {
6591
+ await mkdir2(dataDir, { recursive: true, mode: 448 });
6592
+ const lockPath = join2(dataDir, "flush.lock");
6593
+ const ownerPath = join2(lockPath, FLUSH_LOCK_OWNER_FILE);
6594
+ const owner = { pid: process.pid, id: randomUUID2() };
6595
+ for (let attempt = 0; attempt < 2; attempt += 1) {
6596
+ try {
6597
+ await mkdir2(lockPath, { mode: 448 });
6598
+ await writeFile2(ownerPath, `${JSON.stringify(owner)}
6599
+ `, {
6600
+ encoding: "utf8",
6601
+ mode: 384,
6602
+ flag: "wx"
6603
+ });
6604
+ return async () => {
6605
+ const currentOwner = await readLockOwner(ownerPath);
6606
+ if (currentOwner?.id === owner.id) {
6607
+ await rm2(lockPath, { recursive: true, force: true });
6608
+ }
6609
+ };
6610
+ } catch (error) {
6611
+ if (error.code !== "EEXIST") throw error;
6612
+ if (attempt > 0) return null;
6613
+ const currentOwner = await readLockOwner(ownerPath);
6614
+ if (currentOwner && processIsRunning(currentOwner.pid)) return null;
6615
+ const lockStat = await stat2(lockPath).catch((statError) => {
6616
+ if (statError.code === "ENOENT") return null;
6617
+ throw statError;
6618
+ });
6619
+ if (lockStat && Date.now() - lockStat.mtimeMs <= FLUSH_LOCK_STALE_MS) {
6620
+ return null;
6621
+ }
6622
+ const quarantinePath = join2(dataDir, `flush.lock.stale-${randomUUID2()}`);
6623
+ try {
6624
+ await rename2(lockPath, quarantinePath);
6625
+ } catch (claimError) {
6626
+ if (claimError.code === "ENOENT") {
6627
+ return null;
6628
+ }
6629
+ throw claimError;
6630
+ }
6631
+ await rm2(quarantinePath, { recursive: true, force: true });
6632
+ }
6633
+ }
6634
+ return null;
6635
+ }
6636
+ function isPendingTurn(value, harness) {
6637
+ 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";
6638
+ }
6639
+ async function writePendingTurn(dataDir, turn, scope) {
6640
+ const pendingDir = join2(dataDir, "pending");
6641
+ await mkdir2(pendingDir, { recursive: true, mode: 448 });
6642
+ if (process.platform !== "win32") await chmod(pendingDir, 448);
6643
+ const path = join2(
6644
+ pendingDir,
6645
+ `${turn.endedAt.replaceAll(/[^0-9]/g, "")}-${turn.traceId}-${randomUUID2()}.json`
6646
+ );
6647
+ const temporaryPath = `${path}.${process.pid}.${randomUUID2()}.tmp`;
6648
+ const pending = {
6649
+ version: 1,
6650
+ apiUrl: scope.apiUrl,
6651
+ projectId: scope.projectId,
6652
+ credentialId: scope.credentialId,
6653
+ turn
6654
+ };
6655
+ await writeFile2(temporaryPath, `${JSON.stringify(pending)}
6656
+ `, {
6657
+ encoding: "utf8",
6658
+ mode: 384,
6659
+ flag: "wx"
6660
+ });
6661
+ if (process.platform !== "win32") await chmod(temporaryPath, 384);
6662
+ await rename2(temporaryPath, path);
6663
+ }
6664
+ async function flushPendingTurns(options) {
6665
+ const now = options.now ?? Date.now;
6666
+ const pendingDir = join2(options.dataDir, "pending");
6667
+ let sent = 0;
6668
+ const attempted = /* @__PURE__ */ new Set();
6669
+ while (true) {
6670
+ const releaseLock = await acquireFlushLock(options.dataDir);
6671
+ if (!releaseLock) return sent;
6672
+ try {
6673
+ const credentials = await options.credentials();
6674
+ if (!credentials) return sent;
6675
+ if (await prepareFlush(options.dataDir, credentials.credentialId) === "rejected") {
6676
+ return sent;
6677
+ }
6678
+ for (const name of (await pendingEntryNames(options.dataDir)).filter(
6679
+ (entry) => !attempted.has(entry)
6680
+ )) {
6681
+ const remainingMilliseconds = options.deadline - now();
6682
+ if (remainingMilliseconds <= 0) return sent;
6683
+ attempted.add(name);
6684
+ const path = join2(pendingDir, name);
6685
+ const pending = await readFile2(path, "utf8").then((text) => JSON.parse(text)).catch(() => null);
6686
+ if (!isPendingTurn(pending, options.harness)) {
6687
+ options.retained(name, { kind: "invalid" });
6688
+ continue;
6689
+ }
6690
+ if (pending.apiUrl !== credentials.apiUrl || pending.projectId !== credentials.projectId) {
6691
+ options.retained(name, { kind: "otherProject" });
6692
+ continue;
6693
+ }
6694
+ try {
6695
+ await options.send(pending.turn, credentials, remainingMilliseconds);
6696
+ await unlink2(path);
6697
+ sent += 1;
6698
+ } catch (error) {
6699
+ options.retained(name, { kind: "failed", error });
6700
+ if (await stopOnRejectedCredential(
6701
+ options.dataDir,
6702
+ credentials.credentialId,
6703
+ error
6704
+ )) {
6705
+ return sent;
6706
+ }
6707
+ }
6708
+ }
6709
+ } finally {
6710
+ await releaseLock();
6711
+ }
6712
+ const remaining = await pendingEntryNames(options.dataDir);
6713
+ if (!remaining.some((entry) => !attempted.has(entry))) return sent;
6714
+ }
6715
+ }
6716
+ function retainedReason(error) {
6717
+ if (error instanceof SyntaxError) return "the queued trace is not valid JSON";
6718
+ return error instanceof Error ? error.message : String(error);
6719
+ }
6720
+ function describeRetained(reason) {
6721
+ switch (reason.kind) {
6722
+ case "invalid":
6723
+ return "it is not a valid queued trace";
6724
+ case "otherProject":
6725
+ return "it belongs to another Lemma project";
6726
+ case "failed":
6727
+ return retainedReason(reason.error);
6728
+ }
6729
+ }
6730
+
6731
+ // src/storage.ts
6732
+ import { existsSync, readFileSync } from "node:fs";
6733
+ import {
6734
+ chmod as chmod2,
6735
+ mkdir as mkdir3,
6736
+ readFile as readFile3,
6737
+ rename as rename3,
6738
+ unlink as unlink3,
6739
+ writeFile as writeFile3
6740
+ } from "node:fs/promises";
6741
+ import { homedir } from "node:os";
6742
+ import { dirname as dirname2, join as join3, resolve } from "node:path";
6743
+ var LEMMA_OPENCODE_SETUP_COMMAND = "pnpm dlx @uselemma/opencode setup";
6744
+ var LEMMA_OPENCODE_CREDENTIALS_HELP = `Lemma OpenCode credentials are missing or invalid. Run \`${LEMMA_OPENCODE_SETUP_COMMAND}\` to connect or rotate the scoped credential.`;
6745
+ function isRecord2(value) {
6746
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6747
+ }
5628
6748
  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;
6749
+ 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
6750
  }
5631
6751
  function resolveConfigDir(options = {}) {
5632
6752
  if (options.configDir) return resolve(options.configDir);
@@ -5635,13 +6755,13 @@ function resolveConfigDir(options = {}) {
5635
6755
  if (configured) return resolve(configured);
5636
6756
  const home = options.homeDir ?? homedir();
5637
6757
  const xdgConfigHome = env.XDG_CONFIG_HOME?.trim();
5638
- return xdgConfigHome ? join(resolve(xdgConfigHome), "opencode") : join(resolve(home), ".config", "opencode");
6758
+ return xdgConfigHome ? join3(resolve(xdgConfigHome), "opencode") : join3(resolve(home), ".config", "opencode");
5639
6759
  }
5640
6760
  function defaultDataDir(options) {
5641
- return join(resolveConfigDir(options), "lemma");
6761
+ return join3(resolveConfigDir(options), "lemma");
5642
6762
  }
5643
6763
  function dataDirLocationPath(options) {
5644
- return join(defaultDataDir(options), "data-dir-location.json");
6764
+ return join3(defaultDataDir(options), "data-dir-location.json");
5645
6765
  }
5646
6766
  function resolveDataDir(options = {}) {
5647
6767
  if (options.dataDir) return resolve(options.dataDir);
@@ -5653,7 +6773,7 @@ function resolveDataDir(options = {}) {
5653
6773
  const value = JSON.parse(
5654
6774
  readFileSync(dataDirLocationPath(options), "utf8")
5655
6775
  );
5656
- if (isRecord(value) && value.version === 1 && typeof value.dataDir === "string" && value.dataDir.trim().length > 0) {
6776
+ if (isRecord2(value) && value.version === 1 && typeof value.dataDir === "string" && value.dataDir.trim().length > 0) {
5657
6777
  return resolve(value.dataDir);
5658
6778
  }
5659
6779
  } catch (error) {
@@ -5662,12 +6782,12 @@ function resolveDataDir(options = {}) {
5662
6782
  return fallback;
5663
6783
  }
5664
6784
  function credentialsPath(options = {}) {
5665
- return join(resolveDataDir(options), "credentials.json");
6785
+ return join3(resolveDataDir(options), "credentials.json");
5666
6786
  }
5667
6787
  async function readCredentials(options = {}) {
5668
6788
  try {
5669
6789
  const value = JSON.parse(
5670
- await readFile(credentialsPath(options), "utf8")
6790
+ await readFile3(credentialsPath(options), "utf8")
5671
6791
  );
5672
6792
  if (!isCredentials(value)) throw new Error(LEMMA_OPENCODE_CREDENTIALS_HELP);
5673
6793
  return value;
@@ -5681,36 +6801,8 @@ async function readCredentials(options = {}) {
5681
6801
  }
5682
6802
 
5683
6803
  // 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);
6804
+ async function writePendingTurn2(turn, scope, options = {}) {
6805
+ await writePendingTurn(resolveDataDir(options), turn, scope);
5714
6806
  return true;
5715
6807
  }
5716
6808
 
@@ -5761,7 +6853,7 @@ var PEM_BLOCK = /-----BEGIN [A-Z0-9 ]*(?:PRIVATE KEY|CERTIFICATE)-----[\s\S]*?(?
5761
6853
  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
6854
  var JWT_TOKEN = /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\b/g;
5763
6855
  var CREDENTIAL_BEARING_URL = /\b([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/:@]+:[^\s/@]+@/gi;
5764
- function isRecord2(value) {
6856
+ function isRecord3(value) {
5765
6857
  return typeof value === "object" && value !== null && !Array.isArray(value);
5766
6858
  }
5767
6859
  function normalizedKey(key) {
@@ -5785,7 +6877,7 @@ function sanitizeValue(value, depth = 0) {
5785
6877
  if (Array.isArray(value)) {
5786
6878
  return value.slice(0, 200).map((item) => sanitizeValue(item, depth + 1));
5787
6879
  }
5788
- if (!isRecord2(value)) return String(value).slice(0, 2e4);
6880
+ if (!isRecord3(value)) return String(value).slice(0, 2e4);
5789
6881
  const sanitized = {};
5790
6882
  for (const [key, item] of Object.entries(value).slice(0, 200)) {
5791
6883
  if (isSensitiveKey(key)) continue;
@@ -5898,7 +6990,7 @@ function createOpenCodeAdapter(dependencies) {
5898
6990
  const finalizingTurns = /* @__PURE__ */ new Map();
5899
6991
  const now = dependencies.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
5900
6992
  const scheduleFlush = dependencies.scheduleFlush ?? (() => void 0);
5901
- const writePending = dependencies.writePending ?? writePendingTurn;
6993
+ const writePending = dependencies.writePending ?? writePendingTurn2;
5902
6994
  const warn = dependencies.warn ?? ((message) => console.warn(message));
5903
6995
  async function sessionMessages(sessionId) {
5904
6996
  const result = await dependencies.client.session.messages({
@@ -6098,53 +7190,11 @@ function createOpenCodeAdapter(dependencies) {
6098
7190
 
6099
7191
  // src/flush.ts
6100
7192
  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
7193
 
6144
7194
  // package.json
6145
7195
  var package_default = {
6146
7196
  name: "@uselemma/opencode",
6147
- version: "0.1.3",
7197
+ version: "0.2.1",
6148
7198
  description: "Lemma SDK tracing for OpenCode coding-agent sessions",
6149
7199
  license: "MIT",
6150
7200
  author: "Lemma",
@@ -6189,12 +7239,12 @@ var package_default = {
6189
7239
  prepublishOnly: "pnpm run type-check && pnpm run build"
6190
7240
  },
6191
7241
  dependencies: {
6192
- "@opencode-ai/plugin": "1.18.19",
6193
- "@uselemma/tracing": "workspace:^"
7242
+ "@opencode-ai/plugin": "1.18.19"
6194
7243
  },
6195
7244
  devDependencies: {
6196
7245
  "@opencode-ai/sdk": "1.18.19",
6197
7246
  "@types/node": "^22.18.8",
7247
+ "@uselemma/tracing": "workspace:^",
6198
7248
  esbuild: "^0.25.11",
6199
7249
  typescript: "^5.9.3",
6200
7250
  vitest: "^3.2.4"
@@ -6205,145 +7255,53 @@ var package_default = {
6205
7255
  var PLUGIN_USER_AGENT = `${package_default.name}/${package_default.version}`;
6206
7256
 
6207
7257
  // 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
- });
7258
+ async function startupNotice(options = {}) {
7259
+ const dataDir = resolveDataDir(options);
7260
+ const credentials = await readCredentials({ ...options, dataDir });
7261
+ if (!credentials) return null;
7262
+ const notice = await readSessionStartNotice(
7263
+ dataDir,
7264
+ credentials.credentialId,
7265
+ { harness: "OpenCode", setupCommand: LEMMA_OPENCODE_SETUP_COMMAND }
7266
+ );
7267
+ if (!notice || !await claimSessionStartNotice(dataDir, notice)) return null;
7268
+ return notice.message;
6286
7269
  }
6287
- async function flushPendingTurns(options = {}) {
7270
+ async function flushPendingTurns2(options = {}) {
6288
7271
  const dataDir = resolveDataDir(options);
6289
7272
  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 {
7273
+ return flushPendingTurns({
7274
+ dataDir,
7275
+ harness: "opencode",
7276
+ now,
7277
+ deadline: options.deadline ?? now() + (options.timeoutMilliseconds ?? DEFAULT_FLUSH_TIMEOUT_MS),
7278
+ credentials: async () => {
6297
7279
  const credentials = await readCredentials({ ...options, dataDir });
6298
7280
  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;
7281
+ return credentials;
7282
+ },
7283
+ send: async (turn, credentials, remainingMilliseconds) => {
7284
+ const trace = (0, import_tracing2.codingAgentTurnTrace)(turn);
7285
+ await deliverTrace(
7286
+ createDeliveryFetch(options.fetch ?? fetch, remainingMilliseconds),
7287
+ (deliveryFetch) => new import_tracing2.Lemma({
7288
+ apiKey: credentials.accessToken,
7289
+ projectId: credentials.projectId,
7290
+ baseUrl: credentials.apiUrl,
7291
+ fetch: deliveryFetch,
7292
+ userAgent: PLUGIN_USER_AGENT
7293
+ }).ingest(trace.context, {
7294
+ startedAt: new Date(trace.startedAt),
7295
+ endedAt: new Date(trace.endedAt)
7296
+ })
7297
+ );
7298
+ },
7299
+ retained: (name, reason) => {
7300
+ options.warn?.(
7301
+ `Lemma OpenCode retained a trace for retry (${name}): ${describeRetained(reason)}.`
7302
+ );
6345
7303
  }
6346
- }
7304
+ });
6347
7305
  }
6348
7306
 
6349
7307
  // src/plugin-entry.ts
@@ -6358,7 +7316,7 @@ var LemmaPlugin = async ({ client, directory }) => {
6358
7316
  flushPromise = (async () => {
6359
7317
  do {
6360
7318
  flushRequested = false;
6361
- await flushPendingTurns({ warn, deadline });
7319
+ await flushPendingTurns2({ warn, deadline });
6362
7320
  } while (flushRequested && !disposing);
6363
7321
  })().catch((error) => {
6364
7322
  console.warn(
@@ -6379,6 +7337,11 @@ var LemmaPlugin = async ({ client, directory }) => {
6379
7337
  scheduleFlush
6380
7338
  });
6381
7339
  scheduleFlush();
7340
+ void startupNotice().then(async (message) => {
7341
+ if (!message) return;
7342
+ const result = await client.tui?.showToast({ body: { message, variant: "warning" } }).catch(() => void 0);
7343
+ if (result?.data !== true) warn(message);
7344
+ }).catch(() => void 0);
6382
7345
  return {
6383
7346
  "chat.message": async (_input, output) => {
6384
7347
  await adapter.chatMessage(output.message, output.parts);